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.

6792 lines
200 KiB

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