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.

6772 lines
199 KiB

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