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.

6750 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
  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 expr14="expr14" 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': 'expr14',
  104. 'selector': '[expr14]',
  105. 'template': template(
  106. '<ul><li expr15="expr15"></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': 'expr15',
  135. 'selector': '[expr15]',
  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 expr0="expr0" 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 expr1="expr1" class="button"></button><button expr2="expr2" 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': 'expr0',
  239. 'selector': '[expr0]',
  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': 'expr1',
  267. 'selector': '[expr1]',
  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': 'expr2',
  281. 'selector': '[expr2]',
  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. this.elements = this.form.querySelectorAll('field-error'); // adding submit event
  1825. this.form.addEventListener('submit', function (event) {
  1826. _this.onSubmit(event);
  1827. }); // adding event if a element is updated
  1828. this.form.addEventListener('field-update', function (event) {
  1829. _this.onFieldUpdate(event);
  1830. });
  1831. this.onSuccess = onSuccess;
  1832. }
  1833. /**
  1834. *
  1835. * @param {[type]} event [description]
  1836. * @return {[type]} [description]
  1837. */
  1838. _createClass(FormValidator, [{
  1839. key: "onSubmit",
  1840. value: function onSubmit(event) {
  1841. var _this2 = this;
  1842. event.preventDefault();
  1843. var errors = validate_js__WEBPACK_IMPORTED_MODULE_0___default()(form_serialize__WEBPACK_IMPORTED_MODULE_1___default()(event.target, {
  1844. hash: true
  1845. }), this.constraits, {
  1846. fullMessages: false
  1847. });
  1848. if (errors) {
  1849. // send each element a event
  1850. this.elements.forEach(function (element) {
  1851. var elementErrors = false; // check for errors by name
  1852. if (errors[element.attributes.name.nodeValue]) {
  1853. elementErrors = errors[element.attributes.name.nodeValue];
  1854. }
  1855. _this2.dispatchCustomEvent(elementErrors, element);
  1856. });
  1857. } else {
  1858. this.onSuccess(event, form_serialize__WEBPACK_IMPORTED_MODULE_1___default()(event.target, {
  1859. hash: true
  1860. }));
  1861. }
  1862. }
  1863. /**
  1864. *
  1865. *
  1866. * @param {Event} event
  1867. *
  1868. */
  1869. }, {
  1870. key: "onFieldUpdate",
  1871. value: function onFieldUpdate(event) {
  1872. var _this3 = this;
  1873. // workaround, make sure that value for single is undefined if it is empty
  1874. if (event.detail.value == '') {
  1875. event.detail.value = undefined;
  1876. }
  1877. 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
  1878. this.elements.forEach(function (element) {
  1879. if (element.attributes.name.nodeValue == event.detail.name) {
  1880. _this3.dispatchCustomEvent(errors, element);
  1881. }
  1882. });
  1883. }
  1884. /**
  1885. * dispatch event to single element
  1886. *
  1887. * @param {Array} errors
  1888. * @param {Element} element
  1889. *
  1890. */
  1891. }, {
  1892. key: "dispatchCustomEvent",
  1893. value: function dispatchCustomEvent(errors, element) {
  1894. var detail = false;
  1895. if (errors) {
  1896. detail = errors;
  1897. }
  1898. var formValidationEvent = new CustomEvent('form-validation', {
  1899. 'detail': detail
  1900. });
  1901. element.dispatchEvent(formValidationEvent);
  1902. }
  1903. }]);
  1904. return FormValidator;
  1905. }();
  1906. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (FormValidator);
  1907. /***/ }),
  1908. /***/ "./node_modules/form-serialize/index.js":
  1909. /*!**********************************************!*\
  1910. !*** ./node_modules/form-serialize/index.js ***!
  1911. \**********************************************/
  1912. /***/ ((module) => {
  1913. // get successful control from form and assemble into object
  1914. // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
  1915. // types which indicate a submit action and are not successful controls
  1916. // these will be ignored
  1917. var k_r_submitter = /^(?:submit|button|image|reset|file)$/i;
  1918. // node names which could be successful controls
  1919. var k_r_success_contrls = /^(?:input|select|textarea|keygen)/i;
  1920. // Matches bracket notation.
  1921. var brackets = /(\[[^\[\]]*\])/g;
  1922. // serializes form fields
  1923. // @param form MUST be an HTMLForm element
  1924. // @param options is an optional argument to configure the serialization. Default output
  1925. // with no options specified is a url encoded string
  1926. // - hash: [true | false] Configure the output type. If true, the output will
  1927. // be a js object.
  1928. // - serializer: [function] Optional serializer function to override the default one.
  1929. // The function takes 3 arguments (result, key, value) and should return new result
  1930. // hash and url encoded str serializers are provided with this module
  1931. // - disabled: [true | false]. If true serialize disabled fields.
  1932. // - empty: [true | false]. If true serialize empty fields
  1933. function serialize(form, options) {
  1934. if (typeof options != 'object') {
  1935. options = { hash: !!options };
  1936. }
  1937. else if (options.hash === undefined) {
  1938. options.hash = true;
  1939. }
  1940. var result = (options.hash) ? {} : '';
  1941. var serializer = options.serializer || ((options.hash) ? hash_serializer : str_serialize);
  1942. var elements = form && form.elements ? form.elements : [];
  1943. //Object store each radio and set if it's empty or not
  1944. var radio_store = Object.create(null);
  1945. for (var i=0 ; i<elements.length ; ++i) {
  1946. var element = elements[i];
  1947. // ingore disabled fields
  1948. if ((!options.disabled && element.disabled) || !element.name) {
  1949. continue;
  1950. }
  1951. // ignore anyhting that is not considered a success field
  1952. if (!k_r_success_contrls.test(element.nodeName) ||
  1953. k_r_submitter.test(element.type)) {
  1954. continue;
  1955. }
  1956. var key = element.name;
  1957. var val = element.value;
  1958. // we can't just use element.value for checkboxes cause some browsers lie to us
  1959. // they say "on" for value when the box isn't checked
  1960. if ((element.type === 'checkbox' || element.type === 'radio') && !element.checked) {
  1961. val = undefined;
  1962. }
  1963. // If we want empty elements
  1964. if (options.empty) {
  1965. // for checkbox
  1966. if (element.type === 'checkbox' && !element.checked) {
  1967. val = '';
  1968. }
  1969. // for radio
  1970. if (element.type === 'radio') {
  1971. if (!radio_store[element.name] && !element.checked) {
  1972. radio_store[element.name] = false;
  1973. }
  1974. else if (element.checked) {
  1975. radio_store[element.name] = true;
  1976. }
  1977. }
  1978. // if options empty is true, continue only if its radio
  1979. if (val == undefined && element.type == 'radio') {
  1980. continue;
  1981. }
  1982. }
  1983. else {
  1984. // value-less fields are ignored unless options.empty is true
  1985. if (!val) {
  1986. continue;
  1987. }
  1988. }
  1989. // multi select boxes
  1990. if (element.type === 'select-multiple') {
  1991. val = [];
  1992. var selectOptions = element.options;
  1993. var isSelectedOptions = false;
  1994. for (var j=0 ; j<selectOptions.length ; ++j) {
  1995. var option = selectOptions[j];
  1996. var allowedEmpty = options.empty && !option.value;
  1997. var hasValue = (option.value || allowedEmpty);
  1998. if (option.selected && hasValue) {
  1999. isSelectedOptions = true;
  2000. // If using a hash serializer be sure to add the
  2001. // correct notation for an array in the multi-select
  2002. // context. Here the name attribute on the select element
  2003. // might be missing the trailing bracket pair. Both names
  2004. // "foo" and "foo[]" should be arrays.
  2005. if (options.hash && key.slice(key.length - 2) !== '[]') {
  2006. result = serializer(result, key + '[]', option.value);
  2007. }
  2008. else {
  2009. result = serializer(result, key, option.value);
  2010. }
  2011. }
  2012. }
  2013. // Serialize if no selected options and options.empty is true
  2014. if (!isSelectedOptions && options.empty) {
  2015. result = serializer(result, key, '');
  2016. }
  2017. continue;
  2018. }
  2019. result = serializer(result, key, val);
  2020. }
  2021. // Check for all empty radio buttons and serialize them with key=""
  2022. if (options.empty) {
  2023. for (var key in radio_store) {
  2024. if (!radio_store[key]) {
  2025. result = serializer(result, key, '');
  2026. }
  2027. }
  2028. }
  2029. return result;
  2030. }
  2031. function parse_keys(string) {
  2032. var keys = [];
  2033. var prefix = /^([^\[\]]*)/;
  2034. var children = new RegExp(brackets);
  2035. var match = prefix.exec(string);
  2036. if (match[1]) {
  2037. keys.push(match[1]);
  2038. }
  2039. while ((match = children.exec(string)) !== null) {
  2040. keys.push(match[1]);
  2041. }
  2042. return keys;
  2043. }
  2044. function hash_assign(result, keys, value) {
  2045. if (keys.length === 0) {
  2046. result = value;
  2047. return result;
  2048. }
  2049. var key = keys.shift();
  2050. var between = key.match(/^\[(.+?)\]$/);
  2051. if (key === '[]') {
  2052. result = result || [];
  2053. if (Array.isArray(result)) {
  2054. result.push(hash_assign(null, keys, value));
  2055. }
  2056. else {
  2057. // This might be the result of bad name attributes like "[][foo]",
  2058. // in this case the original `result` object will already be
  2059. // assigned to an object literal. Rather than coerce the object to
  2060. // an array, or cause an exception the attribute "_values" is
  2061. // assigned as an array.
  2062. result._values = result._values || [];
  2063. result._values.push(hash_assign(null, keys, value));
  2064. }
  2065. return result;
  2066. }
  2067. // Key is an attribute name and can be assigned directly.
  2068. if (!between) {
  2069. result[key] = hash_assign(result[key], keys, value);
  2070. }
  2071. else {
  2072. var string = between[1];
  2073. // +var converts the variable into a number
  2074. // better than parseInt because it doesn't truncate away trailing
  2075. // letters and actually fails if whole thing is not a number
  2076. var index = +string;
  2077. // If the characters between the brackets is not a number it is an
  2078. // attribute name and can be assigned directly.
  2079. if (isNaN(index)) {
  2080. result = result || {};
  2081. result[string] = hash_assign(result[string], keys, value);
  2082. }
  2083. else {
  2084. result = result || [];
  2085. result[index] = hash_assign(result[index], keys, value);
  2086. }
  2087. }
  2088. return result;
  2089. }
  2090. // Object/hash encoding serializer.
  2091. function hash_serializer(result, key, value) {
  2092. var matches = key.match(brackets);
  2093. // Has brackets? Use the recursive assignment function to walk the keys,
  2094. // construct any missing objects in the result tree and make the assignment
  2095. // at the end of the chain.
  2096. if (matches) {
  2097. var keys = parse_keys(key);
  2098. hash_assign(result, keys, value);
  2099. }
  2100. else {
  2101. // Non bracket notation can make assignments directly.
  2102. var existing = result[key];
  2103. // If the value has been assigned already (for instance when a radio and
  2104. // a checkbox have the same name attribute) convert the previous value
  2105. // into an array before pushing into it.
  2106. //
  2107. // NOTE: If this requirement were removed all hash creation and
  2108. // assignment could go through `hash_assign`.
  2109. if (existing) {
  2110. if (!Array.isArray(existing)) {
  2111. result[key] = [ existing ];
  2112. }
  2113. result[key].push(value);
  2114. }
  2115. else {
  2116. result[key] = value;
  2117. }
  2118. }
  2119. return result;
  2120. }
  2121. // urlform encoding serializer
  2122. function str_serialize(result, key, value) {
  2123. // encode newlines as \r\n cause the html spec says so
  2124. value = value.replace(/(\r)?\n/g, '\r\n');
  2125. value = encodeURIComponent(value);
  2126. // spaces should be '+' rather than '%20'.
  2127. value = value.replace(/%20/g, '+');
  2128. return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + value;
  2129. }
  2130. module.exports = serialize;
  2131. /***/ }),
  2132. /***/ "./node_modules/process/browser.js":
  2133. /*!*****************************************!*\
  2134. !*** ./node_modules/process/browser.js ***!
  2135. \*****************************************/
  2136. /***/ ((module) => {
  2137. // shim for using process in browser
  2138. var process = module.exports = {};
  2139. // cached from whatever global is present so that test runners that stub it
  2140. // don't break things. But we need to wrap it in a try catch in case it is
  2141. // wrapped in strict mode code which doesn't define any globals. It's inside a
  2142. // function because try/catches deoptimize in certain engines.
  2143. var cachedSetTimeout;
  2144. var cachedClearTimeout;
  2145. function defaultSetTimout() {
  2146. throw new Error('setTimeout has not been defined');
  2147. }
  2148. function defaultClearTimeout () {
  2149. throw new Error('clearTimeout has not been defined');
  2150. }
  2151. (function () {
  2152. try {
  2153. if (typeof setTimeout === 'function') {
  2154. cachedSetTimeout = setTimeout;
  2155. } else {
  2156. cachedSetTimeout = defaultSetTimout;
  2157. }
  2158. } catch (e) {
  2159. cachedSetTimeout = defaultSetTimout;
  2160. }
  2161. try {
  2162. if (typeof clearTimeout === 'function') {
  2163. cachedClearTimeout = clearTimeout;
  2164. } else {
  2165. cachedClearTimeout = defaultClearTimeout;
  2166. }
  2167. } catch (e) {
  2168. cachedClearTimeout = defaultClearTimeout;
  2169. }
  2170. } ())
  2171. function runTimeout(fun) {
  2172. if (cachedSetTimeout === setTimeout) {
  2173. //normal enviroments in sane situations
  2174. return setTimeout(fun, 0);
  2175. }
  2176. // if setTimeout wasn't available but was latter defined
  2177. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  2178. cachedSetTimeout = setTimeout;
  2179. return setTimeout(fun, 0);
  2180. }
  2181. try {
  2182. // when when somebody has screwed with setTimeout but no I.E. maddness
  2183. return cachedSetTimeout(fun, 0);
  2184. } catch(e){
  2185. try {
  2186. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2187. return cachedSetTimeout.call(null, fun, 0);
  2188. } catch(e){
  2189. // 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
  2190. return cachedSetTimeout.call(this, fun, 0);
  2191. }
  2192. }
  2193. }
  2194. function runClearTimeout(marker) {
  2195. if (cachedClearTimeout === clearTimeout) {
  2196. //normal enviroments in sane situations
  2197. return clearTimeout(marker);
  2198. }
  2199. // if clearTimeout wasn't available but was latter defined
  2200. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  2201. cachedClearTimeout = clearTimeout;
  2202. return clearTimeout(marker);
  2203. }
  2204. try {
  2205. // when when somebody has screwed with setTimeout but no I.E. maddness
  2206. return cachedClearTimeout(marker);
  2207. } catch (e){
  2208. try {
  2209. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2210. return cachedClearTimeout.call(null, marker);
  2211. } catch (e){
  2212. // 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.
  2213. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  2214. return cachedClearTimeout.call(this, marker);
  2215. }
  2216. }
  2217. }
  2218. var queue = [];
  2219. var draining = false;
  2220. var currentQueue;
  2221. var queueIndex = -1;
  2222. function cleanUpNextTick() {
  2223. if (!draining || !currentQueue) {
  2224. return;
  2225. }
  2226. draining = false;
  2227. if (currentQueue.length) {
  2228. queue = currentQueue.concat(queue);
  2229. } else {
  2230. queueIndex = -1;
  2231. }
  2232. if (queue.length) {
  2233. drainQueue();
  2234. }
  2235. }
  2236. function drainQueue() {
  2237. if (draining) {
  2238. return;
  2239. }
  2240. var timeout = runTimeout(cleanUpNextTick);
  2241. draining = true;
  2242. var len = queue.length;
  2243. while(len) {
  2244. currentQueue = queue;
  2245. queue = [];
  2246. while (++queueIndex < len) {
  2247. if (currentQueue) {
  2248. currentQueue[queueIndex].run();
  2249. }
  2250. }
  2251. queueIndex = -1;
  2252. len = queue.length;
  2253. }
  2254. currentQueue = null;
  2255. draining = false;
  2256. runClearTimeout(timeout);
  2257. }
  2258. process.nextTick = function (fun) {
  2259. var args = new Array(arguments.length - 1);
  2260. if (arguments.length > 1) {
  2261. for (var i = 1; i < arguments.length; i++) {
  2262. args[i - 1] = arguments[i];
  2263. }
  2264. }
  2265. queue.push(new Item(fun, args));
  2266. if (queue.length === 1 && !draining) {
  2267. runTimeout(drainQueue);
  2268. }
  2269. };
  2270. // v8 likes predictible objects
  2271. function Item(fun, array) {
  2272. this.fun = fun;
  2273. this.array = array;
  2274. }
  2275. Item.prototype.run = function () {
  2276. this.fun.apply(null, this.array);
  2277. };
  2278. process.title = 'browser';
  2279. process.browser = true;
  2280. process.env = {};
  2281. process.argv = [];
  2282. process.version = ''; // empty string to avoid regexp issues
  2283. process.versions = {};
  2284. function noop() {}
  2285. process.on = noop;
  2286. process.addListener = noop;
  2287. process.once = noop;
  2288. process.off = noop;
  2289. process.removeListener = noop;
  2290. process.removeAllListeners = noop;
  2291. process.emit = noop;
  2292. process.prependListener = noop;
  2293. process.prependOnceListener = noop;
  2294. process.listeners = function (name) { return [] }
  2295. process.binding = function (name) {
  2296. throw new Error('process.binding is not supported');
  2297. };
  2298. process.cwd = function () { return '/' };
  2299. process.chdir = function (dir) {
  2300. throw new Error('process.chdir is not supported');
  2301. };
  2302. process.umask = function() { return 0; };
  2303. /***/ }),
  2304. /***/ "./node_modules/riot/riot.esm.js":
  2305. /*!***************************************!*\
  2306. !*** ./node_modules/riot/riot.esm.js ***!
  2307. \***************************************/
  2308. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  2309. "use strict";
  2310. __webpack_require__.r(__webpack_exports__);
  2311. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2312. /* harmony export */ "__": () => (/* binding */ __),
  2313. /* harmony export */ "component": () => (/* binding */ component),
  2314. /* harmony export */ "install": () => (/* binding */ install),
  2315. /* harmony export */ "mount": () => (/* binding */ mount),
  2316. /* harmony export */ "pure": () => (/* binding */ pure),
  2317. /* harmony export */ "register": () => (/* binding */ register),
  2318. /* harmony export */ "uninstall": () => (/* binding */ uninstall),
  2319. /* harmony export */ "unmount": () => (/* binding */ unmount),
  2320. /* harmony export */ "unregister": () => (/* binding */ unregister),
  2321. /* harmony export */ "version": () => (/* binding */ version),
  2322. /* harmony export */ "withTypes": () => (/* binding */ withTypes)
  2323. /* harmony export */ });
  2324. /* Riot v6.0.1, @license MIT */
  2325. /**
  2326. * Convert a string from camel case to dash-case
  2327. * @param {string} string - probably a component tag name
  2328. * @returns {string} component name normalized
  2329. */
  2330. function camelToDashCase(string) {
  2331. return string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  2332. }
  2333. /**
  2334. * Convert a string containing dashes to camel case
  2335. * @param {string} string - input string
  2336. * @returns {string} my-string -> myString
  2337. */
  2338. function dashToCamelCase(string) {
  2339. return string.replace(/-(\w)/g, (_, c) => c.toUpperCase());
  2340. }
  2341. /**
  2342. * Get all the element attributes as object
  2343. * @param {HTMLElement} element - DOM node we want to parse
  2344. * @returns {Object} all the attributes found as a key value pairs
  2345. */
  2346. function DOMattributesToObject(element) {
  2347. return Array.from(element.attributes).reduce((acc, attribute) => {
  2348. acc[dashToCamelCase(attribute.name)] = attribute.value;
  2349. return acc;
  2350. }, {});
  2351. }
  2352. /**
  2353. * Move all the child nodes from a source tag to another
  2354. * @param {HTMLElement} source - source node
  2355. * @param {HTMLElement} target - target node
  2356. * @returns {undefined} it's a void method ¯\_()_/¯
  2357. */
  2358. // Ignore this helper because it's needed only for svg tags
  2359. function moveChildren(source, target) {
  2360. if (source.firstChild) {
  2361. target.appendChild(source.firstChild);
  2362. moveChildren(source, target);
  2363. }
  2364. }
  2365. /**
  2366. * Remove the child nodes from any DOM node
  2367. * @param {HTMLElement} node - target node
  2368. * @returns {undefined}
  2369. */
  2370. function cleanNode(node) {
  2371. clearChildren(node.childNodes);
  2372. }
  2373. /**
  2374. * Clear multiple children in a node
  2375. * @param {HTMLElement[]} children - direct children nodes
  2376. * @returns {undefined}
  2377. */
  2378. function clearChildren(children) {
  2379. Array.from(children).forEach(removeChild);
  2380. }
  2381. /**
  2382. * Remove a node
  2383. * @param {HTMLElement}node - node to remove
  2384. * @returns {undefined}
  2385. */
  2386. const removeChild = node => node && node.parentNode && node.parentNode.removeChild(node);
  2387. /**
  2388. * Insert before a node
  2389. * @param {HTMLElement} newNode - node to insert
  2390. * @param {HTMLElement} refNode - ref child
  2391. * @returns {undefined}
  2392. */
  2393. const insertBefore = (newNode, refNode) => refNode && refNode.parentNode && refNode.parentNode.insertBefore(newNode, refNode);
  2394. /**
  2395. * Replace a node
  2396. * @param {HTMLElement} newNode - new node to add to the DOM
  2397. * @param {HTMLElement} replaced - node to replace
  2398. * @returns {undefined}
  2399. */
  2400. const replaceChild = (newNode, replaced) => replaced && replaced.parentNode && replaced.parentNode.replaceChild(newNode, replaced);
  2401. // Riot.js constants that can be used accross more modules
  2402. const COMPONENTS_IMPLEMENTATION_MAP$1 = new Map(),
  2403. DOM_COMPONENT_INSTANCE_PROPERTY$1 = Symbol('riot-component'),
  2404. PLUGINS_SET$1 = new Set(),
  2405. IS_DIRECTIVE = 'is',
  2406. VALUE_ATTRIBUTE = 'value',
  2407. MOUNT_METHOD_KEY = 'mount',
  2408. UPDATE_METHOD_KEY = 'update',
  2409. UNMOUNT_METHOD_KEY = 'unmount',
  2410. SHOULD_UPDATE_KEY = 'shouldUpdate',
  2411. ON_BEFORE_MOUNT_KEY = 'onBeforeMount',
  2412. ON_MOUNTED_KEY = 'onMounted',
  2413. ON_BEFORE_UPDATE_KEY = 'onBeforeUpdate',
  2414. ON_UPDATED_KEY = 'onUpdated',
  2415. ON_BEFORE_UNMOUNT_KEY = 'onBeforeUnmount',
  2416. ON_UNMOUNTED_KEY = 'onUnmounted',
  2417. PROPS_KEY = 'props',
  2418. STATE_KEY = 'state',
  2419. SLOTS_KEY = 'slots',
  2420. ROOT_KEY = 'root',
  2421. IS_PURE_SYMBOL = Symbol('pure'),
  2422. IS_COMPONENT_UPDATING = Symbol('is_updating'),
  2423. PARENT_KEY_SYMBOL = Symbol('parent'),
  2424. ATTRIBUTES_KEY_SYMBOL = Symbol('attributes'),
  2425. TEMPLATE_KEY_SYMBOL = Symbol('template');
  2426. var globals = /*#__PURE__*/Object.freeze({
  2427. __proto__: null,
  2428. COMPONENTS_IMPLEMENTATION_MAP: COMPONENTS_IMPLEMENTATION_MAP$1,
  2429. DOM_COMPONENT_INSTANCE_PROPERTY: DOM_COMPONENT_INSTANCE_PROPERTY$1,
  2430. PLUGINS_SET: PLUGINS_SET$1,
  2431. IS_DIRECTIVE: IS_DIRECTIVE,
  2432. VALUE_ATTRIBUTE: VALUE_ATTRIBUTE,
  2433. MOUNT_METHOD_KEY: MOUNT_METHOD_KEY,
  2434. UPDATE_METHOD_KEY: UPDATE_METHOD_KEY,
  2435. UNMOUNT_METHOD_KEY: UNMOUNT_METHOD_KEY,
  2436. SHOULD_UPDATE_KEY: SHOULD_UPDATE_KEY,
  2437. ON_BEFORE_MOUNT_KEY: ON_BEFORE_MOUNT_KEY,
  2438. ON_MOUNTED_KEY: ON_MOUNTED_KEY,
  2439. ON_BEFORE_UPDATE_KEY: ON_BEFORE_UPDATE_KEY,
  2440. ON_UPDATED_KEY: ON_UPDATED_KEY,
  2441. ON_BEFORE_UNMOUNT_KEY: ON_BEFORE_UNMOUNT_KEY,
  2442. ON_UNMOUNTED_KEY: ON_UNMOUNTED_KEY,
  2443. PROPS_KEY: PROPS_KEY,
  2444. STATE_KEY: STATE_KEY,
  2445. SLOTS_KEY: SLOTS_KEY,
  2446. ROOT_KEY: ROOT_KEY,
  2447. IS_PURE_SYMBOL: IS_PURE_SYMBOL,
  2448. IS_COMPONENT_UPDATING: IS_COMPONENT_UPDATING,
  2449. PARENT_KEY_SYMBOL: PARENT_KEY_SYMBOL,
  2450. ATTRIBUTES_KEY_SYMBOL: ATTRIBUTES_KEY_SYMBOL,
  2451. TEMPLATE_KEY_SYMBOL: TEMPLATE_KEY_SYMBOL
  2452. });
  2453. const EACH = 0;
  2454. const IF = 1;
  2455. const SIMPLE = 2;
  2456. const TAG = 3;
  2457. const SLOT = 4;
  2458. var bindingTypes = {
  2459. EACH,
  2460. IF,
  2461. SIMPLE,
  2462. TAG,
  2463. SLOT
  2464. };
  2465. const ATTRIBUTE = 0;
  2466. const EVENT = 1;
  2467. const TEXT = 2;
  2468. const VALUE = 3;
  2469. var expressionTypes = {
  2470. ATTRIBUTE,
  2471. EVENT,
  2472. TEXT,
  2473. VALUE
  2474. };
  2475. const HEAD_SYMBOL = Symbol('head');
  2476. const TAIL_SYMBOL = Symbol('tail');
  2477. /**
  2478. * Create the <template> fragments text nodes
  2479. * @return {Object} {{head: Text, tail: Text}}
  2480. */
  2481. function createHeadTailPlaceholders() {
  2482. const head = document.createTextNode('');
  2483. const tail = document.createTextNode('');
  2484. head[HEAD_SYMBOL] = true;
  2485. tail[TAIL_SYMBOL] = true;
  2486. return {
  2487. head,
  2488. tail
  2489. };
  2490. }
  2491. /**
  2492. * Create the template meta object in case of <template> fragments
  2493. * @param {TemplateChunk} componentTemplate - template chunk object
  2494. * @returns {Object} the meta property that will be passed to the mount function of the TemplateChunk
  2495. */
  2496. function createTemplateMeta(componentTemplate) {
  2497. const fragment = componentTemplate.dom.cloneNode(true);
  2498. const {
  2499. head,
  2500. tail
  2501. } = createHeadTailPlaceholders();
  2502. return {
  2503. avoidDOMInjection: true,
  2504. fragment,
  2505. head,
  2506. tail,
  2507. children: [head, ...Array.from(fragment.childNodes), tail]
  2508. };
  2509. }
  2510. /**
  2511. * Helper function to set an immutable property
  2512. * @param {Object} source - object where the new property will be set
  2513. * @param {string} key - object key where the new property will be stored
  2514. * @param {*} value - value of the new property
  2515. * @param {Object} options - set the propery overriding the default options
  2516. * @returns {Object} - the original object modified
  2517. */
  2518. function defineProperty(source, key, value, options) {
  2519. if (options === void 0) {
  2520. options = {};
  2521. }
  2522. /* eslint-disable fp/no-mutating-methods */
  2523. Object.defineProperty(source, key, Object.assign({
  2524. value,
  2525. enumerable: false,
  2526. writable: false,
  2527. configurable: true
  2528. }, options));
  2529. /* eslint-enable fp/no-mutating-methods */
  2530. return source;
  2531. }
  2532. /**
  2533. * Define multiple properties on a target object
  2534. * @param {Object} source - object where the new properties will be set
  2535. * @param {Object} properties - object containing as key pair the key + value properties
  2536. * @param {Object} options - set the propery overriding the default options
  2537. * @returns {Object} the original object modified
  2538. */
  2539. function defineProperties(source, properties, options) {
  2540. Object.entries(properties).forEach(_ref => {
  2541. let [key, value] = _ref;
  2542. defineProperty(source, key, value, options);
  2543. });
  2544. return source;
  2545. }
  2546. /**
  2547. * Define default properties if they don't exist on the source object
  2548. * @param {Object} source - object that will receive the default properties
  2549. * @param {Object} defaults - object containing additional optional keys
  2550. * @returns {Object} the original object received enhanced
  2551. */
  2552. function defineDefaults(source, defaults) {
  2553. Object.entries(defaults).forEach(_ref2 => {
  2554. let [key, value] = _ref2;
  2555. if (!source[key]) source[key] = value;
  2556. });
  2557. return source;
  2558. }
  2559. /**
  2560. * Get the current <template> fragment children located in between the head and tail comments
  2561. * @param {Comment} head - head comment node
  2562. * @param {Comment} tail - tail comment node
  2563. * @return {Array[]} children list of the nodes found in this template fragment
  2564. */
  2565. function getFragmentChildren(_ref) {
  2566. let {
  2567. head,
  2568. tail
  2569. } = _ref;
  2570. const nodes = walkNodes([head], head.nextSibling, n => n === tail, false);
  2571. nodes.push(tail);
  2572. return nodes;
  2573. }
  2574. /**
  2575. * Recursive function to walk all the <template> children nodes
  2576. * @param {Array[]} children - children nodes collection
  2577. * @param {ChildNode} node - current node
  2578. * @param {Function} check - exit function check
  2579. * @param {boolean} isFilterActive - filter flag to skip nodes managed by other bindings
  2580. * @returns {Array[]} children list of the nodes found in this template fragment
  2581. */
  2582. function walkNodes(children, node, check, isFilterActive) {
  2583. const {
  2584. nextSibling
  2585. } = node; // filter tail and head nodes together with all the nodes in between
  2586. // this is needed only to fix a really ugly edge case https://github.com/riot/riot/issues/2892
  2587. if (!isFilterActive && !node[HEAD_SYMBOL] && !node[TAIL_SYMBOL]) {
  2588. children.push(node);
  2589. }
  2590. if (!nextSibling || check(node)) return children;
  2591. return walkNodes(children, nextSibling, check, // activate the filters to skip nodes between <template> fragments that will be managed by other bindings
  2592. isFilterActive && !node[TAIL_SYMBOL] || nextSibling[HEAD_SYMBOL]);
  2593. }
  2594. /**
  2595. * Quick type checking
  2596. * @param {*} element - anything
  2597. * @param {string} type - type definition
  2598. * @returns {boolean} true if the type corresponds
  2599. */
  2600. function checkType(element, type) {
  2601. return typeof element === type;
  2602. }
  2603. /**
  2604. * Check if an element is part of an svg
  2605. * @param {HTMLElement} el - element to check
  2606. * @returns {boolean} true if we are in an svg context
  2607. */
  2608. function isSvg(el) {
  2609. const owner = el.ownerSVGElement;
  2610. return !!owner || owner === null;
  2611. }
  2612. /**
  2613. * Check if an element is a template tag
  2614. * @param {HTMLElement} el - element to check
  2615. * @returns {boolean} true if it's a <template>
  2616. */
  2617. function isTemplate(el) {
  2618. return el.tagName.toLowerCase() === 'template';
  2619. }
  2620. /**
  2621. * Check that will be passed if its argument is a function
  2622. * @param {*} value - value to check
  2623. * @returns {boolean} - true if the value is a function
  2624. */
  2625. function isFunction(value) {
  2626. return checkType(value, 'function');
  2627. }
  2628. /**
  2629. * Check if a value is a Boolean
  2630. * @param {*} value - anything
  2631. * @returns {boolean} true only for the value is a boolean
  2632. */
  2633. function isBoolean(value) {
  2634. return checkType(value, 'boolean');
  2635. }
  2636. /**
  2637. * Check if a value is an Object
  2638. * @param {*} value - anything
  2639. * @returns {boolean} true only for the value is an object
  2640. */
  2641. function isObject(value) {
  2642. return !isNil(value) && value.constructor === Object;
  2643. }
  2644. /**
  2645. * Check if a value is null or undefined
  2646. * @param {*} value - anything
  2647. * @returns {boolean} true only for the 'undefined' and 'null' types
  2648. */
  2649. function isNil(value) {
  2650. return value === null || value === undefined;
  2651. }
  2652. /**
  2653. * ISC License
  2654. *
  2655. * Copyright (c) 2020, Andrea Giammarchi, @WebReflection
  2656. *
  2657. * Permission to use, copy, modify, and/or distribute this software for any
  2658. * purpose with or without fee is hereby granted, provided that the above
  2659. * copyright notice and this permission notice appear in all copies.
  2660. *
  2661. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  2662. * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  2663. * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  2664. * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  2665. * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  2666. * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  2667. * PERFORMANCE OF THIS SOFTWARE.
  2668. */
  2669. // fork of https://github.com/WebReflection/udomdiff version 1.1.0
  2670. // due to https://github.com/WebReflection/udomdiff/pull/2
  2671. /* eslint-disable */
  2672. /**
  2673. * @param {Node[]} a The list of current/live children
  2674. * @param {Node[]} b The list of future children
  2675. * @param {(entry: Node, action: number) => Node} get
  2676. * The callback invoked per each entry related DOM operation.
  2677. * @param {Node} [before] The optional node used as anchor to insert before.
  2678. * @returns {Node[]} The same list of future children.
  2679. */
  2680. var udomdiff = ((a, b, get, before) => {
  2681. const bLength = b.length;
  2682. let aEnd = a.length;
  2683. let bEnd = bLength;
  2684. let aStart = 0;
  2685. let bStart = 0;
  2686. let map = null;
  2687. while (aStart < aEnd || bStart < bEnd) {
  2688. // append head, tail, or nodes in between: fast path
  2689. if (aEnd === aStart) {
  2690. // we could be in a situation where the rest of nodes that
  2691. // need to be added are not at the end, and in such case
  2692. // the node to `insertBefore`, if the index is more than 0
  2693. // must be retrieved, otherwise it's gonna be the first item.
  2694. const node = bEnd < bLength ? bStart ? get(b[bStart - 1], -0).nextSibling : get(b[bEnd - bStart], 0) : before;
  2695. while (bStart < bEnd) insertBefore(get(b[bStart++], 1), node);
  2696. } // remove head or tail: fast path
  2697. else if (bEnd === bStart) {
  2698. while (aStart < aEnd) {
  2699. // remove the node only if it's unknown or not live
  2700. if (!map || !map.has(a[aStart])) removeChild(get(a[aStart], -1));
  2701. aStart++;
  2702. }
  2703. } // same node: fast path
  2704. else if (a[aStart] === b[bStart]) {
  2705. aStart++;
  2706. bStart++;
  2707. } // same tail: fast path
  2708. else if (a[aEnd - 1] === b[bEnd - 1]) {
  2709. aEnd--;
  2710. bEnd--;
  2711. } // The once here single last swap "fast path" has been removed in v1.1.0
  2712. // https://github.com/WebReflection/udomdiff/blob/single-final-swap/esm/index.js#L69-L85
  2713. // reverse swap: also fast path
  2714. else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {
  2715. // this is a "shrink" operation that could happen in these cases:
  2716. // [1, 2, 3, 4, 5]
  2717. // [1, 4, 3, 2, 5]
  2718. // or asymmetric too
  2719. // [1, 2, 3, 4, 5]
  2720. // [1, 2, 3, 5, 6, 4]
  2721. const node = get(a[--aEnd], -1).nextSibling;
  2722. insertBefore(get(b[bStart++], 1), get(a[aStart++], -1).nextSibling);
  2723. insertBefore(get(b[--bEnd], 1), node); // mark the future index as identical (yeah, it's dirty, but cheap 👍)
  2724. // The main reason to do this, is that when a[aEnd] will be reached,
  2725. // the loop will likely be on the fast path, as identical to b[bEnd].
  2726. // In the best case scenario, the next loop will skip the tail,
  2727. // but in the worst one, this node will be considered as already
  2728. // processed, bailing out pretty quickly from the map index check
  2729. a[aEnd] = b[bEnd];
  2730. } // map based fallback, "slow" path
  2731. else {
  2732. // the map requires an O(bEnd - bStart) operation once
  2733. // to store all future nodes indexes for later purposes.
  2734. // In the worst case scenario, this is a full O(N) cost,
  2735. // and such scenario happens at least when all nodes are different,
  2736. // but also if both first and last items of the lists are different
  2737. if (!map) {
  2738. map = new Map();
  2739. let i = bStart;
  2740. while (i < bEnd) map.set(b[i], i++);
  2741. } // if it's a future node, hence it needs some handling
  2742. if (map.has(a[aStart])) {
  2743. // grab the index of such node, 'cause it might have been processed
  2744. const index = map.get(a[aStart]); // if it's not already processed, look on demand for the next LCS
  2745. if (bStart < index && index < bEnd) {
  2746. let i = aStart; // counts the amount of nodes that are the same in the future
  2747. let sequence = 1;
  2748. while (++i < aEnd && i < bEnd && map.get(a[i]) === index + sequence) sequence++; // effort decision here: if the sequence is longer than replaces
  2749. // needed to reach such sequence, which would brings again this loop
  2750. // to the fast path, prepend the difference before a sequence,
  2751. // and move only the future list index forward, so that aStart
  2752. // and bStart will be aligned again, hence on the fast path.
  2753. // An example considering aStart and bStart are both 0:
  2754. // a: [1, 2, 3, 4]
  2755. // b: [7, 1, 2, 3, 6]
  2756. // this would place 7 before 1 and, from that time on, 1, 2, and 3
  2757. // will be processed at zero cost
  2758. if (sequence > index - bStart) {
  2759. const node = get(a[aStart], 0);
  2760. while (bStart < index) insertBefore(get(b[bStart++], 1), node);
  2761. } // if the effort wasn't good enough, fallback to a replace,
  2762. // moving both source and target indexes forward, hoping that some
  2763. // similar node will be found later on, to go back to the fast path
  2764. else {
  2765. replaceChild(get(b[bStart++], 1), get(a[aStart++], -1));
  2766. }
  2767. } // otherwise move the source forward, 'cause there's nothing to do
  2768. else aStart++;
  2769. } // this node has no meaning in the future list, so it's more than safe
  2770. // to remove it, and check the next live node out instead, meaning
  2771. // that only the live list index should be forwarded
  2772. else removeChild(get(a[aStart++], -1));
  2773. }
  2774. }
  2775. return b;
  2776. });
  2777. const UNMOUNT_SCOPE = Symbol('unmount');
  2778. const EachBinding = {
  2779. // dynamic binding properties
  2780. // childrenMap: null,
  2781. // node: null,
  2782. // root: null,
  2783. // condition: null,
  2784. // evaluate: null,
  2785. // template: null,
  2786. // isTemplateTag: false,
  2787. nodes: [],
  2788. // getKey: null,
  2789. // indexName: null,
  2790. // itemName: null,
  2791. // afterPlaceholder: null,
  2792. // placeholder: null,
  2793. // API methods
  2794. mount(scope, parentScope) {
  2795. return this.update(scope, parentScope);
  2796. },
  2797. update(scope, parentScope) {
  2798. const {
  2799. placeholder,
  2800. nodes,
  2801. childrenMap
  2802. } = this;
  2803. const collection = scope === UNMOUNT_SCOPE ? null : this.evaluate(scope);
  2804. const items = collection ? Array.from(collection) : []; // prepare the diffing
  2805. const {
  2806. newChildrenMap,
  2807. batches,
  2808. futureNodes
  2809. } = createPatch(items, scope, parentScope, this); // patch the DOM only if there are new nodes
  2810. udomdiff(nodes, futureNodes, patch(Array.from(childrenMap.values()), parentScope), placeholder); // trigger the mounts and the updates
  2811. batches.forEach(fn => fn()); // update the children map
  2812. this.childrenMap = newChildrenMap;
  2813. this.nodes = futureNodes; // make sure that the loop edge nodes are marked
  2814. markEdgeNodes(this.nodes);
  2815. return this;
  2816. },
  2817. unmount(scope, parentScope) {
  2818. this.update(UNMOUNT_SCOPE, parentScope);
  2819. return this;
  2820. }
  2821. };
  2822. /**
  2823. * Patch the DOM while diffing
  2824. * @param {any[]} redundant - list of all the children (template, nodes, context) added via each
  2825. * @param {*} parentScope - scope of the parent template
  2826. * @returns {Function} patch function used by domdiff
  2827. */
  2828. function patch(redundant, parentScope) {
  2829. return (item, info) => {
  2830. if (info < 0) {
  2831. // get the last element added to the childrenMap saved previously
  2832. const element = redundant[redundant.length - 1];
  2833. if (element) {
  2834. // get the nodes and the template in stored in the last child of the childrenMap
  2835. const {
  2836. template,
  2837. nodes,
  2838. context
  2839. } = element; // remove the last node (notice <template> tags might have more children nodes)
  2840. nodes.pop(); // notice that we pass null as last argument because
  2841. // the root node and its children will be removed by domdiff
  2842. if (!nodes.length) {
  2843. // we have cleared all the children nodes and we can unmount this template
  2844. redundant.pop();
  2845. template.unmount(context, parentScope, null);
  2846. }
  2847. }
  2848. }
  2849. return item;
  2850. };
  2851. }
  2852. /**
  2853. * Check whether a template must be filtered from a loop
  2854. * @param {Function} condition - filter function
  2855. * @param {Object} context - argument passed to the filter function
  2856. * @returns {boolean} true if this item should be skipped
  2857. */
  2858. function mustFilterItem(condition, context) {
  2859. return condition ? !condition(context) : false;
  2860. }
  2861. /**
  2862. * Extend the scope of the looped template
  2863. * @param {Object} scope - current template scope
  2864. * @param {Object} options - options
  2865. * @param {string} options.itemName - key to identify the looped item in the new context
  2866. * @param {string} options.indexName - key to identify the index of the looped item
  2867. * @param {number} options.index - current index
  2868. * @param {*} options.item - collection item looped
  2869. * @returns {Object} enhanced scope object
  2870. */
  2871. function extendScope(scope, _ref) {
  2872. let {
  2873. itemName,
  2874. indexName,
  2875. index,
  2876. item
  2877. } = _ref;
  2878. defineProperty(scope, itemName, item);
  2879. if (indexName) defineProperty(scope, indexName, index);
  2880. return scope;
  2881. }
  2882. /**
  2883. * Mark the first and last nodes in order to ignore them in case we need to retrieve the <template> fragment nodes
  2884. * @param {Array[]} nodes - each binding nodes list
  2885. * @returns {undefined} void function
  2886. */
  2887. function markEdgeNodes(nodes) {
  2888. const first = nodes[0];
  2889. const last = nodes[nodes.length - 1];
  2890. if (first) first[HEAD_SYMBOL] = true;
  2891. if (last) last[TAIL_SYMBOL] = true;
  2892. }
  2893. /**
  2894. * Loop the current template items
  2895. * @param {Array} items - expression collection value
  2896. * @param {*} scope - template scope
  2897. * @param {*} parentScope - scope of the parent template
  2898. * @param {EachBinding} binding - each binding object instance
  2899. * @returns {Object} data
  2900. * @returns {Map} data.newChildrenMap - a Map containing the new children template structure
  2901. * @returns {Array} data.batches - array containing the template lifecycle functions to trigger
  2902. * @returns {Array} data.futureNodes - array containing the nodes we need to diff
  2903. */
  2904. function createPatch(items, scope, parentScope, binding) {
  2905. const {
  2906. condition,
  2907. template,
  2908. childrenMap,
  2909. itemName,
  2910. getKey,
  2911. indexName,
  2912. root,
  2913. isTemplateTag
  2914. } = binding;
  2915. const newChildrenMap = new Map();
  2916. const batches = [];
  2917. const futureNodes = [];
  2918. items.forEach((item, index) => {
  2919. const context = extendScope(Object.create(scope), {
  2920. itemName,
  2921. indexName,
  2922. index,
  2923. item
  2924. });
  2925. const key = getKey ? getKey(context) : index;
  2926. const oldItem = childrenMap.get(key);
  2927. const nodes = [];
  2928. if (mustFilterItem(condition, context)) {
  2929. return;
  2930. }
  2931. const mustMount = !oldItem;
  2932. const componentTemplate = oldItem ? oldItem.template : template.clone();
  2933. const el = componentTemplate.el || root.cloneNode();
  2934. const meta = isTemplateTag && mustMount ? createTemplateMeta(componentTemplate) : componentTemplate.meta;
  2935. if (mustMount) {
  2936. batches.push(() => componentTemplate.mount(el, context, parentScope, meta));
  2937. } else {
  2938. batches.push(() => componentTemplate.update(context, parentScope));
  2939. } // create the collection of nodes to update or to add
  2940. // in case of template tags we need to add all its children nodes
  2941. if (isTemplateTag) {
  2942. nodes.push(...(mustMount ? meta.children : getFragmentChildren(meta)));
  2943. } else {
  2944. nodes.push(el);
  2945. } // delete the old item from the children map
  2946. childrenMap.delete(key);
  2947. futureNodes.push(...nodes); // update the children map
  2948. newChildrenMap.set(key, {
  2949. nodes,
  2950. template: componentTemplate,
  2951. context,
  2952. index
  2953. });
  2954. });
  2955. return {
  2956. newChildrenMap,
  2957. batches,
  2958. futureNodes
  2959. };
  2960. }
  2961. function create$6(node, _ref2) {
  2962. let {
  2963. evaluate,
  2964. condition,
  2965. itemName,
  2966. indexName,
  2967. getKey,
  2968. template
  2969. } = _ref2;
  2970. const placeholder = document.createTextNode('');
  2971. const root = node.cloneNode();
  2972. insertBefore(placeholder, node);
  2973. removeChild(node);
  2974. return Object.assign({}, EachBinding, {
  2975. childrenMap: new Map(),
  2976. node,
  2977. root,
  2978. condition,
  2979. evaluate,
  2980. isTemplateTag: isTemplate(root),
  2981. template: template.createDOM(node),
  2982. getKey,
  2983. indexName,
  2984. itemName,
  2985. placeholder
  2986. });
  2987. }
  2988. /**
  2989. * Binding responsible for the `if` directive
  2990. */
  2991. const IfBinding = {
  2992. // dynamic binding properties
  2993. // node: null,
  2994. // evaluate: null,
  2995. // isTemplateTag: false,
  2996. // placeholder: null,
  2997. // template: null,
  2998. // API methods
  2999. mount(scope, parentScope) {
  3000. return this.update(scope, parentScope);
  3001. },
  3002. update(scope, parentScope) {
  3003. const value = !!this.evaluate(scope);
  3004. const mustMount = !this.value && value;
  3005. const mustUnmount = this.value && !value;
  3006. const mount = () => {
  3007. const pristine = this.node.cloneNode();
  3008. insertBefore(pristine, this.placeholder);
  3009. this.template = this.template.clone();
  3010. this.template.mount(pristine, scope, parentScope);
  3011. };
  3012. switch (true) {
  3013. case mustMount:
  3014. mount();
  3015. break;
  3016. case mustUnmount:
  3017. this.unmount(scope);
  3018. break;
  3019. default:
  3020. if (value) this.template.update(scope, parentScope);
  3021. }
  3022. this.value = value;
  3023. return this;
  3024. },
  3025. unmount(scope, parentScope) {
  3026. this.template.unmount(scope, parentScope, true);
  3027. return this;
  3028. }
  3029. };
  3030. function create$5(node, _ref) {
  3031. let {
  3032. evaluate,
  3033. template
  3034. } = _ref;
  3035. const placeholder = document.createTextNode('');
  3036. insertBefore(placeholder, node);
  3037. removeChild(node);
  3038. return Object.assign({}, IfBinding, {
  3039. node,
  3040. evaluate,
  3041. placeholder,
  3042. template: template.createDOM(node)
  3043. });
  3044. }
  3045. /**
  3046. * Throw an error with a descriptive message
  3047. * @param { string } message - error message
  3048. * @returns { undefined } hoppla.. at this point the program should stop working
  3049. */
  3050. function panic(message) {
  3051. throw new Error(message);
  3052. }
  3053. /**
  3054. * Returns the memoized (cached) function.
  3055. * // borrowed from https://www.30secondsofcode.org/js/s/memoize
  3056. * @param {Function} fn - function to memoize
  3057. * @returns {Function} memoize function
  3058. */
  3059. function memoize(fn) {
  3060. const cache = new Map();
  3061. const cached = val => {
  3062. return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);
  3063. };
  3064. cached.cache = cache;
  3065. return cached;
  3066. }
  3067. /**
  3068. * Evaluate a list of attribute expressions
  3069. * @param {Array} attributes - attribute expressions generated by the riot compiler
  3070. * @returns {Object} key value pairs with the result of the computation
  3071. */
  3072. function evaluateAttributeExpressions(attributes) {
  3073. return attributes.reduce((acc, attribute) => {
  3074. const {
  3075. value,
  3076. type
  3077. } = attribute;
  3078. switch (true) {
  3079. // spread attribute
  3080. case !attribute.name && type === ATTRIBUTE:
  3081. return Object.assign({}, acc, value);
  3082. // value attribute
  3083. case type === VALUE:
  3084. acc.value = attribute.value;
  3085. break;
  3086. // normal attributes
  3087. default:
  3088. acc[dashToCamelCase(attribute.name)] = attribute.value;
  3089. }
  3090. return acc;
  3091. }, {});
  3092. }
  3093. const ElementProto = typeof Element === 'undefined' ? {} : Element.prototype;
  3094. const isNativeHtmlProperty = memoize(name => ElementProto.hasOwnProperty(name)); // eslint-disable-line
  3095. /**
  3096. * Add all the attributes provided
  3097. * @param {HTMLElement} node - target node
  3098. * @param {Object} attributes - object containing the attributes names and values
  3099. * @returns {undefined} sorry it's a void function :(
  3100. */
  3101. function setAllAttributes(node, attributes) {
  3102. Object.entries(attributes).forEach(_ref => {
  3103. let [name, value] = _ref;
  3104. return attributeExpression(node, {
  3105. name
  3106. }, value);
  3107. });
  3108. }
  3109. /**
  3110. * Remove all the attributes provided
  3111. * @param {HTMLElement} node - target node
  3112. * @param {Object} newAttributes - object containing all the new attribute names
  3113. * @param {Object} oldAttributes - object containing all the old attribute names
  3114. * @returns {undefined} sorry it's a void function :(
  3115. */
  3116. function removeAllAttributes(node, newAttributes, oldAttributes) {
  3117. const newKeys = newAttributes ? Object.keys(newAttributes) : [];
  3118. Object.keys(oldAttributes).filter(name => !newKeys.includes(name)).forEach(attribute => node.removeAttribute(attribute));
  3119. }
  3120. /**
  3121. * Check whether the attribute value can be rendered
  3122. * @param {*} value - expression value
  3123. * @returns {boolean} true if we can render this attribute value
  3124. */
  3125. function canRenderAttribute(value) {
  3126. return value === true || ['string', 'number'].includes(typeof value);
  3127. }
  3128. /**
  3129. * Check whether the attribute should be removed
  3130. * @param {*} value - expression value
  3131. * @returns {boolean} boolean - true if the attribute can be removed}
  3132. */
  3133. function shouldRemoveAttribute(value) {
  3134. return !value && value !== 0;
  3135. }
  3136. /**
  3137. * This methods handles the DOM attributes updates
  3138. * @param {HTMLElement} node - target node
  3139. * @param {Object} expression - expression object
  3140. * @param {string} expression.name - attribute name
  3141. * @param {*} value - new expression value
  3142. * @param {*} oldValue - the old expression cached value
  3143. * @returns {undefined}
  3144. */
  3145. function attributeExpression(node, _ref2, value, oldValue) {
  3146. let {
  3147. name
  3148. } = _ref2;
  3149. // is it a spread operator? {...attributes}
  3150. if (!name) {
  3151. if (oldValue) {
  3152. // remove all the old attributes
  3153. removeAllAttributes(node, value, oldValue);
  3154. } // is the value still truthy?
  3155. if (value) {
  3156. setAllAttributes(node, value);
  3157. }
  3158. return;
  3159. } // handle boolean attributes
  3160. if (!isNativeHtmlProperty(name) && (isBoolean(value) || isObject(value) || isFunction(value))) {
  3161. node[name] = value;
  3162. }
  3163. if (shouldRemoveAttribute(value)) {
  3164. node.removeAttribute(name);
  3165. } else if (canRenderAttribute(value)) {
  3166. node.setAttribute(name, normalizeValue(name, value));
  3167. }
  3168. }
  3169. /**
  3170. * Get the value as string
  3171. * @param {string} name - attribute name
  3172. * @param {*} value - user input value
  3173. * @returns {string} input value as string
  3174. */
  3175. function normalizeValue(name, value) {
  3176. // be sure that expressions like selected={ true } will be always rendered as selected='selected'
  3177. return value === true ? name : value;
  3178. }
  3179. const RE_EVENTS_PREFIX = /^on/;
  3180. 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
  3181. const EventListener = {
  3182. handleEvent(event) {
  3183. this[event.type](event);
  3184. }
  3185. };
  3186. const ListenersWeakMap = new WeakMap();
  3187. const createListener = node => {
  3188. const listener = Object.create(EventListener);
  3189. ListenersWeakMap.set(node, listener);
  3190. return listener;
  3191. };
  3192. /**
  3193. * Set a new event listener
  3194. * @param {HTMLElement} node - target node
  3195. * @param {Object} expression - expression object
  3196. * @param {string} expression.name - event name
  3197. * @param {*} value - new expression value
  3198. * @returns {value} the callback just received
  3199. */
  3200. function eventExpression(node, _ref, value) {
  3201. let {
  3202. name
  3203. } = _ref;
  3204. const normalizedEventName = name.replace(RE_EVENTS_PREFIX, '');
  3205. const eventListener = ListenersWeakMap.get(node) || createListener(node);
  3206. const [callback, options] = getCallbackAndOptions(value);
  3207. const handler = eventListener[normalizedEventName];
  3208. const mustRemoveEvent = handler && !callback;
  3209. const mustAddEvent = callback && !handler;
  3210. if (mustRemoveEvent) {
  3211. node.removeEventListener(normalizedEventName, eventListener);
  3212. }
  3213. if (mustAddEvent) {
  3214. node.addEventListener(normalizedEventName, eventListener, options);
  3215. }
  3216. eventListener[normalizedEventName] = callback;
  3217. }
  3218. /**
  3219. * Normalize the user value in order to render a empty string in case of falsy values
  3220. * @param {*} value - user input value
  3221. * @returns {string} hopefully a string
  3222. */
  3223. function normalizeStringValue(value) {
  3224. return isNil(value) ? '' : value;
  3225. }
  3226. /**
  3227. * Get the the target text node to update or create one from of a comment node
  3228. * @param {HTMLElement} node - any html element containing childNodes
  3229. * @param {number} childNodeIndex - index of the text node in the childNodes list
  3230. * @returns {Text} the text node to update
  3231. */
  3232. const getTextNode = (node, childNodeIndex) => {
  3233. const target = node.childNodes[childNodeIndex];
  3234. if (target.nodeType === Node.COMMENT_NODE) {
  3235. const textNode = document.createTextNode('');
  3236. node.replaceChild(textNode, target);
  3237. return textNode;
  3238. }
  3239. return target;
  3240. };
  3241. /**
  3242. * This methods handles a simple text expression update
  3243. * @param {HTMLElement} node - target node
  3244. * @param {Object} data - expression object
  3245. * @param {*} value - new expression value
  3246. * @returns {undefined}
  3247. */
  3248. function textExpression(node, data, value) {
  3249. node.data = normalizeStringValue(value);
  3250. }
  3251. /**
  3252. * This methods handles the input fileds value updates
  3253. * @param {HTMLElement} node - target node
  3254. * @param {Object} expression - expression object
  3255. * @param {*} value - new expression value
  3256. * @returns {undefined}
  3257. */
  3258. function valueExpression(node, expression, value) {
  3259. node.value = normalizeStringValue(value);
  3260. }
  3261. var expressions = {
  3262. [ATTRIBUTE]: attributeExpression,
  3263. [EVENT]: eventExpression,
  3264. [TEXT]: textExpression,
  3265. [VALUE]: valueExpression
  3266. };
  3267. const Expression = {
  3268. // Static props
  3269. // node: null,
  3270. // value: null,
  3271. // API methods
  3272. /**
  3273. * Mount the expression evaluating its initial value
  3274. * @param {*} scope - argument passed to the expression to evaluate its current values
  3275. * @returns {Expression} self
  3276. */
  3277. mount(scope) {
  3278. // hopefully a pure function
  3279. this.value = this.evaluate(scope); // IO() DOM updates
  3280. apply(this, this.value);
  3281. return this;
  3282. },
  3283. /**
  3284. * Update the expression if its value changed
  3285. * @param {*} scope - argument passed to the expression to evaluate its current values
  3286. * @returns {Expression} self
  3287. */
  3288. update(scope) {
  3289. // pure function
  3290. const value = this.evaluate(scope);
  3291. if (this.value !== value) {
  3292. // IO() DOM updates
  3293. apply(this, value);
  3294. this.value = value;
  3295. }
  3296. return this;
  3297. },
  3298. /**
  3299. * Expression teardown method
  3300. * @returns {Expression} self
  3301. */
  3302. unmount() {
  3303. // unmount only the event handling expressions
  3304. if (this.type === EVENT) apply(this, null);
  3305. return this;
  3306. }
  3307. };
  3308. /**
  3309. * IO() function to handle the DOM updates
  3310. * @param {Expression} expression - expression object
  3311. * @param {*} value - current expression value
  3312. * @returns {undefined}
  3313. */
  3314. function apply(expression, value) {
  3315. return expressions[expression.type](expression.node, expression, value, expression.value);
  3316. }
  3317. function create$4(node, data) {
  3318. return Object.assign({}, Expression, data, {
  3319. node: data.type === TEXT ? getTextNode(node, data.childNodeIndex) : node
  3320. });
  3321. }
  3322. /**
  3323. * Create a flat object having as keys a list of methods that if dispatched will propagate
  3324. * on the whole collection
  3325. * @param {Array} collection - collection to iterate
  3326. * @param {Array<string>} methods - methods to execute on each item of the collection
  3327. * @param {*} context - context returned by the new methods created
  3328. * @returns {Object} a new object to simplify the the nested methods dispatching
  3329. */
  3330. function flattenCollectionMethods(collection, methods, context) {
  3331. return methods.reduce((acc, method) => {
  3332. return Object.assign({}, acc, {
  3333. [method]: scope => {
  3334. return collection.map(item => item[method](scope)) && context;
  3335. }
  3336. });
  3337. }, {});
  3338. }
  3339. function create$3(node, _ref) {
  3340. let {
  3341. expressions
  3342. } = _ref;
  3343. return Object.assign({}, flattenCollectionMethods(expressions.map(expression => create$4(node, expression)), ['mount', 'update', 'unmount']));
  3344. }
  3345. function extendParentScope(attributes, scope, parentScope) {
  3346. if (!attributes || !attributes.length) return parentScope;
  3347. const expressions = attributes.map(attr => Object.assign({}, attr, {
  3348. value: attr.evaluate(scope)
  3349. }));
  3350. return Object.assign(Object.create(parentScope || null), evaluateAttributeExpressions(expressions));
  3351. } // this function is only meant to fix an edge case
  3352. // https://github.com/riot/riot/issues/2842
  3353. const getRealParent = (scope, parentScope) => scope[PARENT_KEY_SYMBOL] || parentScope;
  3354. const SlotBinding = {
  3355. // dynamic binding properties
  3356. // node: null,
  3357. // name: null,
  3358. attributes: [],
  3359. // template: null,
  3360. getTemplateScope(scope, parentScope) {
  3361. return extendParentScope(this.attributes, scope, parentScope);
  3362. },
  3363. // API methods
  3364. mount(scope, parentScope) {
  3365. const templateData = scope.slots ? scope.slots.find(_ref => {
  3366. let {
  3367. id
  3368. } = _ref;
  3369. return id === this.name;
  3370. }) : false;
  3371. const {
  3372. parentNode
  3373. } = this.node;
  3374. const realParent = getRealParent(scope, parentScope);
  3375. this.template = templateData && create(templateData.html, templateData.bindings).createDOM(parentNode);
  3376. if (this.template) {
  3377. cleanNode(this.node);
  3378. this.template.mount(this.node, this.getTemplateScope(scope, realParent), realParent);
  3379. this.template.children = Array.from(this.node.childNodes);
  3380. }
  3381. moveSlotInnerContent(this.node);
  3382. removeChild(this.node);
  3383. return this;
  3384. },
  3385. update(scope, parentScope) {
  3386. if (this.template) {
  3387. const realParent = getRealParent(scope, parentScope);
  3388. this.template.update(this.getTemplateScope(scope, realParent), realParent);
  3389. }
  3390. return this;
  3391. },
  3392. unmount(scope, parentScope, mustRemoveRoot) {
  3393. if (this.template) {
  3394. this.template.unmount(this.getTemplateScope(scope, parentScope), null, mustRemoveRoot);
  3395. }
  3396. return this;
  3397. }
  3398. };
  3399. /**
  3400. * Move the inner content of the slots outside of them
  3401. * @param {HTMLElement} slot - slot node
  3402. * @returns {undefined} it's a void method ¯\_()_/¯
  3403. */
  3404. function moveSlotInnerContent(slot) {
  3405. const child = slot && slot.firstChild;
  3406. if (!child) return;
  3407. insertBefore(child, slot);
  3408. moveSlotInnerContent(slot);
  3409. }
  3410. /**
  3411. * Create a single slot binding
  3412. * @param {HTMLElement} node - slot node
  3413. * @param {string} name - slot id
  3414. * @param {AttributeExpressionData[]} attributes - slot attributes
  3415. * @returns {Object} Slot binding object
  3416. */
  3417. function createSlot(node, _ref2) {
  3418. let {
  3419. name,
  3420. attributes
  3421. } = _ref2;
  3422. return Object.assign({}, SlotBinding, {
  3423. attributes,
  3424. node,
  3425. name
  3426. });
  3427. }
  3428. /**
  3429. * Create a new tag object if it was registered before, otherwise fallback to the simple
  3430. * template chunk
  3431. * @param {Function} component - component factory function
  3432. * @param {Array<Object>} slots - array containing the slots markup
  3433. * @param {Array} attributes - dynamic attributes that will be received by the tag element
  3434. * @returns {TagImplementation|TemplateChunk} a tag implementation or a template chunk as fallback
  3435. */
  3436. function getTag(component, slots, attributes) {
  3437. if (slots === void 0) {
  3438. slots = [];
  3439. }
  3440. if (attributes === void 0) {
  3441. attributes = [];
  3442. }
  3443. // if this tag was registered before we will return its implementation
  3444. if (component) {
  3445. return component({
  3446. slots,
  3447. attributes
  3448. });
  3449. } // otherwise we return a template chunk
  3450. return create(slotsToMarkup(slots), [...slotBindings(slots), {
  3451. // the attributes should be registered as binding
  3452. // if we fallback to a normal template chunk
  3453. expressions: attributes.map(attr => {
  3454. return Object.assign({
  3455. type: ATTRIBUTE
  3456. }, attr);
  3457. })
  3458. }]);
  3459. }
  3460. /**
  3461. * Merge all the slots bindings into a single array
  3462. * @param {Array<Object>} slots - slots collection
  3463. * @returns {Array<Bindings>} flatten bindings array
  3464. */
  3465. function slotBindings(slots) {
  3466. return slots.reduce((acc, _ref) => {
  3467. let {
  3468. bindings
  3469. } = _ref;
  3470. return acc.concat(bindings);
  3471. }, []);
  3472. }
  3473. /**
  3474. * Merge all the slots together in a single markup string
  3475. * @param {Array<Object>} slots - slots collection
  3476. * @returns {string} markup of all the slots in a single string
  3477. */
  3478. function slotsToMarkup(slots) {
  3479. return slots.reduce((acc, slot) => {
  3480. return acc + slot.html;
  3481. }, '');
  3482. }
  3483. const TagBinding = {
  3484. // dynamic binding properties
  3485. // node: null,
  3486. // evaluate: null,
  3487. // name: null,
  3488. // slots: null,
  3489. // tag: null,
  3490. // attributes: null,
  3491. // getComponent: null,
  3492. mount(scope) {
  3493. return this.update(scope);
  3494. },
  3495. update(scope, parentScope) {
  3496. const name = this.evaluate(scope); // simple update
  3497. if (name && name === this.name) {
  3498. this.tag.update(scope);
  3499. } else {
  3500. // unmount the old tag if it exists
  3501. this.unmount(scope, parentScope, true); // mount the new tag
  3502. this.name = name;
  3503. this.tag = getTag(this.getComponent(name), this.slots, this.attributes);
  3504. this.tag.mount(this.node, scope);
  3505. }
  3506. return this;
  3507. },
  3508. unmount(scope, parentScope, keepRootTag) {
  3509. if (this.tag) {
  3510. // keep the root tag
  3511. this.tag.unmount(keepRootTag);
  3512. }
  3513. return this;
  3514. }
  3515. };
  3516. function create$2(node, _ref2) {
  3517. let {
  3518. evaluate,
  3519. getComponent,
  3520. slots,
  3521. attributes
  3522. } = _ref2;
  3523. return Object.assign({}, TagBinding, {
  3524. node,
  3525. evaluate,
  3526. slots,
  3527. attributes,
  3528. getComponent
  3529. });
  3530. }
  3531. var bindings = {
  3532. [IF]: create$5,
  3533. [SIMPLE]: create$3,
  3534. [EACH]: create$6,
  3535. [TAG]: create$2,
  3536. [SLOT]: createSlot
  3537. };
  3538. /**
  3539. * Text expressions in a template tag will get childNodeIndex value normalized
  3540. * depending on the position of the <template> tag offset
  3541. * @param {Expression[]} expressions - riot expressions array
  3542. * @param {number} textExpressionsOffset - offset of the <template> tag
  3543. * @returns {Expression[]} expressions containing the text expressions normalized
  3544. */
  3545. function fixTextExpressionsOffset(expressions, textExpressionsOffset) {
  3546. return expressions.map(e => e.type === TEXT ? Object.assign({}, e, {
  3547. childNodeIndex: e.childNodeIndex + textExpressionsOffset
  3548. }) : e);
  3549. }
  3550. /**
  3551. * Bind a new expression object to a DOM node
  3552. * @param {HTMLElement} root - DOM node where to bind the expression
  3553. * @param {TagBindingData} binding - binding data
  3554. * @param {number|null} templateTagOffset - if it's defined we need to fix the text expressions childNodeIndex offset
  3555. * @returns {Binding} Binding object
  3556. */
  3557. function create$1(root, binding, templateTagOffset) {
  3558. const {
  3559. selector,
  3560. type,
  3561. redundantAttribute,
  3562. expressions
  3563. } = binding; // find the node to apply the bindings
  3564. const node = selector ? root.querySelector(selector) : root; // remove eventually additional attributes created only to select this node
  3565. if (redundantAttribute) node.removeAttribute(redundantAttribute);
  3566. const bindingExpressions = expressions || []; // init the binding
  3567. return (bindings[type] || bindings[SIMPLE])(node, Object.assign({}, binding, {
  3568. expressions: templateTagOffset && !selector ? fixTextExpressionsOffset(bindingExpressions, templateTagOffset) : bindingExpressions
  3569. }));
  3570. }
  3571. function createHTMLTree(html, root) {
  3572. const template = isTemplate(root) ? root : document.createElement('template');
  3573. template.innerHTML = html;
  3574. return template.content;
  3575. } // for svg nodes we need a bit more work
  3576. function createSVGTree(html, container) {
  3577. // create the SVGNode
  3578. const svgNode = container.ownerDocument.importNode(new window.DOMParser().parseFromString(`<svg xmlns="http://www.w3.org/2000/svg">${html}</svg>`, 'application/xml').documentElement, true);
  3579. return svgNode;
  3580. }
  3581. /**
  3582. * Create the DOM that will be injected
  3583. * @param {Object} root - DOM node to find out the context where the fragment will be created
  3584. * @param {string} html - DOM to create as string
  3585. * @returns {HTMLDocumentFragment|HTMLElement} a new html fragment
  3586. */
  3587. function createDOMTree(root, html) {
  3588. if (isSvg(root)) return createSVGTree(html, root);
  3589. return createHTMLTree(html, root);
  3590. }
  3591. /**
  3592. * Inject the DOM tree into a target node
  3593. * @param {HTMLElement} el - target element
  3594. * @param {DocumentFragment|SVGElement} dom - dom tree to inject
  3595. * @returns {undefined}
  3596. */
  3597. function injectDOM(el, dom) {
  3598. switch (true) {
  3599. case isSvg(el):
  3600. moveChildren(dom, el);
  3601. break;
  3602. case isTemplate(el):
  3603. el.parentNode.replaceChild(dom, el);
  3604. break;
  3605. default:
  3606. el.appendChild(dom);
  3607. }
  3608. }
  3609. /**
  3610. * Create the Template DOM skeleton
  3611. * @param {HTMLElement} el - root node where the DOM will be injected
  3612. * @param {string|HTMLElement} html - HTML markup or HTMLElement that will be injected into the root node
  3613. * @returns {?DocumentFragment} fragment that will be injected into the root node
  3614. */
  3615. function createTemplateDOM(el, html) {
  3616. return html && (typeof html === 'string' ? createDOMTree(el, html) : html);
  3617. }
  3618. /**
  3619. * Get the offset of the <template> tag
  3620. * @param {HTMLElement} parentNode - template tag parent node
  3621. * @param {HTMLElement} el - the template tag we want to render
  3622. * @param {Object} meta - meta properties needed to handle the <template> tags in loops
  3623. * @returns {number} offset of the <template> tag calculated from its siblings DOM nodes
  3624. */
  3625. function getTemplateTagOffset(parentNode, el, meta) {
  3626. const siblings = Array.from(parentNode.childNodes);
  3627. return Math.max(siblings.indexOf(el), siblings.indexOf(meta.head) + 1, 0);
  3628. }
  3629. /**
  3630. * Template Chunk model
  3631. * @type {Object}
  3632. */
  3633. const TemplateChunk = Object.freeze({
  3634. // Static props
  3635. // bindings: null,
  3636. // bindingsData: null,
  3637. // html: null,
  3638. // isTemplateTag: false,
  3639. // fragment: null,
  3640. // children: null,
  3641. // dom: null,
  3642. // el: null,
  3643. /**
  3644. * Create the template DOM structure that will be cloned on each mount
  3645. * @param {HTMLElement} el - the root node
  3646. * @returns {TemplateChunk} self
  3647. */
  3648. createDOM(el) {
  3649. // make sure that the DOM gets created before cloning the template
  3650. this.dom = this.dom || createTemplateDOM(el, this.html) || document.createDocumentFragment();
  3651. return this;
  3652. },
  3653. // API methods
  3654. /**
  3655. * Attach the template to a DOM node
  3656. * @param {HTMLElement} el - target DOM node
  3657. * @param {*} scope - template data
  3658. * @param {*} parentScope - scope of the parent template tag
  3659. * @param {Object} meta - meta properties needed to handle the <template> tags in loops
  3660. * @returns {TemplateChunk} self
  3661. */
  3662. mount(el, scope, parentScope, meta) {
  3663. if (meta === void 0) {
  3664. meta = {};
  3665. }
  3666. if (!el) throw new Error('Please provide DOM node to mount properly your template');
  3667. if (this.el) this.unmount(scope); // <template> tags require a bit more work
  3668. // the template fragment might be already created via meta outside of this call
  3669. const {
  3670. fragment,
  3671. children,
  3672. avoidDOMInjection
  3673. } = meta; // <template> bindings of course can not have a root element
  3674. // so we check the parent node to set the query selector bindings
  3675. const {
  3676. parentNode
  3677. } = children ? children[0] : el;
  3678. const isTemplateTag = isTemplate(el);
  3679. const templateTagOffset = isTemplateTag ? getTemplateTagOffset(parentNode, el, meta) : null; // create the DOM if it wasn't created before
  3680. this.createDOM(el); // create the DOM of this template cloning the original DOM structure stored in this instance
  3681. // notice that if a documentFragment was passed (via meta) we will use it instead
  3682. const cloneNode = fragment || this.dom.cloneNode(true); // store root node
  3683. // notice that for template tags the root note will be the parent tag
  3684. this.el = isTemplateTag ? parentNode : el; // create the children array only for the <template> fragments
  3685. this.children = isTemplateTag ? children || Array.from(cloneNode.childNodes) : null; // inject the DOM into the el only if a fragment is available
  3686. if (!avoidDOMInjection && cloneNode) injectDOM(el, cloneNode); // create the bindings
  3687. this.bindings = this.bindingsData.map(binding => create$1(this.el, binding, templateTagOffset));
  3688. this.bindings.forEach(b => b.mount(scope, parentScope)); // store the template meta properties
  3689. this.meta = meta;
  3690. return this;
  3691. },
  3692. /**
  3693. * Update the template with fresh data
  3694. * @param {*} scope - template data
  3695. * @param {*} parentScope - scope of the parent template tag
  3696. * @returns {TemplateChunk} self
  3697. */
  3698. update(scope, parentScope) {
  3699. this.bindings.forEach(b => b.update(scope, parentScope));
  3700. return this;
  3701. },
  3702. /**
  3703. * Remove the template from the node where it was initially mounted
  3704. * @param {*} scope - template data
  3705. * @param {*} parentScope - scope of the parent template tag
  3706. * @param {boolean|null} mustRemoveRoot - if true remove the root element,
  3707. * if false or undefined clean the root tag content, if null don't touch the DOM
  3708. * @returns {TemplateChunk} self
  3709. */
  3710. unmount(scope, parentScope, mustRemoveRoot) {
  3711. if (mustRemoveRoot === void 0) {
  3712. mustRemoveRoot = false;
  3713. }
  3714. const el = this.el;
  3715. if (!el) {
  3716. return this;
  3717. }
  3718. this.bindings.forEach(b => b.unmount(scope, parentScope, mustRemoveRoot));
  3719. switch (true) {
  3720. // pure components should handle the DOM unmount updates by themselves
  3721. // for mustRemoveRoot === null don't touch the DOM
  3722. case el[IS_PURE_SYMBOL] || mustRemoveRoot === null:
  3723. break;
  3724. // if children are declared, clear them
  3725. // applicable for <template> and <slot/> bindings
  3726. case Array.isArray(this.children):
  3727. clearChildren(this.children);
  3728. break;
  3729. // clean the node children only
  3730. case !mustRemoveRoot:
  3731. cleanNode(el);
  3732. break;
  3733. // remove the root node only if the mustRemoveRoot is truly
  3734. case !!mustRemoveRoot:
  3735. removeChild(el);
  3736. break;
  3737. }
  3738. this.el = null;
  3739. return this;
  3740. },
  3741. /**
  3742. * Clone the template chunk
  3743. * @returns {TemplateChunk} a clone of this object resetting the this.el property
  3744. */
  3745. clone() {
  3746. return Object.assign({}, this, {
  3747. meta: {},
  3748. el: null
  3749. });
  3750. }
  3751. });
  3752. /**
  3753. * Create a template chunk wiring also the bindings
  3754. * @param {string|HTMLElement} html - template string
  3755. * @param {BindingData[]} bindings - bindings collection
  3756. * @returns {TemplateChunk} a new TemplateChunk copy
  3757. */
  3758. function create(html, bindings) {
  3759. if (bindings === void 0) {
  3760. bindings = [];
  3761. }
  3762. return Object.assign({}, TemplateChunk, {
  3763. html,
  3764. bindingsData: bindings
  3765. });
  3766. }
  3767. /**
  3768. * Method used to bind expressions to a DOM node
  3769. * @param {string|HTMLElement} html - your static template html structure
  3770. * @param {Array} bindings - list of the expressions to bind to update the markup
  3771. * @returns {TemplateChunk} a new TemplateChunk object having the `update`,`mount`, `unmount` and `clone` methods
  3772. *
  3773. * @example
  3774. *
  3775. * riotDOMBindings
  3776. * .template(
  3777. * `<div expr0><!----></div><div><p expr1><!----><section expr2></section></p>`,
  3778. * [
  3779. * {
  3780. * selector: '[expr0]',
  3781. * redundantAttribute: 'expr0',
  3782. * expressions: [
  3783. * {
  3784. * type: expressionTypes.TEXT,
  3785. * childNodeIndex: 0,
  3786. * evaluate(scope) {
  3787. * return scope.time;
  3788. * },
  3789. * },
  3790. * ],
  3791. * },
  3792. * {
  3793. * selector: '[expr1]',
  3794. * redundantAttribute: 'expr1',
  3795. * expressions: [
  3796. * {
  3797. * type: expressionTypes.TEXT,
  3798. * childNodeIndex: 0,
  3799. * evaluate(scope) {
  3800. * return scope.name;
  3801. * },
  3802. * },
  3803. * {
  3804. * type: 'attribute',
  3805. * name: 'style',
  3806. * evaluate(scope) {
  3807. * return scope.style;
  3808. * },
  3809. * },
  3810. * ],
  3811. * },
  3812. * {
  3813. * selector: '[expr2]',
  3814. * redundantAttribute: 'expr2',
  3815. * type: bindingTypes.IF,
  3816. * evaluate(scope) {
  3817. * return scope.isVisible;
  3818. * },
  3819. * template: riotDOMBindings.template('hello there'),
  3820. * },
  3821. * ]
  3822. * )
  3823. */
  3824. var DOMBindings = /*#__PURE__*/Object.freeze({
  3825. __proto__: null,
  3826. template: create,
  3827. createBinding: create$1,
  3828. createExpression: create$4,
  3829. bindingTypes: bindingTypes,
  3830. expressionTypes: expressionTypes
  3831. });
  3832. function noop() {
  3833. return this;
  3834. }
  3835. /**
  3836. * Autobind the methods of a source object to itself
  3837. * @param {Object} source - probably a riot tag instance
  3838. * @param {Array<string>} methods - list of the methods to autobind
  3839. * @returns {Object} the original object received
  3840. */
  3841. function autobindMethods(source, methods) {
  3842. methods.forEach(method => {
  3843. source[method] = source[method].bind(source);
  3844. });
  3845. return source;
  3846. }
  3847. /**
  3848. * Call the first argument received only if it's a function otherwise return it as it is
  3849. * @param {*} source - anything
  3850. * @returns {*} anything
  3851. */
  3852. function callOrAssign(source) {
  3853. return isFunction(source) ? source.prototype && source.prototype.constructor ? new source() : source() : source;
  3854. }
  3855. /**
  3856. * Converts any DOM node/s to a loopable array
  3857. * @param { HTMLElement|NodeList } els - single html element or a node list
  3858. * @returns { Array } always a loopable object
  3859. */
  3860. function domToArray(els) {
  3861. // can this object be already looped?
  3862. if (!Array.isArray(els)) {
  3863. // is it a node list?
  3864. 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
  3865. // it will be returned as "array" with one single entry
  3866. return [els];
  3867. } // this object could be looped out of the box
  3868. return els;
  3869. }
  3870. /**
  3871. * Simple helper to find DOM nodes returning them as array like loopable object
  3872. * @param { string|DOMNodeList } selector - either the query or the DOM nodes to arraify
  3873. * @param { HTMLElement } ctx - context defining where the query will search for the DOM nodes
  3874. * @returns { Array } DOM nodes found as array
  3875. */
  3876. function $(selector, ctx) {
  3877. return domToArray(typeof selector === 'string' ? (ctx || document).querySelectorAll(selector) : selector);
  3878. }
  3879. /**
  3880. * Normalize the return values, in case of a single value we avoid to return an array
  3881. * @param { Array } values - list of values we want to return
  3882. * @returns { Array|string|boolean } either the whole list of values or the single one found
  3883. * @private
  3884. */
  3885. const normalize = values => values.length === 1 ? values[0] : values;
  3886. /**
  3887. * Parse all the nodes received to get/remove/check their attributes
  3888. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  3889. * @param { string|Array } name - name or list of attributes
  3890. * @param { string } method - method that will be used to parse the attributes
  3891. * @returns { Array|string } result of the parsing in a list or a single value
  3892. * @private
  3893. */
  3894. function parseNodes(els, name, method) {
  3895. const names = typeof name === 'string' ? [name] : name;
  3896. return normalize(domToArray(els).map(el => {
  3897. return normalize(names.map(n => el[method](n)));
  3898. }));
  3899. }
  3900. /**
  3901. * Set any attribute on a single or a list of DOM nodes
  3902. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  3903. * @param { string|Object } name - either the name of the attribute to set
  3904. * or a list of properties as object key - value
  3905. * @param { string } value - the new value of the attribute (optional)
  3906. * @returns { HTMLElement|NodeList|Array } the original array of elements passed to this function
  3907. *
  3908. * @example
  3909. *
  3910. * import { set } from 'bianco.attr'
  3911. *
  3912. * const img = document.createElement('img')
  3913. *
  3914. * set(img, 'width', 100)
  3915. *
  3916. * // or also
  3917. * set(img, {
  3918. * width: 300,
  3919. * height: 300
  3920. * })
  3921. *
  3922. */
  3923. function set(els, name, value) {
  3924. const attrs = typeof name === 'object' ? name : {
  3925. [name]: value
  3926. };
  3927. const props = Object.keys(attrs);
  3928. domToArray(els).forEach(el => {
  3929. props.forEach(prop => el.setAttribute(prop, attrs[prop]));
  3930. });
  3931. return els;
  3932. }
  3933. /**
  3934. * Get any attribute from a single or a list of DOM nodes
  3935. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  3936. * @param { string|Array } name - name or list of attributes to get
  3937. * @returns { Array|string } list of the attributes found
  3938. *
  3939. * @example
  3940. *
  3941. * import { get } from 'bianco.attr'
  3942. *
  3943. * const img = document.createElement('img')
  3944. *
  3945. * get(img, 'width') // => '200'
  3946. *
  3947. * // or also
  3948. * get(img, ['width', 'height']) // => ['200', '300']
  3949. *
  3950. * // or also
  3951. * get([img1, img2], ['width', 'height']) // => [['200', '300'], ['500', '200']]
  3952. */
  3953. function get(els, name) {
  3954. return parseNodes(els, name, 'getAttribute');
  3955. }
  3956. const CSS_BY_NAME = new Map();
  3957. const STYLE_NODE_SELECTOR = 'style[riot]'; // memoized curried function
  3958. const getStyleNode = (style => {
  3959. return () => {
  3960. // lazy evaluation:
  3961. // if this function was already called before
  3962. // we return its cached result
  3963. if (style) return style; // create a new style element or use an existing one
  3964. // and cache it internally
  3965. style = $(STYLE_NODE_SELECTOR)[0] || document.createElement('style');
  3966. set(style, 'type', 'text/css');
  3967. /* istanbul ignore next */
  3968. if (!style.parentNode) document.head.appendChild(style);
  3969. return style;
  3970. };
  3971. })();
  3972. /**
  3973. * Object that will be used to inject and manage the css of every tag instance
  3974. */
  3975. var cssManager = {
  3976. CSS_BY_NAME,
  3977. /**
  3978. * Save a tag style to be later injected into DOM
  3979. * @param { string } name - if it's passed we will map the css to a tagname
  3980. * @param { string } css - css string
  3981. * @returns {Object} self
  3982. */
  3983. add(name, css) {
  3984. if (!CSS_BY_NAME.has(name)) {
  3985. CSS_BY_NAME.set(name, css);
  3986. this.inject();
  3987. }
  3988. return this;
  3989. },
  3990. /**
  3991. * Inject all previously saved tag styles into DOM
  3992. * innerHTML seems slow: http://jsperf.com/riot-insert-style
  3993. * @returns {Object} self
  3994. */
  3995. inject() {
  3996. getStyleNode().innerHTML = [...CSS_BY_NAME.values()].join('\n');
  3997. return this;
  3998. },
  3999. /**
  4000. * Remove a tag style from the DOM
  4001. * @param {string} name a registered tagname
  4002. * @returns {Object} self
  4003. */
  4004. remove(name) {
  4005. if (CSS_BY_NAME.has(name)) {
  4006. CSS_BY_NAME.delete(name);
  4007. this.inject();
  4008. }
  4009. return this;
  4010. }
  4011. };
  4012. /**
  4013. * Function to curry any javascript method
  4014. * @param {Function} fn - the target function we want to curry
  4015. * @param {...[args]} acc - initial arguments
  4016. * @returns {Function|*} it will return a function until the target function
  4017. * will receive all of its arguments
  4018. */
  4019. function curry(fn) {
  4020. for (var _len = arguments.length, acc = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4021. acc[_key - 1] = arguments[_key];
  4022. }
  4023. return function () {
  4024. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  4025. args[_key2] = arguments[_key2];
  4026. }
  4027. args = [...acc, ...args];
  4028. return args.length < fn.length ? curry(fn, ...args) : fn(...args);
  4029. };
  4030. }
  4031. /**
  4032. * Get the tag name of any DOM node
  4033. * @param {HTMLElement} element - DOM node we want to inspect
  4034. * @returns {string} name to identify this dom node in riot
  4035. */
  4036. function getName(element) {
  4037. return get(element, IS_DIRECTIVE) || element.tagName.toLowerCase();
  4038. }
  4039. const COMPONENT_CORE_HELPERS = Object.freeze({
  4040. // component helpers
  4041. $(selector) {
  4042. return $(selector, this.root)[0];
  4043. },
  4044. $$(selector) {
  4045. return $(selector, this.root);
  4046. }
  4047. });
  4048. const PURE_COMPONENT_API = Object.freeze({
  4049. [MOUNT_METHOD_KEY]: noop,
  4050. [UPDATE_METHOD_KEY]: noop,
  4051. [UNMOUNT_METHOD_KEY]: noop
  4052. });
  4053. const COMPONENT_LIFECYCLE_METHODS = Object.freeze({
  4054. [SHOULD_UPDATE_KEY]: noop,
  4055. [ON_BEFORE_MOUNT_KEY]: noop,
  4056. [ON_MOUNTED_KEY]: noop,
  4057. [ON_BEFORE_UPDATE_KEY]: noop,
  4058. [ON_UPDATED_KEY]: noop,
  4059. [ON_BEFORE_UNMOUNT_KEY]: noop,
  4060. [ON_UNMOUNTED_KEY]: noop
  4061. });
  4062. const MOCKED_TEMPLATE_INTERFACE = Object.assign({}, PURE_COMPONENT_API, {
  4063. clone: noop,
  4064. createDOM: noop
  4065. });
  4066. /**
  4067. * Performance optimization for the recursive components
  4068. * @param {RiotComponentWrapper} componentWrapper - riot compiler generated object
  4069. * @returns {Object} component like interface
  4070. */
  4071. const memoizedCreateComponent = memoize(createComponent);
  4072. /**
  4073. * Evaluate the component properties either from its real attributes or from its initial user properties
  4074. * @param {HTMLElement} element - component root
  4075. * @param {Object} initialProps - initial props
  4076. * @returns {Object} component props key value pairs
  4077. */
  4078. function evaluateInitialProps(element, initialProps) {
  4079. if (initialProps === void 0) {
  4080. initialProps = {};
  4081. }
  4082. return Object.assign({}, DOMattributesToObject(element), callOrAssign(initialProps));
  4083. }
  4084. /**
  4085. * Bind a DOM node to its component object
  4086. * @param {HTMLElement} node - html node mounted
  4087. * @param {Object} component - Riot.js component object
  4088. * @returns {Object} the component object received as second argument
  4089. */
  4090. const bindDOMNodeToComponentObject = (node, component) => node[DOM_COMPONENT_INSTANCE_PROPERTY$1] = component;
  4091. /**
  4092. * Wrap the Riot.js core API methods using a mapping function
  4093. * @param {Function} mapFunction - lifting function
  4094. * @returns {Object} an object having the { mount, update, unmount } functions
  4095. */
  4096. function createCoreAPIMethods(mapFunction) {
  4097. return [MOUNT_METHOD_KEY, UPDATE_METHOD_KEY, UNMOUNT_METHOD_KEY].reduce((acc, method) => {
  4098. acc[method] = mapFunction(method);
  4099. return acc;
  4100. }, {});
  4101. }
  4102. /**
  4103. * Factory function to create the component templates only once
  4104. * @param {Function} template - component template creation function
  4105. * @param {RiotComponentWrapper} componentWrapper - riot compiler generated object
  4106. * @returns {TemplateChunk} template chunk object
  4107. */
  4108. function componentTemplateFactory(template, componentWrapper) {
  4109. const components = createSubcomponents(componentWrapper.exports ? componentWrapper.exports.components : {});
  4110. return template(create, expressionTypes, bindingTypes, name => {
  4111. // improve support for recursive components
  4112. if (name === componentWrapper.name) return memoizedCreateComponent(componentWrapper); // return the registered components
  4113. return components[name] || COMPONENTS_IMPLEMENTATION_MAP$1.get(name);
  4114. });
  4115. }
  4116. /**
  4117. * Create a pure component
  4118. * @param {Function} pureFactoryFunction - pure component factory function
  4119. * @param {Array} options.slots - component slots
  4120. * @param {Array} options.attributes - component attributes
  4121. * @param {Array} options.template - template factory function
  4122. * @param {Array} options.template - template factory function
  4123. * @param {any} options.props - initial component properties
  4124. * @returns {Object} pure component object
  4125. */
  4126. function createPureComponent(pureFactoryFunction, _ref) {
  4127. let {
  4128. slots,
  4129. attributes,
  4130. props,
  4131. css,
  4132. template
  4133. } = _ref;
  4134. if (template) panic('Pure components can not have html');
  4135. if (css) panic('Pure components do not have css');
  4136. const component = defineDefaults(pureFactoryFunction({
  4137. slots,
  4138. attributes,
  4139. props
  4140. }), PURE_COMPONENT_API);
  4141. return createCoreAPIMethods(method => function () {
  4142. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  4143. args[_key] = arguments[_key];
  4144. }
  4145. // intercept the mount calls to bind the DOM node to the pure object created
  4146. // see also https://github.com/riot/riot/issues/2806
  4147. if (method === MOUNT_METHOD_KEY) {
  4148. const [el] = args; // mark this node as pure element
  4149. el[IS_PURE_SYMBOL] = true;
  4150. bindDOMNodeToComponentObject(el, component);
  4151. }
  4152. component[method](...args);
  4153. return component;
  4154. });
  4155. }
  4156. /**
  4157. * Create the component interface needed for the @riotjs/dom-bindings tag bindings
  4158. * @param {RiotComponentWrapper} componentWrapper - riot compiler generated object
  4159. * @param {string} componentWrapper.css - component css
  4160. * @param {Function} componentWrapper.template - function that will return the dom-bindings template function
  4161. * @param {Object} componentWrapper.exports - component interface
  4162. * @param {string} componentWrapper.name - component name
  4163. * @returns {Object} component like interface
  4164. */
  4165. function createComponent(componentWrapper) {
  4166. const {
  4167. css,
  4168. template,
  4169. exports,
  4170. name
  4171. } = componentWrapper;
  4172. const templateFn = template ? componentTemplateFactory(template, componentWrapper) : MOCKED_TEMPLATE_INTERFACE;
  4173. return _ref2 => {
  4174. let {
  4175. slots,
  4176. attributes,
  4177. props
  4178. } = _ref2;
  4179. // pure components rendering will be managed by the end user
  4180. if (exports && exports[IS_PURE_SYMBOL]) return createPureComponent(exports, {
  4181. slots,
  4182. attributes,
  4183. props,
  4184. css,
  4185. template
  4186. });
  4187. const componentAPI = callOrAssign(exports) || {};
  4188. const component = defineComponent({
  4189. css,
  4190. template: templateFn,
  4191. componentAPI,
  4192. name
  4193. })({
  4194. slots,
  4195. attributes,
  4196. props
  4197. }); // notice that for the components create via tag binding
  4198. // we need to invert the mount (state/parentScope) arguments
  4199. // the template bindings will only forward the parentScope updates
  4200. // and never deal with the component state
  4201. return {
  4202. mount(element, parentScope, state) {
  4203. return component.mount(element, state, parentScope);
  4204. },
  4205. update(parentScope, state) {
  4206. return component.update(state, parentScope);
  4207. },
  4208. unmount(preserveRoot) {
  4209. return component.unmount(preserveRoot);
  4210. }
  4211. };
  4212. };
  4213. }
  4214. /**
  4215. * Component definition function
  4216. * @param {Object} implementation - the componen implementation will be generated via compiler
  4217. * @param {Object} component - the component initial properties
  4218. * @returns {Object} a new component implementation object
  4219. */
  4220. function defineComponent(_ref3) {
  4221. let {
  4222. css,
  4223. template,
  4224. componentAPI,
  4225. name
  4226. } = _ref3;
  4227. // add the component css into the DOM
  4228. if (css && name) cssManager.add(name, css);
  4229. return curry(enhanceComponentAPI)(defineProperties( // set the component defaults without overriding the original component API
  4230. defineDefaults(componentAPI, Object.assign({}, COMPONENT_LIFECYCLE_METHODS, {
  4231. [PROPS_KEY]: {},
  4232. [STATE_KEY]: {}
  4233. })), Object.assign({
  4234. // defined during the component creation
  4235. [SLOTS_KEY]: null,
  4236. [ROOT_KEY]: null
  4237. }, COMPONENT_CORE_HELPERS, {
  4238. name,
  4239. css,
  4240. template
  4241. })));
  4242. }
  4243. /**
  4244. * Create the bindings to update the component attributes
  4245. * @param {HTMLElement} node - node where we will bind the expressions
  4246. * @param {Array} attributes - list of attribute bindings
  4247. * @returns {TemplateChunk} - template bindings object
  4248. */
  4249. function createAttributeBindings(node, attributes) {
  4250. if (attributes === void 0) {
  4251. attributes = [];
  4252. }
  4253. const expressions = attributes.map(a => create$4(node, a));
  4254. const binding = {};
  4255. return Object.assign(binding, Object.assign({
  4256. expressions
  4257. }, createCoreAPIMethods(method => scope => {
  4258. expressions.forEach(e => e[method](scope));
  4259. return binding;
  4260. })));
  4261. }
  4262. /**
  4263. * Create the subcomponents that can be included inside a tag in runtime
  4264. * @param {Object} components - components imported in runtime
  4265. * @returns {Object} all the components transformed into Riot.Component factory functions
  4266. */
  4267. function createSubcomponents(components) {
  4268. if (components === void 0) {
  4269. components = {};
  4270. }
  4271. return Object.entries(callOrAssign(components)).reduce((acc, _ref4) => {
  4272. let [key, value] = _ref4;
  4273. acc[camelToDashCase(key)] = createComponent(value);
  4274. return acc;
  4275. }, {});
  4276. }
  4277. /**
  4278. * Run the component instance through all the plugins set by the user
  4279. * @param {Object} component - component instance
  4280. * @returns {Object} the component enhanced by the plugins
  4281. */
  4282. function runPlugins(component) {
  4283. return [...PLUGINS_SET$1].reduce((c, fn) => fn(c) || c, component);
  4284. }
  4285. /**
  4286. * Compute the component current state merging it with its previous state
  4287. * @param {Object} oldState - previous state object
  4288. * @param {Object} newState - new state givent to the `update` call
  4289. * @returns {Object} new object state
  4290. */
  4291. function computeState(oldState, newState) {
  4292. return Object.assign({}, oldState, callOrAssign(newState));
  4293. }
  4294. /**
  4295. * Add eventually the "is" attribute to link this DOM node to its css
  4296. * @param {HTMLElement} element - target root node
  4297. * @param {string} name - name of the component mounted
  4298. * @returns {undefined} it's a void function
  4299. */
  4300. function addCssHook(element, name) {
  4301. if (getName(element) !== name) {
  4302. set(element, IS_DIRECTIVE, name);
  4303. }
  4304. }
  4305. /**
  4306. * Component creation factory function that will enhance the user provided API
  4307. * @param {Object} component - a component implementation previously defined
  4308. * @param {Array} options.slots - component slots generated via riot compiler
  4309. * @param {Array} options.attributes - attribute expressions generated via riot compiler
  4310. * @returns {Riot.Component} a riot component instance
  4311. */
  4312. function enhanceComponentAPI(component, _ref5) {
  4313. let {
  4314. slots,
  4315. attributes,
  4316. props
  4317. } = _ref5;
  4318. return autobindMethods(runPlugins(defineProperties(isObject(component) ? Object.create(component) : component, {
  4319. mount(element, state, parentScope) {
  4320. if (state === void 0) {
  4321. state = {};
  4322. }
  4323. this[PARENT_KEY_SYMBOL] = parentScope;
  4324. this[ATTRIBUTES_KEY_SYMBOL] = createAttributeBindings(element, attributes).mount(parentScope);
  4325. defineProperty(this, PROPS_KEY, Object.freeze(Object.assign({}, evaluateInitialProps(element, props), evaluateAttributeExpressions(this[ATTRIBUTES_KEY_SYMBOL].expressions))));
  4326. this[STATE_KEY] = computeState(this[STATE_KEY], state);
  4327. this[TEMPLATE_KEY_SYMBOL] = this.template.createDOM(element).clone(); // link this object to the DOM node
  4328. bindDOMNodeToComponentObject(element, this); // add eventually the 'is' attribute
  4329. component.name && addCssHook(element, component.name); // define the root element
  4330. defineProperty(this, ROOT_KEY, element); // define the slots array
  4331. defineProperty(this, SLOTS_KEY, slots); // before mount lifecycle event
  4332. this[ON_BEFORE_MOUNT_KEY](this[PROPS_KEY], this[STATE_KEY]); // mount the template
  4333. this[TEMPLATE_KEY_SYMBOL].mount(element, this, parentScope);
  4334. this[ON_MOUNTED_KEY](this[PROPS_KEY], this[STATE_KEY]);
  4335. return this;
  4336. },
  4337. update(state, parentScope) {
  4338. if (state === void 0) {
  4339. state = {};
  4340. }
  4341. if (parentScope) {
  4342. this[PARENT_KEY_SYMBOL] = parentScope;
  4343. this[ATTRIBUTES_KEY_SYMBOL].update(parentScope);
  4344. }
  4345. const newProps = evaluateAttributeExpressions(this[ATTRIBUTES_KEY_SYMBOL].expressions);
  4346. if (this[SHOULD_UPDATE_KEY](newProps, this[PROPS_KEY]) === false) return;
  4347. defineProperty(this, PROPS_KEY, Object.freeze(Object.assign({}, this[PROPS_KEY], newProps)));
  4348. this[STATE_KEY] = computeState(this[STATE_KEY], state);
  4349. this[ON_BEFORE_UPDATE_KEY](this[PROPS_KEY], this[STATE_KEY]); // avoiding recursive updates
  4350. // see also https://github.com/riot/riot/issues/2895
  4351. if (!this[IS_COMPONENT_UPDATING]) {
  4352. this[IS_COMPONENT_UPDATING] = true;
  4353. this[TEMPLATE_KEY_SYMBOL].update(this, this[PARENT_KEY_SYMBOL]);
  4354. }
  4355. this[ON_UPDATED_KEY](this[PROPS_KEY], this[STATE_KEY]);
  4356. this[IS_COMPONENT_UPDATING] = false;
  4357. return this;
  4358. },
  4359. unmount(preserveRoot) {
  4360. this[ON_BEFORE_UNMOUNT_KEY](this[PROPS_KEY], this[STATE_KEY]);
  4361. this[ATTRIBUTES_KEY_SYMBOL].unmount(); // if the preserveRoot is null the template html will be left untouched
  4362. // in that case the DOM cleanup will happen differently from a parent node
  4363. this[TEMPLATE_KEY_SYMBOL].unmount(this, this[PARENT_KEY_SYMBOL], preserveRoot === null ? null : !preserveRoot);
  4364. this[ON_UNMOUNTED_KEY](this[PROPS_KEY], this[STATE_KEY]);
  4365. return this;
  4366. }
  4367. })), Object.keys(component).filter(prop => isFunction(component[prop])));
  4368. }
  4369. /**
  4370. * Component initialization function starting from a DOM node
  4371. * @param {HTMLElement} element - element to upgrade
  4372. * @param {Object} initialProps - initial component properties
  4373. * @param {string} componentName - component id
  4374. * @returns {Object} a new component instance bound to a DOM node
  4375. */
  4376. function mountComponent(element, initialProps, componentName) {
  4377. const name = componentName || getName(element);
  4378. if (!COMPONENTS_IMPLEMENTATION_MAP$1.has(name)) panic(`The component named "${name}" was never registered`);
  4379. const component = COMPONENTS_IMPLEMENTATION_MAP$1.get(name)({
  4380. props: initialProps
  4381. });
  4382. return component.mount(element);
  4383. }
  4384. /**
  4385. * Similar to compose but performs from left-to-right function composition.<br/>
  4386. * {@link https://30secondsofcode.org/function#composeright see also}
  4387. * @param {...[function]} fns) - list of unary function
  4388. * @returns {*} result of the computation
  4389. */
  4390. /**
  4391. * Performs right-to-left function composition.<br/>
  4392. * Use Array.prototype.reduce() to perform right-to-left function composition.<br/>
  4393. * The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.<br/>
  4394. * {@link https://30secondsofcode.org/function#compose original source code}
  4395. * @param {...[function]} fns) - list of unary function
  4396. * @returns {*} result of the computation
  4397. */
  4398. function compose() {
  4399. for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  4400. fns[_key2] = arguments[_key2];
  4401. }
  4402. return fns.reduce((f, g) => function () {
  4403. return f(g(...arguments));
  4404. });
  4405. }
  4406. const {
  4407. DOM_COMPONENT_INSTANCE_PROPERTY,
  4408. COMPONENTS_IMPLEMENTATION_MAP,
  4409. PLUGINS_SET
  4410. } = globals;
  4411. /**
  4412. * Riot public api
  4413. */
  4414. /**
  4415. * Register a custom tag by name
  4416. * @param {string} name - component name
  4417. * @param {Object} implementation - tag implementation
  4418. * @returns {Map} map containing all the components implementations
  4419. */
  4420. function register(name, _ref) {
  4421. let {
  4422. css,
  4423. template,
  4424. exports
  4425. } = _ref;
  4426. if (COMPONENTS_IMPLEMENTATION_MAP.has(name)) panic(`The component "${name}" was already registered`);
  4427. COMPONENTS_IMPLEMENTATION_MAP.set(name, createComponent({
  4428. name,
  4429. css,
  4430. template,
  4431. exports
  4432. }));
  4433. return COMPONENTS_IMPLEMENTATION_MAP;
  4434. }
  4435. /**
  4436. * Unregister a riot web component
  4437. * @param {string} name - component name
  4438. * @returns {Map} map containing all the components implementations
  4439. */
  4440. function unregister(name) {
  4441. if (!COMPONENTS_IMPLEMENTATION_MAP.has(name)) panic(`The component "${name}" was never registered`);
  4442. COMPONENTS_IMPLEMENTATION_MAP.delete(name);
  4443. cssManager.remove(name);
  4444. return COMPONENTS_IMPLEMENTATION_MAP;
  4445. }
  4446. /**
  4447. * Mounting function that will work only for the components that were globally registered
  4448. * @param {string|HTMLElement} selector - query for the selection or a DOM element
  4449. * @param {Object} initialProps - the initial component properties
  4450. * @param {string} name - optional component name
  4451. * @returns {Array} list of riot components
  4452. */
  4453. function mount(selector, initialProps, name) {
  4454. return $(selector).map(element => mountComponent(element, initialProps, name));
  4455. }
  4456. /**
  4457. * Sweet unmounting helper function for the DOM node mounted manually by the user
  4458. * @param {string|HTMLElement} selector - query for the selection or a DOM element
  4459. * @param {boolean|null} keepRootElement - if true keep the root element
  4460. * @returns {Array} list of nodes unmounted
  4461. */
  4462. function unmount(selector, keepRootElement) {
  4463. return $(selector).map(element => {
  4464. if (element[DOM_COMPONENT_INSTANCE_PROPERTY]) {
  4465. element[DOM_COMPONENT_INSTANCE_PROPERTY].unmount(keepRootElement);
  4466. }
  4467. return element;
  4468. });
  4469. }
  4470. /**
  4471. * Define a riot plugin
  4472. * @param {Function} plugin - function that will receive all the components created
  4473. * @returns {Set} the set containing all the plugins installed
  4474. */
  4475. function install(plugin) {
  4476. if (!isFunction(plugin)) panic('Plugins must be of type function');
  4477. if (PLUGINS_SET.has(plugin)) panic('This plugin was already installed');
  4478. PLUGINS_SET.add(plugin);
  4479. return PLUGINS_SET;
  4480. }
  4481. /**
  4482. * Uninstall a riot plugin
  4483. * @param {Function} plugin - plugin previously installed
  4484. * @returns {Set} the set containing all the plugins installed
  4485. */
  4486. function uninstall(plugin) {
  4487. if (!PLUGINS_SET.has(plugin)) panic('This plugin was never installed');
  4488. PLUGINS_SET.delete(plugin);
  4489. return PLUGINS_SET;
  4490. }
  4491. /**
  4492. * Helper method to create component without relying on the registered ones
  4493. * @param {Object} implementation - component implementation
  4494. * @returns {Function} function that will allow you to mount a riot component on a DOM node
  4495. */
  4496. function component(implementation) {
  4497. return function (el, props, _temp) {
  4498. let {
  4499. slots,
  4500. attributes,
  4501. parentScope
  4502. } = _temp === void 0 ? {} : _temp;
  4503. return compose(c => c.mount(el, parentScope), c => c({
  4504. props,
  4505. slots,
  4506. attributes
  4507. }), createComponent)(implementation);
  4508. };
  4509. }
  4510. /**
  4511. * Lift a riot component Interface into a pure riot object
  4512. * @param {Function} func - RiotPureComponent factory function
  4513. * @returns {Function} the lifted original function received as argument
  4514. */
  4515. function pure(func) {
  4516. if (!isFunction(func)) panic('riot.pure accepts only arguments of type "function"');
  4517. func[IS_PURE_SYMBOL] = true;
  4518. return func;
  4519. }
  4520. /**
  4521. * no-op function needed to add the proper types to your component via typescript
  4522. * @param {Function|Object} component - component default export
  4523. * @returns {Function|Object} returns exactly what it has received
  4524. */
  4525. const withTypes = component => component;
  4526. /** @type {string} current riot version */
  4527. const version = 'v6.0.1'; // expose some internal stuff that might be used from external tools
  4528. const __ = {
  4529. cssManager,
  4530. DOMBindings,
  4531. createComponent,
  4532. defineComponent,
  4533. globals
  4534. };
  4535. /***/ }),
  4536. /***/ "./node_modules/validate.js/validate.js":
  4537. /*!**********************************************!*\
  4538. !*** ./node_modules/validate.js/validate.js ***!
  4539. \**********************************************/
  4540. /***/ (function(module, exports, __webpack_require__) {
  4541. /* module decorator */ module = __webpack_require__.nmd(module);
  4542. /*!
  4543. * validate.js 0.13.1
  4544. *
  4545. * (c) 2013-2019 Nicklas Ansman, 2013 Wrapp
  4546. * Validate.js may be freely distributed under the MIT license.
  4547. * For all details and documentation:
  4548. * http://validatejs.org/
  4549. */
  4550. (function(exports, module, define) {
  4551. "use strict";
  4552. // The main function that calls the validators specified by the constraints.
  4553. // The options are the following:
  4554. // - format (string) - An option that controls how the returned value is formatted
  4555. // * flat - Returns a flat array of just the error messages
  4556. // * grouped - Returns the messages grouped by attribute (default)
  4557. // * detailed - Returns an array of the raw validation data
  4558. // - fullMessages (boolean) - If `true` (default) the attribute name is prepended to the error.
  4559. //
  4560. // Please note that the options are also passed to each validator.
  4561. var validate = function(attributes, constraints, options) {
  4562. options = v.extend({}, v.options, options);
  4563. var results = v.runValidations(attributes, constraints, options)
  4564. , attr
  4565. , validator;
  4566. if (results.some(function(r) { return v.isPromise(r.error); })) {
  4567. throw new Error("Use validate.async if you want support for promises");
  4568. }
  4569. return validate.processValidationResults(results, options);
  4570. };
  4571. var v = validate;
  4572. // Copies over attributes from one or more sources to a single destination.
  4573. // Very much similar to underscore's extend.
  4574. // The first argument is the target object and the remaining arguments will be
  4575. // used as sources.
  4576. v.extend = function(obj) {
  4577. [].slice.call(arguments, 1).forEach(function(source) {
  4578. for (var attr in source) {
  4579. obj[attr] = source[attr];
  4580. }
  4581. });
  4582. return obj;
  4583. };
  4584. v.extend(validate, {
  4585. // This is the version of the library as a semver.
  4586. // The toString function will allow it to be coerced into a string
  4587. version: {
  4588. major: 0,
  4589. minor: 13,
  4590. patch: 1,
  4591. metadata: null,
  4592. toString: function() {
  4593. var version = v.format("%{major}.%{minor}.%{patch}", v.version);
  4594. if (!v.isEmpty(v.version.metadata)) {
  4595. version += "+" + v.version.metadata;
  4596. }
  4597. return version;
  4598. }
  4599. },
  4600. // Below is the dependencies that are used in validate.js
  4601. // The constructor of the Promise implementation.
  4602. // If you are using Q.js, RSVP or any other A+ compatible implementation
  4603. // override this attribute to be the constructor of that promise.
  4604. // Since jQuery promises aren't A+ compatible they won't work.
  4605. Promise: typeof Promise !== "undefined" ? Promise : /* istanbul ignore next */ null,
  4606. EMPTY_STRING_REGEXP: /^\s*$/,
  4607. // Runs the validators specified by the constraints object.
  4608. // Will return an array of the format:
  4609. // [{attribute: "<attribute name>", error: "<validation result>"}, ...]
  4610. runValidations: function(attributes, constraints, options) {
  4611. var results = []
  4612. , attr
  4613. , validatorName
  4614. , value
  4615. , validators
  4616. , validator
  4617. , validatorOptions
  4618. , error;
  4619. if (v.isDomElement(attributes) || v.isJqueryElement(attributes)) {
  4620. attributes = v.collectFormValues(attributes);
  4621. }
  4622. // Loops through each constraints, finds the correct validator and run it.
  4623. for (attr in constraints) {
  4624. value = v.getDeepObjectValue(attributes, attr);
  4625. // This allows the constraints for an attribute to be a function.
  4626. // The function will be called with the value, attribute name, the complete dict of
  4627. // attributes as well as the options and constraints passed in.
  4628. // This is useful when you want to have different
  4629. // validations depending on the attribute value.
  4630. validators = v.result(constraints[attr], value, attributes, attr, options, constraints);
  4631. for (validatorName in validators) {
  4632. validator = v.validators[validatorName];
  4633. if (!validator) {
  4634. error = v.format("Unknown validator %{name}", {name: validatorName});
  4635. throw new Error(error);
  4636. }
  4637. validatorOptions = validators[validatorName];
  4638. // This allows the options to be a function. The function will be
  4639. // called with the value, attribute name, the complete dict of
  4640. // attributes as well as the options and constraints passed in.
  4641. // This is useful when you want to have different
  4642. // validations depending on the attribute value.
  4643. validatorOptions = v.result(validatorOptions, value, attributes, attr, options, constraints);
  4644. if (!validatorOptions) {
  4645. continue;
  4646. }
  4647. results.push({
  4648. attribute: attr,
  4649. value: value,
  4650. validator: validatorName,
  4651. globalOptions: options,
  4652. attributes: attributes,
  4653. options: validatorOptions,
  4654. error: validator.call(validator,
  4655. value,
  4656. validatorOptions,
  4657. attr,
  4658. attributes,
  4659. options)
  4660. });
  4661. }
  4662. }
  4663. return results;
  4664. },
  4665. // Takes the output from runValidations and converts it to the correct
  4666. // output format.
  4667. processValidationResults: function(errors, options) {
  4668. errors = v.pruneEmptyErrors(errors, options);
  4669. errors = v.expandMultipleErrors(errors, options);
  4670. errors = v.convertErrorMessages(errors, options);
  4671. var format = options.format || "grouped";
  4672. if (typeof v.formatters[format] === 'function') {
  4673. errors = v.formatters[format](errors);
  4674. } else {
  4675. throw new Error(v.format("Unknown format %{format}", options));
  4676. }
  4677. return v.isEmpty(errors) ? undefined : errors;
  4678. },
  4679. // Runs the validations with support for promises.
  4680. // This function will return a promise that is settled when all the
  4681. // validation promises have been completed.
  4682. // It can be called even if no validations returned a promise.
  4683. async: function(attributes, constraints, options) {
  4684. options = v.extend({}, v.async.options, options);
  4685. var WrapErrors = options.wrapErrors || function(errors) {
  4686. return errors;
  4687. };
  4688. // Removes unknown attributes
  4689. if (options.cleanAttributes !== false) {
  4690. attributes = v.cleanAttributes(attributes, constraints);
  4691. }
  4692. var results = v.runValidations(attributes, constraints, options);
  4693. return new v.Promise(function(resolve, reject) {
  4694. v.waitForResults(results).then(function() {
  4695. var errors = v.processValidationResults(results, options);
  4696. if (errors) {
  4697. reject(new WrapErrors(errors, options, attributes, constraints));
  4698. } else {
  4699. resolve(attributes);
  4700. }
  4701. }, function(err) {
  4702. reject(err);
  4703. });
  4704. });
  4705. },
  4706. single: function(value, constraints, options) {
  4707. options = v.extend({}, v.single.options, options, {
  4708. format: "flat",
  4709. fullMessages: false
  4710. });
  4711. return v({single: value}, {single: constraints}, options);
  4712. },
  4713. // Returns a promise that is resolved when all promises in the results array
  4714. // are settled. The promise returned from this function is always resolved,
  4715. // never rejected.
  4716. // This function modifies the input argument, it replaces the promises
  4717. // with the value returned from the promise.
  4718. waitForResults: function(results) {
  4719. // Create a sequence of all the results starting with a resolved promise.
  4720. return results.reduce(function(memo, result) {
  4721. // If this result isn't a promise skip it in the sequence.
  4722. if (!v.isPromise(result.error)) {
  4723. return memo;
  4724. }
  4725. return memo.then(function() {
  4726. return result.error.then(function(error) {
  4727. result.error = error || null;
  4728. });
  4729. });
  4730. }, new v.Promise(function(r) { r(); })); // A resolved promise
  4731. },
  4732. // If the given argument is a call: function the and: function return the value
  4733. // otherwise just return the value. Additional arguments will be passed as
  4734. // arguments to the function.
  4735. // Example:
  4736. // ```
  4737. // result('foo') // 'foo'
  4738. // result(Math.max, 1, 2) // 2
  4739. // ```
  4740. result: function(value) {
  4741. var args = [].slice.call(arguments, 1);
  4742. if (typeof value === 'function') {
  4743. value = value.apply(null, args);
  4744. }
  4745. return value;
  4746. },
  4747. // Checks if the value is a number. This function does not consider NaN a
  4748. // number like many other `isNumber` functions do.
  4749. isNumber: function(value) {
  4750. return typeof value === 'number' && !isNaN(value);
  4751. },
  4752. // Returns false if the object is not a function
  4753. isFunction: function(value) {
  4754. return typeof value === 'function';
  4755. },
  4756. // A simple check to verify that the value is an integer. Uses `isNumber`
  4757. // and a simple modulo check.
  4758. isInteger: function(value) {
  4759. return v.isNumber(value) && value % 1 === 0;
  4760. },
  4761. // Checks if the value is a boolean
  4762. isBoolean: function(value) {
  4763. return typeof value === 'boolean';
  4764. },
  4765. // Uses the `Object` function to check if the given argument is an object.
  4766. isObject: function(obj) {
  4767. return obj === Object(obj);
  4768. },
  4769. // Simply checks if the object is an instance of a date
  4770. isDate: function(obj) {
  4771. return obj instanceof Date;
  4772. },
  4773. // Returns false if the object is `null` of `undefined`
  4774. isDefined: function(obj) {
  4775. return obj !== null && obj !== undefined;
  4776. },
  4777. // Checks if the given argument is a promise. Anything with a `then`
  4778. // function is considered a promise.
  4779. isPromise: function(p) {
  4780. return !!p && v.isFunction(p.then);
  4781. },
  4782. isJqueryElement: function(o) {
  4783. return o && v.isString(o.jquery);
  4784. },
  4785. isDomElement: function(o) {
  4786. if (!o) {
  4787. return false;
  4788. }
  4789. if (!o.querySelectorAll || !o.querySelector) {
  4790. return false;
  4791. }
  4792. if (v.isObject(document) && o === document) {
  4793. return true;
  4794. }
  4795. // http://stackoverflow.com/a/384380/699304
  4796. /* istanbul ignore else */
  4797. if (typeof HTMLElement === "object") {
  4798. return o instanceof HTMLElement;
  4799. } else {
  4800. return o &&
  4801. typeof o === "object" &&
  4802. o !== null &&
  4803. o.nodeType === 1 &&
  4804. typeof o.nodeName === "string";
  4805. }
  4806. },
  4807. isEmpty: function(value) {
  4808. var attr;
  4809. // Null and undefined are empty
  4810. if (!v.isDefined(value)) {
  4811. return true;
  4812. }
  4813. // functions are non empty
  4814. if (v.isFunction(value)) {
  4815. return false;
  4816. }
  4817. // Whitespace only strings are empty
  4818. if (v.isString(value)) {
  4819. return v.EMPTY_STRING_REGEXP.test(value);
  4820. }
  4821. // For arrays we use the length property
  4822. if (v.isArray(value)) {
  4823. return value.length === 0;
  4824. }
  4825. // Dates have no attributes but aren't empty
  4826. if (v.isDate(value)) {
  4827. return false;
  4828. }
  4829. // If we find at least one property we consider it non empty
  4830. if (v.isObject(value)) {
  4831. for (attr in value) {
  4832. return false;
  4833. }
  4834. return true;
  4835. }
  4836. return false;
  4837. },
  4838. // Formats the specified strings with the given values like so:
  4839. // ```
  4840. // format("Foo: %{foo}", {foo: "bar"}) // "Foo bar"
  4841. // ```
  4842. // If you want to write %{...} without having it replaced simply
  4843. // prefix it with % like this `Foo: %%{foo}` and it will be returned
  4844. // as `"Foo: %{foo}"`
  4845. format: v.extend(function(str, vals) {
  4846. if (!v.isString(str)) {
  4847. return str;
  4848. }
  4849. return str.replace(v.format.FORMAT_REGEXP, function(m0, m1, m2) {
  4850. if (m1 === '%') {
  4851. return "%{" + m2 + "}";
  4852. } else {
  4853. return String(vals[m2]);
  4854. }
  4855. });
  4856. }, {
  4857. // Finds %{key} style patterns in the given string
  4858. FORMAT_REGEXP: /(%?)%\{([^\}]+)\}/g
  4859. }),
  4860. // "Prettifies" the given string.
  4861. // Prettifying means replacing [.\_-] with spaces as well as splitting
  4862. // camel case words.
  4863. prettify: function(str) {
  4864. if (v.isNumber(str)) {
  4865. // If there are more than 2 decimals round it to two
  4866. if ((str * 100) % 1 === 0) {
  4867. return "" + str;
  4868. } else {
  4869. return parseFloat(Math.round(str * 100) / 100).toFixed(2);
  4870. }
  4871. }
  4872. if (v.isArray(str)) {
  4873. return str.map(function(s) { return v.prettify(s); }).join(", ");
  4874. }
  4875. if (v.isObject(str)) {
  4876. if (!v.isDefined(str.toString)) {
  4877. return JSON.stringify(str);
  4878. }
  4879. return str.toString();
  4880. }
  4881. // Ensure the string is actually a string
  4882. str = "" + str;
  4883. return str
  4884. // Splits keys separated by periods
  4885. .replace(/([^\s])\.([^\s])/g, '$1 $2')
  4886. // Removes backslashes
  4887. .replace(/\\+/g, '')
  4888. // Replaces - and - with space
  4889. .replace(/[_-]/g, ' ')
  4890. // Splits camel cased words
  4891. .replace(/([a-z])([A-Z])/g, function(m0, m1, m2) {
  4892. return "" + m1 + " " + m2.toLowerCase();
  4893. })
  4894. .toLowerCase();
  4895. },
  4896. stringifyValue: function(value, options) {
  4897. var prettify = options && options.prettify || v.prettify;
  4898. return prettify(value);
  4899. },
  4900. isString: function(value) {
  4901. return typeof value === 'string';
  4902. },
  4903. isArray: function(value) {
  4904. return {}.toString.call(value) === '[object Array]';
  4905. },
  4906. // Checks if the object is a hash, which is equivalent to an object that
  4907. // is neither an array nor a function.
  4908. isHash: function(value) {
  4909. return v.isObject(value) && !v.isArray(value) && !v.isFunction(value);
  4910. },
  4911. contains: function(obj, value) {
  4912. if (!v.isDefined(obj)) {
  4913. return false;
  4914. }
  4915. if (v.isArray(obj)) {
  4916. return obj.indexOf(value) !== -1;
  4917. }
  4918. return value in obj;
  4919. },
  4920. unique: function(array) {
  4921. if (!v.isArray(array)) {
  4922. return array;
  4923. }
  4924. return array.filter(function(el, index, array) {
  4925. return array.indexOf(el) == index;
  4926. });
  4927. },
  4928. forEachKeyInKeypath: function(object, keypath, callback) {
  4929. if (!v.isString(keypath)) {
  4930. return undefined;
  4931. }
  4932. var key = ""
  4933. , i
  4934. , escape = false;
  4935. for (i = 0; i < keypath.length; ++i) {
  4936. switch (keypath[i]) {
  4937. case '.':
  4938. if (escape) {
  4939. escape = false;
  4940. key += '.';
  4941. } else {
  4942. object = callback(object, key, false);
  4943. key = "";
  4944. }
  4945. break;
  4946. case '\\':
  4947. if (escape) {
  4948. escape = false;
  4949. key += '\\';
  4950. } else {
  4951. escape = true;
  4952. }
  4953. break;
  4954. default:
  4955. escape = false;
  4956. key += keypath[i];
  4957. break;
  4958. }
  4959. }
  4960. return callback(object, key, true);
  4961. },
  4962. getDeepObjectValue: function(obj, keypath) {
  4963. if (!v.isObject(obj)) {
  4964. return undefined;
  4965. }
  4966. return v.forEachKeyInKeypath(obj, keypath, function(obj, key) {
  4967. if (v.isObject(obj)) {
  4968. return obj[key];
  4969. }
  4970. });
  4971. },
  4972. // This returns an object with all the values of the form.
  4973. // It uses the input name as key and the value as value
  4974. // So for example this:
  4975. // <input type="text" name="email" value="foo@bar.com" />
  4976. // would return:
  4977. // {email: "foo@bar.com"}
  4978. collectFormValues: function(form, options) {
  4979. var values = {}
  4980. , i
  4981. , j
  4982. , input
  4983. , inputs
  4984. , option
  4985. , value;
  4986. if (v.isJqueryElement(form)) {
  4987. form = form[0];
  4988. }
  4989. if (!form) {
  4990. return values;
  4991. }
  4992. options = options || {};
  4993. inputs = form.querySelectorAll("input[name], textarea[name]");
  4994. for (i = 0; i < inputs.length; ++i) {
  4995. input = inputs.item(i);
  4996. if (v.isDefined(input.getAttribute("data-ignored"))) {
  4997. continue;
  4998. }
  4999. var name = input.name.replace(/\./g, "\\\\.");
  5000. value = v.sanitizeFormValue(input.value, options);
  5001. if (input.type === "number") {
  5002. value = value ? +value : null;
  5003. } else if (input.type === "checkbox") {
  5004. if (input.attributes.value) {
  5005. if (!input.checked) {
  5006. value = values[name] || null;
  5007. }
  5008. } else {
  5009. value = input.checked;
  5010. }
  5011. } else if (input.type === "radio") {
  5012. if (!input.checked) {
  5013. value = values[name] || null;
  5014. }
  5015. }
  5016. values[name] = value;
  5017. }
  5018. inputs = form.querySelectorAll("select[name]");
  5019. for (i = 0; i < inputs.length; ++i) {
  5020. input = inputs.item(i);
  5021. if (v.isDefined(input.getAttribute("data-ignored"))) {
  5022. continue;
  5023. }
  5024. if (input.multiple) {
  5025. value = [];
  5026. for (j in input.options) {
  5027. option = input.options[j];
  5028. if (option && option.selected) {
  5029. value.push(v.sanitizeFormValue(option.value, options));
  5030. }
  5031. }
  5032. } else {
  5033. var _val = typeof input.options[input.selectedIndex] !== 'undefined' ? input.options[input.selectedIndex].value : /* istanbul ignore next */ '';
  5034. value = v.sanitizeFormValue(_val, options);
  5035. }
  5036. values[input.name] = value;
  5037. }
  5038. return values;
  5039. },
  5040. sanitizeFormValue: function(value, options) {
  5041. if (options.trim && v.isString(value)) {
  5042. value = value.trim();
  5043. }
  5044. if (options.nullify !== false && value === "") {
  5045. return null;
  5046. }
  5047. return value;
  5048. },
  5049. capitalize: function(str) {
  5050. if (!v.isString(str)) {
  5051. return str;
  5052. }
  5053. return str[0].toUpperCase() + str.slice(1);
  5054. },
  5055. // Remove all errors who's error attribute is empty (null or undefined)
  5056. pruneEmptyErrors: function(errors) {
  5057. return errors.filter(function(error) {
  5058. return !v.isEmpty(error.error);
  5059. });
  5060. },
  5061. // In
  5062. // [{error: ["err1", "err2"], ...}]
  5063. // Out
  5064. // [{error: "err1", ...}, {error: "err2", ...}]
  5065. //
  5066. // All attributes in an error with multiple messages are duplicated
  5067. // when expanding the errors.
  5068. expandMultipleErrors: function(errors) {
  5069. var ret = [];
  5070. errors.forEach(function(error) {
  5071. // Removes errors without a message
  5072. if (v.isArray(error.error)) {
  5073. error.error.forEach(function(msg) {
  5074. ret.push(v.extend({}, error, {error: msg}));
  5075. });
  5076. } else {
  5077. ret.push(error);
  5078. }
  5079. });
  5080. return ret;
  5081. },
  5082. // Converts the error mesages by prepending the attribute name unless the
  5083. // message is prefixed by ^
  5084. convertErrorMessages: function(errors, options) {
  5085. options = options || {};
  5086. var ret = []
  5087. , prettify = options.prettify || v.prettify;
  5088. errors.forEach(function(errorInfo) {
  5089. var error = v.result(errorInfo.error,
  5090. errorInfo.value,
  5091. errorInfo.attribute,
  5092. errorInfo.options,
  5093. errorInfo.attributes,
  5094. errorInfo.globalOptions);
  5095. if (!v.isString(error)) {
  5096. ret.push(errorInfo);
  5097. return;
  5098. }
  5099. if (error[0] === '^') {
  5100. error = error.slice(1);
  5101. } else if (options.fullMessages !== false) {
  5102. error = v.capitalize(prettify(errorInfo.attribute)) + " " + error;
  5103. }
  5104. error = error.replace(/\\\^/g, "^");
  5105. error = v.format(error, {
  5106. value: v.stringifyValue(errorInfo.value, options)
  5107. });
  5108. ret.push(v.extend({}, errorInfo, {error: error}));
  5109. });
  5110. return ret;
  5111. },
  5112. // In:
  5113. // [{attribute: "<attributeName>", ...}]
  5114. // Out:
  5115. // {"<attributeName>": [{attribute: "<attributeName>", ...}]}
  5116. groupErrorsByAttribute: function(errors) {
  5117. var ret = {};
  5118. errors.forEach(function(error) {
  5119. var list = ret[error.attribute];
  5120. if (list) {
  5121. list.push(error);
  5122. } else {
  5123. ret[error.attribute] = [error];
  5124. }
  5125. });
  5126. return ret;
  5127. },
  5128. // In:
  5129. // [{error: "<message 1>", ...}, {error: "<message 2>", ...}]
  5130. // Out:
  5131. // ["<message 1>", "<message 2>"]
  5132. flattenErrorsToArray: function(errors) {
  5133. return errors
  5134. .map(function(error) { return error.error; })
  5135. .filter(function(value, index, self) {
  5136. return self.indexOf(value) === index;
  5137. });
  5138. },
  5139. cleanAttributes: function(attributes, whitelist) {
  5140. function whitelistCreator(obj, key, last) {
  5141. if (v.isObject(obj[key])) {
  5142. return obj[key];
  5143. }
  5144. return (obj[key] = last ? true : {});
  5145. }
  5146. function buildObjectWhitelist(whitelist) {
  5147. var ow = {}
  5148. , lastObject
  5149. , attr;
  5150. for (attr in whitelist) {
  5151. if (!whitelist[attr]) {
  5152. continue;
  5153. }
  5154. v.forEachKeyInKeypath(ow, attr, whitelistCreator);
  5155. }
  5156. return ow;
  5157. }
  5158. function cleanRecursive(attributes, whitelist) {
  5159. if (!v.isObject(attributes)) {
  5160. return attributes;
  5161. }
  5162. var ret = v.extend({}, attributes)
  5163. , w
  5164. , attribute;
  5165. for (attribute in attributes) {
  5166. w = whitelist[attribute];
  5167. if (v.isObject(w)) {
  5168. ret[attribute] = cleanRecursive(ret[attribute], w);
  5169. } else if (!w) {
  5170. delete ret[attribute];
  5171. }
  5172. }
  5173. return ret;
  5174. }
  5175. if (!v.isObject(whitelist) || !v.isObject(attributes)) {
  5176. return {};
  5177. }
  5178. whitelist = buildObjectWhitelist(whitelist);
  5179. return cleanRecursive(attributes, whitelist);
  5180. },
  5181. exposeModule: function(validate, root, exports, module, define) {
  5182. if (exports) {
  5183. if (module && module.exports) {
  5184. exports = module.exports = validate;
  5185. }
  5186. exports.validate = validate;
  5187. } else {
  5188. root.validate = validate;
  5189. if (validate.isFunction(define) && define.amd) {
  5190. define([], function () { return validate; });
  5191. }
  5192. }
  5193. },
  5194. warn: function(msg) {
  5195. if (typeof console !== "undefined" && console.warn) {
  5196. console.warn("[validate.js] " + msg);
  5197. }
  5198. },
  5199. error: function(msg) {
  5200. if (typeof console !== "undefined" && console.error) {
  5201. console.error("[validate.js] " + msg);
  5202. }
  5203. }
  5204. });
  5205. validate.validators = {
  5206. // Presence validates that the value isn't empty
  5207. presence: function(value, options) {
  5208. options = v.extend({}, this.options, options);
  5209. if (options.allowEmpty !== false ? !v.isDefined(value) : v.isEmpty(value)) {
  5210. return options.message || this.message || "can't be blank";
  5211. }
  5212. },
  5213. length: function(value, options, attribute) {
  5214. // Empty values are allowed
  5215. if (!v.isDefined(value)) {
  5216. return;
  5217. }
  5218. options = v.extend({}, this.options, options);
  5219. var is = options.is
  5220. , maximum = options.maximum
  5221. , minimum = options.minimum
  5222. , tokenizer = options.tokenizer || function(val) { return val; }
  5223. , err
  5224. , errors = [];
  5225. value = tokenizer(value);
  5226. var length = value.length;
  5227. if(!v.isNumber(length)) {
  5228. return options.message || this.notValid || "has an incorrect length";
  5229. }
  5230. // Is checks
  5231. if (v.isNumber(is) && length !== is) {
  5232. err = options.wrongLength ||
  5233. this.wrongLength ||
  5234. "is the wrong length (should be %{count} characters)";
  5235. errors.push(v.format(err, {count: is}));
  5236. }
  5237. if (v.isNumber(minimum) && length < minimum) {
  5238. err = options.tooShort ||
  5239. this.tooShort ||
  5240. "is too short (minimum is %{count} characters)";
  5241. errors.push(v.format(err, {count: minimum}));
  5242. }
  5243. if (v.isNumber(maximum) && length > maximum) {
  5244. err = options.tooLong ||
  5245. this.tooLong ||
  5246. "is too long (maximum is %{count} characters)";
  5247. errors.push(v.format(err, {count: maximum}));
  5248. }
  5249. if (errors.length > 0) {
  5250. return options.message || errors;
  5251. }
  5252. },
  5253. numericality: function(value, options, attribute, attributes, globalOptions) {
  5254. // Empty values are fine
  5255. if (!v.isDefined(value)) {
  5256. return;
  5257. }
  5258. options = v.extend({}, this.options, options);
  5259. var errors = []
  5260. , name
  5261. , count
  5262. , checks = {
  5263. greaterThan: function(v, c) { return v > c; },
  5264. greaterThanOrEqualTo: function(v, c) { return v >= c; },
  5265. equalTo: function(v, c) { return v === c; },
  5266. lessThan: function(v, c) { return v < c; },
  5267. lessThanOrEqualTo: function(v, c) { return v <= c; },
  5268. divisibleBy: function(v, c) { return v % c === 0; }
  5269. }
  5270. , prettify = options.prettify ||
  5271. (globalOptions && globalOptions.prettify) ||
  5272. v.prettify;
  5273. // Strict will check that it is a valid looking number
  5274. if (v.isString(value) && options.strict) {
  5275. var pattern = "^-?(0|[1-9]\\d*)";
  5276. if (!options.onlyInteger) {
  5277. pattern += "(\\.\\d+)?";
  5278. }
  5279. pattern += "$";
  5280. if (!(new RegExp(pattern).test(value))) {
  5281. return options.message ||
  5282. options.notValid ||
  5283. this.notValid ||
  5284. this.message ||
  5285. "must be a valid number";
  5286. }
  5287. }
  5288. // Coerce the value to a number unless we're being strict.
  5289. if (options.noStrings !== true && v.isString(value) && !v.isEmpty(value)) {
  5290. value = +value;
  5291. }
  5292. // If it's not a number we shouldn't continue since it will compare it.
  5293. if (!v.isNumber(value)) {
  5294. return options.message ||
  5295. options.notValid ||
  5296. this.notValid ||
  5297. this.message ||
  5298. "is not a number";
  5299. }
  5300. // Same logic as above, sort of. Don't bother with comparisons if this
  5301. // doesn't pass.
  5302. if (options.onlyInteger && !v.isInteger(value)) {
  5303. return options.message ||
  5304. options.notInteger ||
  5305. this.notInteger ||
  5306. this.message ||
  5307. "must be an integer";
  5308. }
  5309. for (name in checks) {
  5310. count = options[name];
  5311. if (v.isNumber(count) && !checks[name](value, count)) {
  5312. // This picks the default message if specified
  5313. // For example the greaterThan check uses the message from
  5314. // this.notGreaterThan so we capitalize the name and prepend "not"
  5315. var key = "not" + v.capitalize(name);
  5316. var msg = options[key] ||
  5317. this[key] ||
  5318. this.message ||
  5319. "must be %{type} %{count}";
  5320. errors.push(v.format(msg, {
  5321. count: count,
  5322. type: prettify(name)
  5323. }));
  5324. }
  5325. }
  5326. if (options.odd && value % 2 !== 1) {
  5327. errors.push(options.notOdd ||
  5328. this.notOdd ||
  5329. this.message ||
  5330. "must be odd");
  5331. }
  5332. if (options.even && value % 2 !== 0) {
  5333. errors.push(options.notEven ||
  5334. this.notEven ||
  5335. this.message ||
  5336. "must be even");
  5337. }
  5338. if (errors.length) {
  5339. return options.message || errors;
  5340. }
  5341. },
  5342. datetime: v.extend(function(value, options) {
  5343. if (!v.isFunction(this.parse) || !v.isFunction(this.format)) {
  5344. throw new Error("Both the parse and format functions needs to be set to use the datetime/date validator");
  5345. }
  5346. // Empty values are fine
  5347. if (!v.isDefined(value)) {
  5348. return;
  5349. }
  5350. options = v.extend({}, this.options, options);
  5351. var err
  5352. , errors = []
  5353. , earliest = options.earliest ? this.parse(options.earliest, options) : NaN
  5354. , latest = options.latest ? this.parse(options.latest, options) : NaN;
  5355. value = this.parse(value, options);
  5356. // 86400000 is the number of milliseconds in a day, this is used to remove
  5357. // the time from the date
  5358. if (isNaN(value) || options.dateOnly && value % 86400000 !== 0) {
  5359. err = options.notValid ||
  5360. options.message ||
  5361. this.notValid ||
  5362. "must be a valid date";
  5363. return v.format(err, {value: arguments[0]});
  5364. }
  5365. if (!isNaN(earliest) && value < earliest) {
  5366. err = options.tooEarly ||
  5367. options.message ||
  5368. this.tooEarly ||
  5369. "must be no earlier than %{date}";
  5370. err = v.format(err, {
  5371. value: this.format(value, options),
  5372. date: this.format(earliest, options)
  5373. });
  5374. errors.push(err);
  5375. }
  5376. if (!isNaN(latest) && value > latest) {
  5377. err = options.tooLate ||
  5378. options.message ||
  5379. this.tooLate ||
  5380. "must be no later than %{date}";
  5381. err = v.format(err, {
  5382. date: this.format(latest, options),
  5383. value: this.format(value, options)
  5384. });
  5385. errors.push(err);
  5386. }
  5387. if (errors.length) {
  5388. return v.unique(errors);
  5389. }
  5390. }, {
  5391. parse: null,
  5392. format: null
  5393. }),
  5394. date: function(value, options) {
  5395. options = v.extend({}, options, {dateOnly: true});
  5396. return v.validators.datetime.call(v.validators.datetime, value, options);
  5397. },
  5398. format: function(value, options) {
  5399. if (v.isString(options) || (options instanceof RegExp)) {
  5400. options = {pattern: options};
  5401. }
  5402. options = v.extend({}, this.options, options);
  5403. var message = options.message || this.message || "is invalid"
  5404. , pattern = options.pattern
  5405. , match;
  5406. // Empty values are allowed
  5407. if (!v.isDefined(value)) {
  5408. return;
  5409. }
  5410. if (!v.isString(value)) {
  5411. return message;
  5412. }
  5413. if (v.isString(pattern)) {
  5414. pattern = new RegExp(options.pattern, options.flags);
  5415. }
  5416. match = pattern.exec(value);
  5417. if (!match || match[0].length != value.length) {
  5418. return message;
  5419. }
  5420. },
  5421. inclusion: function(value, options) {
  5422. // Empty values are fine
  5423. if (!v.isDefined(value)) {
  5424. return;
  5425. }
  5426. if (v.isArray(options)) {
  5427. options = {within: options};
  5428. }
  5429. options = v.extend({}, this.options, options);
  5430. if (v.contains(options.within, value)) {
  5431. return;
  5432. }
  5433. var message = options.message ||
  5434. this.message ||
  5435. "^%{value} is not included in the list";
  5436. return v.format(message, {value: value});
  5437. },
  5438. exclusion: function(value, options) {
  5439. // Empty values are fine
  5440. if (!v.isDefined(value)) {
  5441. return;
  5442. }
  5443. if (v.isArray(options)) {
  5444. options = {within: options};
  5445. }
  5446. options = v.extend({}, this.options, options);
  5447. if (!v.contains(options.within, value)) {
  5448. return;
  5449. }
  5450. var message = options.message || this.message || "^%{value} is restricted";
  5451. if (v.isString(options.within[value])) {
  5452. value = options.within[value];
  5453. }
  5454. return v.format(message, {value: value});
  5455. },
  5456. email: v.extend(function(value, options) {
  5457. options = v.extend({}, this.options, options);
  5458. var message = options.message || this.message || "is not a valid email";
  5459. // Empty values are fine
  5460. if (!v.isDefined(value)) {
  5461. return;
  5462. }
  5463. if (!v.isString(value)) {
  5464. return message;
  5465. }
  5466. if (!this.PATTERN.exec(value)) {
  5467. return message;
  5468. }
  5469. }, {
  5470. 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
  5471. }),
  5472. equality: function(value, options, attribute, attributes, globalOptions) {
  5473. if (!v.isDefined(value)) {
  5474. return;
  5475. }
  5476. if (v.isString(options)) {
  5477. options = {attribute: options};
  5478. }
  5479. options = v.extend({}, this.options, options);
  5480. var message = options.message ||
  5481. this.message ||
  5482. "is not equal to %{attribute}";
  5483. if (v.isEmpty(options.attribute) || !v.isString(options.attribute)) {
  5484. throw new Error("The attribute must be a non empty string");
  5485. }
  5486. var otherValue = v.getDeepObjectValue(attributes, options.attribute)
  5487. , comparator = options.comparator || function(v1, v2) {
  5488. return v1 === v2;
  5489. }
  5490. , prettify = options.prettify ||
  5491. (globalOptions && globalOptions.prettify) ||
  5492. v.prettify;
  5493. if (!comparator(value, otherValue, options, attribute, attributes)) {
  5494. return v.format(message, {attribute: prettify(options.attribute)});
  5495. }
  5496. },
  5497. // A URL validator that is used to validate URLs with the ability to
  5498. // restrict schemes and some domains.
  5499. url: function(value, options) {
  5500. if (!v.isDefined(value)) {
  5501. return;
  5502. }
  5503. options = v.extend({}, this.options, options);
  5504. var message = options.message || this.message || "is not a valid url"
  5505. , schemes = options.schemes || this.schemes || ['http', 'https']
  5506. , allowLocal = options.allowLocal || this.allowLocal || false
  5507. , allowDataUrl = options.allowDataUrl || this.allowDataUrl || false;
  5508. if (!v.isString(value)) {
  5509. return message;
  5510. }
  5511. // https://gist.github.com/dperini/729294
  5512. var regex =
  5513. "^" +
  5514. // protocol identifier
  5515. "(?:(?:" + schemes.join("|") + ")://)" +
  5516. // user:pass authentication
  5517. "(?:\\S+(?::\\S*)?@)?" +
  5518. "(?:";
  5519. var tld = "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))";
  5520. if (allowLocal) {
  5521. tld += "?";
  5522. } else {
  5523. regex +=
  5524. // IP address exclusion
  5525. // private & local networks
  5526. "(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
  5527. "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
  5528. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})";
  5529. }
  5530. regex +=
  5531. // IP address dotted notation octets
  5532. // excludes loopback network 0.0.0.0
  5533. // excludes reserved space >= 224.0.0.0
  5534. // excludes network & broacast addresses
  5535. // (first & last IP address of each class)
  5536. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  5537. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  5538. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  5539. "|" +
  5540. // host name
  5541. "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
  5542. // domain name
  5543. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
  5544. tld +
  5545. ")" +
  5546. // port number
  5547. "(?::\\d{2,5})?" +
  5548. // resource path
  5549. "(?:[/?#]\\S*)?" +
  5550. "$";
  5551. if (allowDataUrl) {
  5552. // RFC 2397
  5553. var mediaType = "\\w+\\/[-+.\\w]+(?:;[\\w=]+)*";
  5554. var urlchar = "[A-Za-z0-9-_.!~\\*'();\\/?:@&=+$,%]*";
  5555. var dataurl = "data:(?:"+mediaType+")?(?:;base64)?,"+urlchar;
  5556. regex = "(?:"+regex+")|(?:^"+dataurl+"$)";
  5557. }
  5558. var PATTERN = new RegExp(regex, 'i');
  5559. if (!PATTERN.exec(value)) {
  5560. return message;
  5561. }
  5562. },
  5563. type: v.extend(function(value, originalOptions, attribute, attributes, globalOptions) {
  5564. if (v.isString(originalOptions)) {
  5565. originalOptions = {type: originalOptions};
  5566. }
  5567. if (!v.isDefined(value)) {
  5568. return;
  5569. }
  5570. var options = v.extend({}, this.options, originalOptions);
  5571. var type = options.type;
  5572. if (!v.isDefined(type)) {
  5573. throw new Error("No type was specified");
  5574. }
  5575. var check;
  5576. if (v.isFunction(type)) {
  5577. check = type;
  5578. } else {
  5579. check = this.types[type];
  5580. }
  5581. if (!v.isFunction(check)) {
  5582. throw new Error("validate.validators.type.types." + type + " must be a function.");
  5583. }
  5584. if (!check(value, options, attribute, attributes, globalOptions)) {
  5585. var message = originalOptions.message ||
  5586. this.messages[type] ||
  5587. this.message ||
  5588. options.message ||
  5589. (v.isFunction(type) ? "must be of the correct type" : "must be of type %{type}");
  5590. if (v.isFunction(message)) {
  5591. message = message(value, originalOptions, attribute, attributes, globalOptions);
  5592. }
  5593. return v.format(message, {attribute: v.prettify(attribute), type: type});
  5594. }
  5595. }, {
  5596. types: {
  5597. object: function(value) {
  5598. return v.isObject(value) && !v.isArray(value);
  5599. },
  5600. array: v.isArray,
  5601. integer: v.isInteger,
  5602. number: v.isNumber,
  5603. string: v.isString,
  5604. date: v.isDate,
  5605. boolean: v.isBoolean
  5606. },
  5607. messages: {}
  5608. })
  5609. };
  5610. validate.formatters = {
  5611. detailed: function(errors) {return errors;},
  5612. flat: v.flattenErrorsToArray,
  5613. grouped: function(errors) {
  5614. var attr;
  5615. errors = v.groupErrorsByAttribute(errors);
  5616. for (attr in errors) {
  5617. errors[attr] = v.flattenErrorsToArray(errors[attr]);
  5618. }
  5619. return errors;
  5620. },
  5621. constraint: function(errors) {
  5622. var attr;
  5623. errors = v.groupErrorsByAttribute(errors);
  5624. for (attr in errors) {
  5625. errors[attr] = errors[attr].map(function(result) {
  5626. return result.validator;
  5627. }).sort();
  5628. }
  5629. return errors;
  5630. }
  5631. };
  5632. validate.exposeModule(validate, this, exports, module, __webpack_require__.amdD);
  5633. }).call(this,
  5634. true ? /* istanbul ignore next */ exports : 0,
  5635. true ? /* istanbul ignore next */ module : 0,
  5636. __webpack_require__.amdD);
  5637. /***/ })
  5638. /******/ });
  5639. /************************************************************************/
  5640. /******/ // The module cache
  5641. /******/ var __webpack_module_cache__ = {};
  5642. /******/
  5643. /******/ // The require function
  5644. /******/ function __webpack_require__(moduleId) {
  5645. /******/ // Check if module is in cache
  5646. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  5647. /******/ if (cachedModule !== undefined) {
  5648. /******/ return cachedModule.exports;
  5649. /******/ }
  5650. /******/ // Create a new module (and put it into the cache)
  5651. /******/ var module = __webpack_module_cache__[moduleId] = {
  5652. /******/ id: moduleId,
  5653. /******/ loaded: false,
  5654. /******/ exports: {}
  5655. /******/ };
  5656. /******/
  5657. /******/ // Execute the module function
  5658. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  5659. /******/
  5660. /******/ // Flag the module as loaded
  5661. /******/ module.loaded = true;
  5662. /******/
  5663. /******/ // Return the exports of the module
  5664. /******/ return module.exports;
  5665. /******/ }
  5666. /******/
  5667. /************************************************************************/
  5668. /******/ /* webpack/runtime/amd define */
  5669. /******/ (() => {
  5670. /******/ __webpack_require__.amdD = function () {
  5671. /******/ throw new Error('define cannot be used indirect');
  5672. /******/ };
  5673. /******/ })();
  5674. /******/
  5675. /******/ /* webpack/runtime/compat get default export */
  5676. /******/ (() => {
  5677. /******/ // getDefaultExport function for compatibility with non-harmony modules
  5678. /******/ __webpack_require__.n = (module) => {
  5679. /******/ var getter = module && module.__esModule ?
  5680. /******/ () => (module['default']) :
  5681. /******/ () => (module);
  5682. /******/ __webpack_require__.d(getter, { a: getter });
  5683. /******/ return getter;
  5684. /******/ };
  5685. /******/ })();
  5686. /******/
  5687. /******/ /* webpack/runtime/define property getters */
  5688. /******/ (() => {
  5689. /******/ // define getter functions for harmony exports
  5690. /******/ __webpack_require__.d = (exports, definition) => {
  5691. /******/ for(var key in definition) {
  5692. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  5693. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  5694. /******/ }
  5695. /******/ }
  5696. /******/ };
  5697. /******/ })();
  5698. /******/
  5699. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  5700. /******/ (() => {
  5701. /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
  5702. /******/ })();
  5703. /******/
  5704. /******/ /* webpack/runtime/make namespace object */
  5705. /******/ (() => {
  5706. /******/ // define __esModule on exports
  5707. /******/ __webpack_require__.r = (exports) => {
  5708. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  5709. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  5710. /******/ }
  5711. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  5712. /******/ };
  5713. /******/ })();
  5714. /******/
  5715. /******/ /* webpack/runtime/node module decorator */
  5716. /******/ (() => {
  5717. /******/ __webpack_require__.nmd = (module) => {
  5718. /******/ module.paths = [];
  5719. /******/ if (!module.children) module.children = [];
  5720. /******/ return module;
  5721. /******/ };
  5722. /******/ })();
  5723. /******/
  5724. /************************************************************************/
  5725. var __webpack_exports__ = {};
  5726. // This entry need to be wrapped in an IIFE because it need to be in strict mode.
  5727. (() => {
  5728. "use strict";
  5729. /*!***************************************!*\
  5730. !*** ./resources/js/bucket-single.js ***!
  5731. \***************************************/
  5732. __webpack_require__.r(__webpack_exports__);
  5733. /* harmony import */ var riot__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! riot */ "./node_modules/riot/riot.esm.js");
  5734. /* harmony import */ var _components_note_form_riot__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components/note-form.riot */ "./resources/js/components/note-form.riot");
  5735. riot__WEBPACK_IMPORTED_MODULE_1__.register('note-form', _components_note_form_riot__WEBPACK_IMPORTED_MODULE_0__.default);
  5736. riot__WEBPACK_IMPORTED_MODULE_1__.mount('note-form');
  5737. })();
  5738. /******/ })()
  5739. ;