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.

9856 lines
282 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. /******/ (() => { // webpackBootstrap
  2. /******/ var __webpack_modules__ = ({
  3. /***/ "./resources/js/components/field-error.riot":
  4. /*!**************************************************!*\
  5. !*** ./resources/js/components/field-error.riot ***!
  6. \**************************************************/
  7. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  8. "use strict";
  9. __webpack_require__.r(__webpack_exports__);
  10. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  11. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  12. /* harmony export */ });
  13. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  14. 'css': null,
  15. 'exports': {
  16. state: {
  17. errors: [
  18. ],
  19. // css class for
  20. closest: '.field-group',
  21. },
  22. /**
  23. *
  24. *
  25. * @param {Object} props
  26. * @param {Object} state
  27. *
  28. */
  29. onBeforeMounted(props, state)
  30. {
  31. if (props.closest) {
  32. state.closest = props.closest
  33. }
  34. },
  35. /**
  36. *
  37. *
  38. * @param {Object} props
  39. * @param {Object} state
  40. *
  41. */
  42. onMounted(props, state)
  43. {
  44. // getting parent element for entire field
  45. const parent = this.root.closest(state.closest)
  46. // getting current element by name
  47. const element = parent.querySelector('[name="' + props.name + '"]')
  48. // getting form
  49. const form = element.closest('form')
  50. // element, form are exists and nofieldupdate is not set
  51. // each change of the element dispatch a event to form validation
  52. if (element && form && !props.nofieldupdate) {
  53. element.addEventListener('input', (event) => {
  54. this.dispatchCustomEvent(event, form, props.name)
  55. })
  56. }
  57. // add custom event to listen to form-validation
  58. this.root.addEventListener('form-validation', (event) => {
  59. this.onFormValidation(event, parent)
  60. })
  61. },
  62. /**
  63. * process form validation triggered by form
  64. *
  65. * @param {Event} event
  66. * @param {Element} parent
  67. *
  68. */
  69. onFormValidation(event, parent)
  70. {
  71. // if detail is a value, set to errors
  72. if (event.detail) {
  73. this.state.errors = event.detail
  74. parent.classList.add('field--error')
  75. parent.classList.remove('field--valid')
  76. } else {
  77. this.state.errors = []
  78. parent.classList.remove('field--error')
  79. parent.classList.add('field--valid')
  80. }
  81. this.update()
  82. },
  83. /**
  84. * create event to send to form validation
  85. *
  86. * @param {Event} event
  87. * @param {Element} form
  88. * @param {string} name
  89. *
  90. */
  91. dispatchCustomEvent(event, form, name)
  92. {
  93. const fieldUpdateEvent = new CustomEvent('field-update', {
  94. 'detail': {
  95. 'name': name,
  96. 'value': event.target.value
  97. }
  98. })
  99. form.dispatchEvent(fieldUpdateEvent)
  100. }
  101. },
  102. 'template': function(
  103. template,
  104. expressionTypes,
  105. bindingTypes,
  106. getComponent
  107. ) {
  108. return template(
  109. '<div expr3="expr3" 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': 'expr3',
  119. 'selector': '[expr3]',
  120. 'template': template(
  121. '<ul><li expr4="expr4"></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': 'expr4',
  150. 'selector': '[expr4]',
  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/modal.riot":
  169. /*!********************************************!*\
  170. !*** ./resources/js/components/modal.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 default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  179. 'css': null,
  180. 'exports': {
  181. state: {
  182. confirm: {}
  183. },
  184. onMounted() {
  185. this.root.addEventListener('open', this.__open)
  186. this.root.addEventListener('close', this.__close)
  187. },
  188. __open(event) {
  189. // adding confirm function to state
  190. this.state.confirm = event.detail.confirm
  191. this.state.body = event.detail.body
  192. this.$('.modal').classList.add('modal--open')
  193. this.update()
  194. },
  195. __close(event) {
  196. this.$('.modal').classList.remove('modal--open')
  197. this.update()
  198. },
  199. /**
  200. *
  201. * @param {[type]} event
  202. * @return {[type]}
  203. *
  204. */
  205. handleConfirm(event) {
  206. event.preventDefault()
  207. // calling confirm function
  208. this.state.confirm()
  209. this.__close()
  210. },
  211. /**
  212. *
  213. *
  214. * @param {object} event
  215. *
  216. */
  217. handleClose(event) {
  218. event.preventDefault()
  219. this.__close()
  220. }
  221. },
  222. 'template': function(
  223. template,
  224. expressionTypes,
  225. bindingTypes,
  226. getComponent
  227. ) {
  228. return template(
  229. '<div class="modal"><div class="modal__inner"><div class="modal__title center"><slot expr31="expr31" name="title"></slot></div><div expr32="expr32" class="modal__body"> </div><div class="modal__footer"><button expr33="expr33" class="button button--outline button--danger">\n Confirm\n </button><button expr34="expr34" class="button button--outline float-right">\n Reject\n </button></div></div></div>',
  230. [
  231. {
  232. 'type': bindingTypes.SLOT,
  233. 'attributes': [],
  234. 'name': 'title',
  235. 'redundantAttribute': 'expr31',
  236. 'selector': '[expr31]'
  237. },
  238. {
  239. 'redundantAttribute': 'expr32',
  240. 'selector': '[expr32]',
  241. 'expressions': [
  242. {
  243. 'type': expressionTypes.TEXT,
  244. 'childNodeIndex': 0,
  245. 'evaluate': function(
  246. _scope
  247. ) {
  248. return [
  249. _scope.state.body
  250. ].join(
  251. ''
  252. );
  253. }
  254. }
  255. ]
  256. },
  257. {
  258. 'redundantAttribute': 'expr33',
  259. 'selector': '[expr33]',
  260. 'expressions': [
  261. {
  262. 'type': expressionTypes.EVENT,
  263. 'name': 'onclick',
  264. 'evaluate': function(
  265. _scope
  266. ) {
  267. return (event) => { _scope.handleConfirm(event) };
  268. }
  269. }
  270. ]
  271. },
  272. {
  273. 'redundantAttribute': 'expr34',
  274. 'selector': '[expr34]',
  275. 'expressions': [
  276. {
  277. 'type': expressionTypes.EVENT,
  278. 'name': 'onclick',
  279. 'evaluate': function(
  280. _scope
  281. ) {
  282. return (event) => { _scope.handleClose(event) };
  283. }
  284. }
  285. ]
  286. }
  287. ]
  288. );
  289. },
  290. 'name': 'app-modal'
  291. });
  292. /***/ }),
  293. /***/ "./resources/js/components/sidebar-button.riot":
  294. /*!*****************************************************!*\
  295. !*** ./resources/js/components/sidebar-button.riot ***!
  296. \*****************************************************/
  297. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  298. "use strict";
  299. __webpack_require__.r(__webpack_exports__);
  300. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  301. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  302. /* harmony export */ });
  303. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  304. 'css': null,
  305. 'exports': {
  306. state: {
  307. element: undefined,
  308. data: false
  309. },
  310. /**
  311. *
  312. *
  313. */
  314. onBeforeMount() {
  315. if (this.root.innerHTML) {
  316. this.content = this.root.innerHTML;
  317. this.root.innerHTML = '';
  318. }
  319. if (!this.props.event) {
  320. console.error('sidebar-button: attribute for name of custom event is missing')
  321. }
  322. if (!this.props.selector) {
  323. console.error('sidebar-button: attribute for selector to send custom event is missing')
  324. }
  325. if (this.props.data) {
  326. this.state.data = this.props.data
  327. }
  328. },
  329. /**
  330. *
  331. *
  332. */
  333. onMounted() {
  334. this.state.element = document.querySelector(this.props.selector)
  335. // adding innerHtml to button
  336. if (this.content) {
  337. this.$('button').innerHTML = this.content;
  338. }
  339. },
  340. /**
  341. * create custom event with props
  342. *
  343. * @param {[type]} event
  344. * @return {[type]}
  345. */
  346. handleClick(event) {
  347. event.preventDefault()
  348. const customEvent = new CustomEvent(this.props.event, {
  349. 'detail': {
  350. 'data': this.state.data
  351. }
  352. })
  353. this.state.element.dispatchEvent(customEvent)
  354. }
  355. },
  356. 'template': function(
  357. template,
  358. expressionTypes,
  359. bindingTypes,
  360. getComponent
  361. ) {
  362. return template(
  363. '<button expr14="expr14" class="button m-bottom-0" type="button"><slot expr15="expr15"></slot></button>',
  364. [
  365. {
  366. 'redundantAttribute': 'expr14',
  367. 'selector': '[expr14]',
  368. 'expressions': [
  369. {
  370. 'type': expressionTypes.EVENT,
  371. 'name': 'onclick',
  372. 'evaluate': function(
  373. _scope
  374. ) {
  375. return (event) => { _scope.handleClick(event) };
  376. }
  377. }
  378. ]
  379. },
  380. {
  381. 'type': bindingTypes.SLOT,
  382. 'attributes': [],
  383. 'name': 'default',
  384. 'redundantAttribute': 'expr15',
  385. 'selector': '[expr15]'
  386. }
  387. ]
  388. );
  389. },
  390. 'name': 'app-sidebar-button'
  391. });
  392. /***/ }),
  393. /***/ "./resources/js/components/users.riot":
  394. /*!********************************************!*\
  395. !*** ./resources/js/components/users.riot ***!
  396. \********************************************/
  397. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  398. "use strict";
  399. __webpack_require__.r(__webpack_exports__);
  400. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  401. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  402. /* harmony export */ });
  403. /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ "./node_modules/axios/index.js");
  404. /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);
  405. /* harmony import */ var lodash_remove__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash.remove */ "./node_modules/lodash.remove/index.js");
  406. /* harmony import */ var lodash_remove__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash_remove__WEBPACK_IMPORTED_MODULE_1__);
  407. /* harmony import */ var riot__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! riot */ "./node_modules/riot/riot.esm.js");
  408. /* harmony import */ var _modal_riot__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./modal.riot */ "./resources/js/components/modal.riot");
  409. riot__WEBPACK_IMPORTED_MODULE_3__.register('app-modal', _modal_riot__WEBPACK_IMPORTED_MODULE_2__.default)
  410. riot__WEBPACK_IMPORTED_MODULE_3__.mount('app-modal')
  411. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  412. 'css': null,
  413. 'exports': {
  414. state: {
  415. users: [],
  416. maxLength: 0
  417. },
  418. onBeforeMount() {
  419. this.fetch()
  420. },
  421. /**
  422. *
  423. * @param {[type]} event
  424. * @param {[type]} user
  425. * @return {[type]}
  426. *
  427. */
  428. handleUpdate(event, user) {
  429. const customEvent = new CustomEvent('app-users-form-open', {
  430. 'detail': user
  431. })
  432. document.querySelector('app-users-form').dispatchEvent(customEvent);
  433. },
  434. handleDelete(event, user) {
  435. event.preventDefault()
  436. const customEvent = new CustomEvent('open', {
  437. 'detail': {
  438. 'confirm': () => {
  439. axios__WEBPACK_IMPORTED_MODULE_0___default().delete('/api/users/' + user._id)
  440. .then((response) => {
  441. // removing from buckets
  442. lodash_remove__WEBPACK_IMPORTED_MODULE_1___default()(this.state.users, function(u) {
  443. return u._id === user._id
  444. })
  445. this.update()
  446. })
  447. },
  448. // @TODO find a better solution to create body text
  449. 'body': 'Do you want delete ' + user.email + '?'
  450. }
  451. })
  452. this.$('#user-delete-confirm').dispatchEvent(customEvent);
  453. },
  454. /**
  455. * getting all buckets
  456. *
  457. *
  458. */
  459. fetch() {
  460. axios__WEBPACK_IMPORTED_MODULE_0___default().get('/api/users').then((response) => {
  461. this.state.users = response.data.data
  462. this.update()
  463. })
  464. }
  465. },
  466. 'template': function(
  467. template,
  468. expressionTypes,
  469. bindingTypes,
  470. getComponent
  471. ) {
  472. return template(
  473. '<div class="buckets"><table class="table"><thead><tr class="table__tr"><th class="table__th">\n Email\n </th><th class="table__th">\n Display Name\n </th><th class="table__th" colspan="2">\n Roles\n </th></tr></thead><tbody><tr expr5="expr5" class="table__tr"></tr></tbody></table><app-modal expr11="expr11" id="user-delete-confirm"></app-modal><div expr12="expr12" class="grid"></div></div>',
  474. [
  475. {
  476. 'type': bindingTypes.EACH,
  477. 'getKey': null,
  478. 'condition': null,
  479. 'template': template(
  480. '<td expr6="expr6" class="table__td"> </td><td expr7="expr7" class="table__td"> </td><td class="table__td"><div expr8="expr8"></div></td><td class="table__td right"><app-sidebar-button expr9="expr9" class="m-bottom-0 m-right-3" event="app-users-form-open" selector="app-users-form"></app-sidebar-button><button expr10="expr10" class="button button--small m-bottom-0" type="button"><svg class="icon" aria-hidden="true"><use xlink:href="/symbol-defs.svg#icon-delete"/></svg></button></td>',
  481. [
  482. {
  483. 'redundantAttribute': 'expr6',
  484. 'selector': '[expr6]',
  485. 'expressions': [
  486. {
  487. 'type': expressionTypes.TEXT,
  488. 'childNodeIndex': 0,
  489. 'evaluate': function(
  490. _scope
  491. ) {
  492. return [
  493. _scope.user.email
  494. ].join(
  495. ''
  496. );
  497. }
  498. }
  499. ]
  500. },
  501. {
  502. 'redundantAttribute': 'expr7',
  503. 'selector': '[expr7]',
  504. 'expressions': [
  505. {
  506. 'type': expressionTypes.TEXT,
  507. 'childNodeIndex': 0,
  508. 'evaluate': function(
  509. _scope
  510. ) {
  511. return [
  512. _scope.user.display_name
  513. ].join(
  514. ''
  515. );
  516. }
  517. }
  518. ]
  519. },
  520. {
  521. 'type': bindingTypes.IF,
  522. 'evaluate': function(
  523. _scope
  524. ) {
  525. return _scope.user.roles && _scope.user.roles.indexOf('admin') >= 0;
  526. },
  527. 'redundantAttribute': 'expr8',
  528. 'selector': '[expr8]',
  529. 'template': template(
  530. '\n Admin\n <svg class="icon" aria-hidden="true"><use xlink:href="/symbol-defs.svg#icon-check"/></svg>',
  531. []
  532. )
  533. },
  534. {
  535. 'type': bindingTypes.TAG,
  536. 'getComponent': getComponent,
  537. 'evaluate': function(
  538. _scope
  539. ) {
  540. return 'app-sidebar-button';
  541. },
  542. 'slots': [
  543. {
  544. 'id': 'default',
  545. 'html': '<svg class="icon" aria-hidden="true"><use xlink:href="/symbol-defs.svg#icon-edit"/></svg>',
  546. 'bindings': []
  547. }
  548. ],
  549. 'attributes': [
  550. {
  551. 'type': expressionTypes.ATTRIBUTE,
  552. 'name': 'data',
  553. 'evaluate': function(
  554. _scope
  555. ) {
  556. return _scope.user;
  557. }
  558. }
  559. ],
  560. 'redundantAttribute': 'expr9',
  561. 'selector': '[expr9]'
  562. },
  563. {
  564. 'redundantAttribute': 'expr10',
  565. 'selector': '[expr10]',
  566. 'expressions': [
  567. {
  568. 'type': expressionTypes.EVENT,
  569. 'name': 'onclick',
  570. 'evaluate': function(
  571. _scope
  572. ) {
  573. return (event) => { _scope.handleDelete(event, _scope.user) };
  574. }
  575. }
  576. ]
  577. }
  578. ]
  579. ),
  580. 'redundantAttribute': 'expr5',
  581. 'selector': '[expr5]',
  582. 'itemName': 'user',
  583. 'indexName': null,
  584. 'evaluate': function(
  585. _scope
  586. ) {
  587. return _scope.state.users;
  588. }
  589. },
  590. {
  591. 'type': bindingTypes.TAG,
  592. 'getComponent': getComponent,
  593. 'evaluate': function(
  594. _scope
  595. ) {
  596. return 'app-modal';
  597. },
  598. 'slots': [
  599. {
  600. 'id': 'title',
  601. 'html': '<span slot="title"><svg class="icon fill-text-contrast" aria-hidden="true"><use xlink:href="/symbol-defs.svg#icon-close"/></svg>\n Delete\n </span>',
  602. 'bindings': []
  603. }
  604. ],
  605. 'attributes': [],
  606. 'redundantAttribute': 'expr11',
  607. 'selector': '[expr11]'
  608. },
  609. {
  610. 'type': bindingTypes.IF,
  611. 'evaluate': function(
  612. _scope
  613. ) {
  614. return _scope.state.maxLength > _scope.state.users.length;
  615. },
  616. 'redundantAttribute': 'expr12',
  617. 'selector': '[expr12]',
  618. 'template': template(
  619. '<div class="col-12"><div class="buckets__more"><button expr13="expr13" type="button" class="button">\n More\n <svg class="icon" aria-hidden="true"><use xlink:href="/symbol-defs.svg#icon-arrow-down"/></svg></button></div></div>',
  620. [
  621. {
  622. 'redundantAttribute': 'expr13',
  623. 'selector': '[expr13]',
  624. 'expressions': [
  625. {
  626. 'type': expressionTypes.EVENT,
  627. 'name': 'onclick',
  628. 'evaluate': function(
  629. _scope
  630. ) {
  631. return _scope.handleClick;
  632. }
  633. }
  634. ]
  635. }
  636. ]
  637. )
  638. }
  639. ]
  640. );
  641. },
  642. 'name': 'app-users'
  643. });
  644. /***/ }),
  645. /***/ "./resources/js/components/users/form.riot":
  646. /*!*************************************************!*\
  647. !*** ./resources/js/components/users/form.riot ***!
  648. \*************************************************/
  649. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  650. "use strict";
  651. __webpack_require__.r(__webpack_exports__);
  652. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  653. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  654. /* harmony export */ });
  655. /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ "./node_modules/axios/index.js");
  656. /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);
  657. /* harmony import */ var riot__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! riot */ "./node_modules/riot/riot.esm.js");
  658. /* harmony import */ var _FormValidator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./../../FormValidator */ "./resources/js/FormValidator.js");
  659. /* harmony import */ var _field_error_riot__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./../field-error.riot */ "./resources/js/components/field-error.riot");
  660. riot__WEBPACK_IMPORTED_MODULE_3__.register('field-error', _field_error_riot__WEBPACK_IMPORTED_MODULE_2__.default)
  661. riot__WEBPACK_IMPORTED_MODULE_3__.mount('field-error')
  662. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  663. 'css': null,
  664. 'exports': {
  665. state: {
  666. user: {
  667. }
  668. },
  669. /**
  670. *
  671. *
  672. */
  673. onMounted(props, state) {
  674. this.root.addEventListener('app-users-form-open', (event) => {
  675. this.$('.sidebar').classList.add('sidebar--open')
  676. // check for data, and if user is send add to state
  677. if (event.detail.data) {
  678. this.state.user = event.detail.data
  679. this.state.formValidation.setConstraits({
  680. 'email': {
  681. 'length': {
  682. 'maximum': 255
  683. },
  684. 'email': true,
  685. 'presence': true
  686. }
  687. })
  688. this.update()
  689. }
  690. })
  691. // create form validation
  692. this.state.formValidation = new _FormValidator__WEBPACK_IMPORTED_MODULE_1__.default('#app-users-form', {
  693. 'email': {
  694. 'length': {
  695. 'maximum': 255
  696. },
  697. 'email': true,
  698. 'presence': true
  699. },
  700. 'password': {
  701. 'length': {
  702. 'maximum': 64
  703. },
  704. 'presence': true
  705. }
  706. }, (event, data) => {
  707. this.handleSubmit(event, data)
  708. })
  709. },
  710. /**
  711. * close current form
  712. *
  713. *
  714. * @param {object} event
  715. *
  716. */
  717. handleClose(event)
  718. {
  719. event.preventDefault()
  720. this.$('.sidebar').classList.remove('sidebar--open')
  721. this.reset()
  722. },
  723. /**
  724. *
  725. *
  726. */
  727. handleSubmit(event, data) {
  728. let method = 'post'
  729. let url = '/api/users'
  730. // user is set and has id, send as put with id
  731. if (this.state.user && this.state.user._id) {
  732. method = 'put'
  733. url += '/' + this.state.user._id
  734. }
  735. axios__WEBPACK_IMPORTED_MODULE_0___default()({
  736. method: method,
  737. url: url,
  738. data: data
  739. }).then((response) => {
  740. this.state.user = response.data.data
  741. console.log(event)
  742. if (event.submitter.attributes.close) {
  743. this.$('#sidebar-user-form-close').click()
  744. }
  745. this.update()
  746. })
  747. },
  748. /**
  749. *
  750. *
  751. */
  752. reset() {
  753. this.state.user = { }
  754. this.update()
  755. }
  756. },
  757. 'template': function(
  758. template,
  759. expressionTypes,
  760. bindingTypes,
  761. getComponent
  762. ) {
  763. return template(
  764. '<div class="sidebar"><div class="sidebar__inner"><div class="bar"><div class="bar__main"><span expr22="expr22"></span><span expr23="expr23"></span></div><div class="bar__end"><button expr24="expr24" id="sidebar-user-form-close" class="button button--transparent" type="button"><svg class="icon fill-text-contrast" aria-hidden="true"><use xlink:href="/symbol-defs.svg#icon-close"/></svg></button></div></div><div class="sidebar__body"><form id="app-users-form" novalidate><div class="field-group"><label class="field-label">\n E-Mail\n <input expr25="expr25" name="email" type="text" class="field-text"/></label><field-error expr26="expr26" name="email"></field-error></div><div class="field-group"><label class="field-label">\n Display Name\n <input expr27="expr27" name="display_name" type="text" class="field-text"/></label><field-error expr28="expr28" name="display_name"></field-error></div><div class="field-group"><label class="field-label">\n Password\n <input name="password" type="password" class="field-text"/></label><field-error expr29="expr29" name="password"></field-error></div><div class="field-group"><label class="field-label"><input name="roles[]" type="checkbox" class="field-choice" value="admin"/><svg class="icon field-choice__unchecked" aria-hidden="true"><use xlink:href="/symbol-defs.svg#icon-checkbox"/></svg><svg class="icon field-choice__checked" aria-hidden="true"><use xlink:href="/symbol-defs.svg#icon-checkbox-checked"/></svg>\n Admin\n </label><field-error expr30="expr30" name="roles"></field-error></div></form></div><div class="sidebar__footer"><button class="button m-bottom-0" type="submit" form="app-users-form">\n Save\n <svg class="icon fill-success p-left-3" aria-hidden="true"><use xlink:href="/symbol-defs.svg#icon-check"/></svg></button><button class="button m-bottom-0" type="submit" form="app-users-form" close>\n Save and Close\n <svg class="icon fill-success p-left-3" aria-hidden="true"><use xlink:href="/symbol-defs.svg#icon-arrow-right"/></svg></button></div></div></div>',
  765. [
  766. {
  767. 'type': bindingTypes.IF,
  768. 'evaluate': function(
  769. _scope
  770. ) {
  771. return !_scope.state.user._id;
  772. },
  773. 'redundantAttribute': 'expr22',
  774. 'selector': '[expr22]',
  775. 'template': template(
  776. '\n Create User\n ',
  777. []
  778. )
  779. },
  780. {
  781. 'type': bindingTypes.IF,
  782. 'evaluate': function(
  783. _scope
  784. ) {
  785. return _scope.state.user._id;
  786. },
  787. 'redundantAttribute': 'expr23',
  788. 'selector': '[expr23]',
  789. 'template': template(
  790. '\n Update User\n ',
  791. []
  792. )
  793. },
  794. {
  795. 'redundantAttribute': 'expr24',
  796. 'selector': '[expr24]',
  797. 'expressions': [
  798. {
  799. 'type': expressionTypes.EVENT,
  800. 'name': 'onclick',
  801. 'evaluate': function(
  802. _scope
  803. ) {
  804. return (event) => { _scope.handleClose(event) };
  805. }
  806. }
  807. ]
  808. },
  809. {
  810. 'redundantAttribute': 'expr25',
  811. 'selector': '[expr25]',
  812. 'expressions': [
  813. {
  814. 'type': expressionTypes.VALUE,
  815. 'evaluate': function(
  816. _scope
  817. ) {
  818. return _scope.state.user.email;
  819. }
  820. }
  821. ]
  822. },
  823. {
  824. 'type': bindingTypes.TAG,
  825. 'getComponent': getComponent,
  826. 'evaluate': function(
  827. _scope
  828. ) {
  829. return 'field-error';
  830. },
  831. 'slots': [],
  832. 'attributes': [],
  833. 'redundantAttribute': 'expr26',
  834. 'selector': '[expr26]'
  835. },
  836. {
  837. 'redundantAttribute': 'expr27',
  838. 'selector': '[expr27]',
  839. 'expressions': [
  840. {
  841. 'type': expressionTypes.VALUE,
  842. 'evaluate': function(
  843. _scope
  844. ) {
  845. return _scope.state.user.display_name;
  846. }
  847. }
  848. ]
  849. },
  850. {
  851. 'type': bindingTypes.TAG,
  852. 'getComponent': getComponent,
  853. 'evaluate': function(
  854. _scope
  855. ) {
  856. return 'field-error';
  857. },
  858. 'slots': [],
  859. 'attributes': [],
  860. 'redundantAttribute': 'expr28',
  861. 'selector': '[expr28]'
  862. },
  863. {
  864. 'type': bindingTypes.TAG,
  865. 'getComponent': getComponent,
  866. 'evaluate': function(
  867. _scope
  868. ) {
  869. return 'field-error';
  870. },
  871. 'slots': [],
  872. 'attributes': [],
  873. 'redundantAttribute': 'expr29',
  874. 'selector': '[expr29]'
  875. },
  876. {
  877. 'type': bindingTypes.TAG,
  878. 'getComponent': getComponent,
  879. 'evaluate': function(
  880. _scope
  881. ) {
  882. return 'field-error';
  883. },
  884. 'slots': [],
  885. 'attributes': [],
  886. 'redundantAttribute': 'expr30',
  887. 'selector': '[expr30]'
  888. }
  889. ]
  890. );
  891. },
  892. 'name': 'app-users-form'
  893. });
  894. /***/ }),
  895. /***/ "./node_modules/axios/index.js":
  896. /*!*************************************!*\
  897. !*** ./node_modules/axios/index.js ***!
  898. \*************************************/
  899. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  900. module.exports = __webpack_require__(/*! ./lib/axios */ "./node_modules/axios/lib/axios.js");
  901. /***/ }),
  902. /***/ "./node_modules/axios/lib/adapters/xhr.js":
  903. /*!************************************************!*\
  904. !*** ./node_modules/axios/lib/adapters/xhr.js ***!
  905. \************************************************/
  906. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  907. "use strict";
  908. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  909. var settle = __webpack_require__(/*! ./../core/settle */ "./node_modules/axios/lib/core/settle.js");
  910. var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./node_modules/axios/lib/helpers/cookies.js");
  911. var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js");
  912. var buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ "./node_modules/axios/lib/core/buildFullPath.js");
  913. var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./node_modules/axios/lib/helpers/parseHeaders.js");
  914. var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./node_modules/axios/lib/helpers/isURLSameOrigin.js");
  915. var createError = __webpack_require__(/*! ../core/createError */ "./node_modules/axios/lib/core/createError.js");
  916. module.exports = function xhrAdapter(config) {
  917. return new Promise(function dispatchXhrRequest(resolve, reject) {
  918. var requestData = config.data;
  919. var requestHeaders = config.headers;
  920. if (utils.isFormData(requestData)) {
  921. delete requestHeaders['Content-Type']; // Let the browser set it
  922. }
  923. var request = new XMLHttpRequest();
  924. // HTTP basic authentication
  925. if (config.auth) {
  926. var username = config.auth.username || '';
  927. var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
  928. requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
  929. }
  930. var fullPath = buildFullPath(config.baseURL, config.url);
  931. request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
  932. // Set the request timeout in MS
  933. request.timeout = config.timeout;
  934. // Listen for ready state
  935. request.onreadystatechange = function handleLoad() {
  936. if (!request || request.readyState !== 4) {
  937. return;
  938. }
  939. // The request errored out and we didn't get a response, this will be
  940. // handled by onerror instead
  941. // With one exception: request that using file: protocol, most browsers
  942. // will return status as 0 even though it's a successful request
  943. if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
  944. return;
  945. }
  946. // Prepare the response
  947. var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
  948. var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
  949. var response = {
  950. data: responseData,
  951. status: request.status,
  952. statusText: request.statusText,
  953. headers: responseHeaders,
  954. config: config,
  955. request: request
  956. };
  957. settle(resolve, reject, response);
  958. // Clean up request
  959. request = null;
  960. };
  961. // Handle browser request cancellation (as opposed to a manual cancellation)
  962. request.onabort = function handleAbort() {
  963. if (!request) {
  964. return;
  965. }
  966. reject(createError('Request aborted', config, 'ECONNABORTED', request));
  967. // Clean up request
  968. request = null;
  969. };
  970. // Handle low level network errors
  971. request.onerror = function handleError() {
  972. // Real errors are hidden from us by the browser
  973. // onerror should only fire if it's a network error
  974. reject(createError('Network Error', config, null, request));
  975. // Clean up request
  976. request = null;
  977. };
  978. // Handle timeout
  979. request.ontimeout = function handleTimeout() {
  980. var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
  981. if (config.timeoutErrorMessage) {
  982. timeoutErrorMessage = config.timeoutErrorMessage;
  983. }
  984. reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
  985. request));
  986. // Clean up request
  987. request = null;
  988. };
  989. // Add xsrf header
  990. // This is only done if running in a standard browser environment.
  991. // Specifically not if we're in a web worker, or react-native.
  992. if (utils.isStandardBrowserEnv()) {
  993. // Add xsrf header
  994. var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
  995. cookies.read(config.xsrfCookieName) :
  996. undefined;
  997. if (xsrfValue) {
  998. requestHeaders[config.xsrfHeaderName] = xsrfValue;
  999. }
  1000. }
  1001. // Add headers to the request
  1002. if ('setRequestHeader' in request) {
  1003. utils.forEach(requestHeaders, function setRequestHeader(val, key) {
  1004. if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
  1005. // Remove Content-Type if data is undefined
  1006. delete requestHeaders[key];
  1007. } else {
  1008. // Otherwise add header to the request
  1009. request.setRequestHeader(key, val);
  1010. }
  1011. });
  1012. }
  1013. // Add withCredentials to request if needed
  1014. if (!utils.isUndefined(config.withCredentials)) {
  1015. request.withCredentials = !!config.withCredentials;
  1016. }
  1017. // Add responseType to request if needed
  1018. if (config.responseType) {
  1019. try {
  1020. request.responseType = config.responseType;
  1021. } catch (e) {
  1022. // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
  1023. // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
  1024. if (config.responseType !== 'json') {
  1025. throw e;
  1026. }
  1027. }
  1028. }
  1029. // Handle progress if needed
  1030. if (typeof config.onDownloadProgress === 'function') {
  1031. request.addEventListener('progress', config.onDownloadProgress);
  1032. }
  1033. // Not all browsers support upload events
  1034. if (typeof config.onUploadProgress === 'function' && request.upload) {
  1035. request.upload.addEventListener('progress', config.onUploadProgress);
  1036. }
  1037. if (config.cancelToken) {
  1038. // Handle cancellation
  1039. config.cancelToken.promise.then(function onCanceled(cancel) {
  1040. if (!request) {
  1041. return;
  1042. }
  1043. request.abort();
  1044. reject(cancel);
  1045. // Clean up request
  1046. request = null;
  1047. });
  1048. }
  1049. if (!requestData) {
  1050. requestData = null;
  1051. }
  1052. // Send the request
  1053. request.send(requestData);
  1054. });
  1055. };
  1056. /***/ }),
  1057. /***/ "./node_modules/axios/lib/axios.js":
  1058. /*!*****************************************!*\
  1059. !*** ./node_modules/axios/lib/axios.js ***!
  1060. \*****************************************/
  1061. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1062. "use strict";
  1063. var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js");
  1064. var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js");
  1065. var Axios = __webpack_require__(/*! ./core/Axios */ "./node_modules/axios/lib/core/Axios.js");
  1066. var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js");
  1067. var defaults = __webpack_require__(/*! ./defaults */ "./node_modules/axios/lib/defaults.js");
  1068. /**
  1069. * Create an instance of Axios
  1070. *
  1071. * @param {Object} defaultConfig The default config for the instance
  1072. * @return {Axios} A new instance of Axios
  1073. */
  1074. function createInstance(defaultConfig) {
  1075. var context = new Axios(defaultConfig);
  1076. var instance = bind(Axios.prototype.request, context);
  1077. // Copy axios.prototype to instance
  1078. utils.extend(instance, Axios.prototype, context);
  1079. // Copy context to instance
  1080. utils.extend(instance, context);
  1081. return instance;
  1082. }
  1083. // Create the default instance to be exported
  1084. var axios = createInstance(defaults);
  1085. // Expose Axios class to allow class inheritance
  1086. axios.Axios = Axios;
  1087. // Factory for creating new instances
  1088. axios.create = function create(instanceConfig) {
  1089. return createInstance(mergeConfig(axios.defaults, instanceConfig));
  1090. };
  1091. // Expose Cancel & CancelToken
  1092. axios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ "./node_modules/axios/lib/cancel/Cancel.js");
  1093. axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./node_modules/axios/lib/cancel/CancelToken.js");
  1094. axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js");
  1095. // Expose all/spread
  1096. axios.all = function all(promises) {
  1097. return Promise.all(promises);
  1098. };
  1099. axios.spread = __webpack_require__(/*! ./helpers/spread */ "./node_modules/axios/lib/helpers/spread.js");
  1100. // Expose isAxiosError
  1101. axios.isAxiosError = __webpack_require__(/*! ./helpers/isAxiosError */ "./node_modules/axios/lib/helpers/isAxiosError.js");
  1102. module.exports = axios;
  1103. // Allow use of default import syntax in TypeScript
  1104. module.exports.default = axios;
  1105. /***/ }),
  1106. /***/ "./node_modules/axios/lib/cancel/Cancel.js":
  1107. /*!*************************************************!*\
  1108. !*** ./node_modules/axios/lib/cancel/Cancel.js ***!
  1109. \*************************************************/
  1110. /***/ ((module) => {
  1111. "use strict";
  1112. /**
  1113. * A `Cancel` is an object that is thrown when an operation is canceled.
  1114. *
  1115. * @class
  1116. * @param {string=} message The message.
  1117. */
  1118. function Cancel(message) {
  1119. this.message = message;
  1120. }
  1121. Cancel.prototype.toString = function toString() {
  1122. return 'Cancel' + (this.message ? ': ' + this.message : '');
  1123. };
  1124. Cancel.prototype.__CANCEL__ = true;
  1125. module.exports = Cancel;
  1126. /***/ }),
  1127. /***/ "./node_modules/axios/lib/cancel/CancelToken.js":
  1128. /*!******************************************************!*\
  1129. !*** ./node_modules/axios/lib/cancel/CancelToken.js ***!
  1130. \******************************************************/
  1131. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1132. "use strict";
  1133. var Cancel = __webpack_require__(/*! ./Cancel */ "./node_modules/axios/lib/cancel/Cancel.js");
  1134. /**
  1135. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  1136. *
  1137. * @class
  1138. * @param {Function} executor The executor function.
  1139. */
  1140. function CancelToken(executor) {
  1141. if (typeof executor !== 'function') {
  1142. throw new TypeError('executor must be a function.');
  1143. }
  1144. var resolvePromise;
  1145. this.promise = new Promise(function promiseExecutor(resolve) {
  1146. resolvePromise = resolve;
  1147. });
  1148. var token = this;
  1149. executor(function cancel(message) {
  1150. if (token.reason) {
  1151. // Cancellation has already been requested
  1152. return;
  1153. }
  1154. token.reason = new Cancel(message);
  1155. resolvePromise(token.reason);
  1156. });
  1157. }
  1158. /**
  1159. * Throws a `Cancel` if cancellation has been requested.
  1160. */
  1161. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  1162. if (this.reason) {
  1163. throw this.reason;
  1164. }
  1165. };
  1166. /**
  1167. * Returns an object that contains a new `CancelToken` and a function that, when called,
  1168. * cancels the `CancelToken`.
  1169. */
  1170. CancelToken.source = function source() {
  1171. var cancel;
  1172. var token = new CancelToken(function executor(c) {
  1173. cancel = c;
  1174. });
  1175. return {
  1176. token: token,
  1177. cancel: cancel
  1178. };
  1179. };
  1180. module.exports = CancelToken;
  1181. /***/ }),
  1182. /***/ "./node_modules/axios/lib/cancel/isCancel.js":
  1183. /*!***************************************************!*\
  1184. !*** ./node_modules/axios/lib/cancel/isCancel.js ***!
  1185. \***************************************************/
  1186. /***/ ((module) => {
  1187. "use strict";
  1188. module.exports = function isCancel(value) {
  1189. return !!(value && value.__CANCEL__);
  1190. };
  1191. /***/ }),
  1192. /***/ "./node_modules/axios/lib/core/Axios.js":
  1193. /*!**********************************************!*\
  1194. !*** ./node_modules/axios/lib/core/Axios.js ***!
  1195. \**********************************************/
  1196. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1197. "use strict";
  1198. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1199. var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js");
  1200. var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./node_modules/axios/lib/core/InterceptorManager.js");
  1201. var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./node_modules/axios/lib/core/dispatchRequest.js");
  1202. var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js");
  1203. /**
  1204. * Create a new instance of Axios
  1205. *
  1206. * @param {Object} instanceConfig The default config for the instance
  1207. */
  1208. function Axios(instanceConfig) {
  1209. this.defaults = instanceConfig;
  1210. this.interceptors = {
  1211. request: new InterceptorManager(),
  1212. response: new InterceptorManager()
  1213. };
  1214. }
  1215. /**
  1216. * Dispatch a request
  1217. *
  1218. * @param {Object} config The config specific for this request (merged with this.defaults)
  1219. */
  1220. Axios.prototype.request = function request(config) {
  1221. /*eslint no-param-reassign:0*/
  1222. // Allow for axios('example/url'[, config]) a la fetch API
  1223. if (typeof config === 'string') {
  1224. config = arguments[1] || {};
  1225. config.url = arguments[0];
  1226. } else {
  1227. config = config || {};
  1228. }
  1229. config = mergeConfig(this.defaults, config);
  1230. // Set config.method
  1231. if (config.method) {
  1232. config.method = config.method.toLowerCase();
  1233. } else if (this.defaults.method) {
  1234. config.method = this.defaults.method.toLowerCase();
  1235. } else {
  1236. config.method = 'get';
  1237. }
  1238. // Hook up interceptors middleware
  1239. var chain = [dispatchRequest, undefined];
  1240. var promise = Promise.resolve(config);
  1241. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  1242. chain.unshift(interceptor.fulfilled, interceptor.rejected);
  1243. });
  1244. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  1245. chain.push(interceptor.fulfilled, interceptor.rejected);
  1246. });
  1247. while (chain.length) {
  1248. promise = promise.then(chain.shift(), chain.shift());
  1249. }
  1250. return promise;
  1251. };
  1252. Axios.prototype.getUri = function getUri(config) {
  1253. config = mergeConfig(this.defaults, config);
  1254. return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
  1255. };
  1256. // Provide aliases for supported request methods
  1257. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  1258. /*eslint func-names:0*/
  1259. Axios.prototype[method] = function(url, config) {
  1260. return this.request(mergeConfig(config || {}, {
  1261. method: method,
  1262. url: url,
  1263. data: (config || {}).data
  1264. }));
  1265. };
  1266. });
  1267. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  1268. /*eslint func-names:0*/
  1269. Axios.prototype[method] = function(url, data, config) {
  1270. return this.request(mergeConfig(config || {}, {
  1271. method: method,
  1272. url: url,
  1273. data: data
  1274. }));
  1275. };
  1276. });
  1277. module.exports = Axios;
  1278. /***/ }),
  1279. /***/ "./node_modules/axios/lib/core/InterceptorManager.js":
  1280. /*!***********************************************************!*\
  1281. !*** ./node_modules/axios/lib/core/InterceptorManager.js ***!
  1282. \***********************************************************/
  1283. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1284. "use strict";
  1285. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1286. function InterceptorManager() {
  1287. this.handlers = [];
  1288. }
  1289. /**
  1290. * Add a new interceptor to the stack
  1291. *
  1292. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  1293. * @param {Function} rejected The function to handle `reject` for a `Promise`
  1294. *
  1295. * @return {Number} An ID used to remove interceptor later
  1296. */
  1297. InterceptorManager.prototype.use = function use(fulfilled, rejected) {
  1298. this.handlers.push({
  1299. fulfilled: fulfilled,
  1300. rejected: rejected
  1301. });
  1302. return this.handlers.length - 1;
  1303. };
  1304. /**
  1305. * Remove an interceptor from the stack
  1306. *
  1307. * @param {Number} id The ID that was returned by `use`
  1308. */
  1309. InterceptorManager.prototype.eject = function eject(id) {
  1310. if (this.handlers[id]) {
  1311. this.handlers[id] = null;
  1312. }
  1313. };
  1314. /**
  1315. * Iterate over all the registered interceptors
  1316. *
  1317. * This method is particularly useful for skipping over any
  1318. * interceptors that may have become `null` calling `eject`.
  1319. *
  1320. * @param {Function} fn The function to call for each interceptor
  1321. */
  1322. InterceptorManager.prototype.forEach = function forEach(fn) {
  1323. utils.forEach(this.handlers, function forEachHandler(h) {
  1324. if (h !== null) {
  1325. fn(h);
  1326. }
  1327. });
  1328. };
  1329. module.exports = InterceptorManager;
  1330. /***/ }),
  1331. /***/ "./node_modules/axios/lib/core/buildFullPath.js":
  1332. /*!******************************************************!*\
  1333. !*** ./node_modules/axios/lib/core/buildFullPath.js ***!
  1334. \******************************************************/
  1335. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1336. "use strict";
  1337. var isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ "./node_modules/axios/lib/helpers/isAbsoluteURL.js");
  1338. var combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ "./node_modules/axios/lib/helpers/combineURLs.js");
  1339. /**
  1340. * Creates a new URL by combining the baseURL with the requestedURL,
  1341. * only when the requestedURL is not already an absolute URL.
  1342. * If the requestURL is absolute, this function returns the requestedURL untouched.
  1343. *
  1344. * @param {string} baseURL The base URL
  1345. * @param {string} requestedURL Absolute or relative URL to combine
  1346. * @returns {string} The combined full path
  1347. */
  1348. module.exports = function buildFullPath(baseURL, requestedURL) {
  1349. if (baseURL && !isAbsoluteURL(requestedURL)) {
  1350. return combineURLs(baseURL, requestedURL);
  1351. }
  1352. return requestedURL;
  1353. };
  1354. /***/ }),
  1355. /***/ "./node_modules/axios/lib/core/createError.js":
  1356. /*!****************************************************!*\
  1357. !*** ./node_modules/axios/lib/core/createError.js ***!
  1358. \****************************************************/
  1359. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1360. "use strict";
  1361. var enhanceError = __webpack_require__(/*! ./enhanceError */ "./node_modules/axios/lib/core/enhanceError.js");
  1362. /**
  1363. * Create an Error with the specified message, config, error code, request and response.
  1364. *
  1365. * @param {string} message The error message.
  1366. * @param {Object} config The config.
  1367. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  1368. * @param {Object} [request] The request.
  1369. * @param {Object} [response] The response.
  1370. * @returns {Error} The created error.
  1371. */
  1372. module.exports = function createError(message, config, code, request, response) {
  1373. var error = new Error(message);
  1374. return enhanceError(error, config, code, request, response);
  1375. };
  1376. /***/ }),
  1377. /***/ "./node_modules/axios/lib/core/dispatchRequest.js":
  1378. /*!********************************************************!*\
  1379. !*** ./node_modules/axios/lib/core/dispatchRequest.js ***!
  1380. \********************************************************/
  1381. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1382. "use strict";
  1383. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1384. var transformData = __webpack_require__(/*! ./transformData */ "./node_modules/axios/lib/core/transformData.js");
  1385. var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js");
  1386. var defaults = __webpack_require__(/*! ../defaults */ "./node_modules/axios/lib/defaults.js");
  1387. /**
  1388. * Throws a `Cancel` if cancellation has been requested.
  1389. */
  1390. function throwIfCancellationRequested(config) {
  1391. if (config.cancelToken) {
  1392. config.cancelToken.throwIfRequested();
  1393. }
  1394. }
  1395. /**
  1396. * Dispatch a request to the server using the configured adapter.
  1397. *
  1398. * @param {object} config The config that is to be used for the request
  1399. * @returns {Promise} The Promise to be fulfilled
  1400. */
  1401. module.exports = function dispatchRequest(config) {
  1402. throwIfCancellationRequested(config);
  1403. // Ensure headers exist
  1404. config.headers = config.headers || {};
  1405. // Transform request data
  1406. config.data = transformData(
  1407. config.data,
  1408. config.headers,
  1409. config.transformRequest
  1410. );
  1411. // Flatten headers
  1412. config.headers = utils.merge(
  1413. config.headers.common || {},
  1414. config.headers[config.method] || {},
  1415. config.headers
  1416. );
  1417. utils.forEach(
  1418. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  1419. function cleanHeaderConfig(method) {
  1420. delete config.headers[method];
  1421. }
  1422. );
  1423. var adapter = config.adapter || defaults.adapter;
  1424. return adapter(config).then(function onAdapterResolution(response) {
  1425. throwIfCancellationRequested(config);
  1426. // Transform response data
  1427. response.data = transformData(
  1428. response.data,
  1429. response.headers,
  1430. config.transformResponse
  1431. );
  1432. return response;
  1433. }, function onAdapterRejection(reason) {
  1434. if (!isCancel(reason)) {
  1435. throwIfCancellationRequested(config);
  1436. // Transform response data
  1437. if (reason && reason.response) {
  1438. reason.response.data = transformData(
  1439. reason.response.data,
  1440. reason.response.headers,
  1441. config.transformResponse
  1442. );
  1443. }
  1444. }
  1445. return Promise.reject(reason);
  1446. });
  1447. };
  1448. /***/ }),
  1449. /***/ "./node_modules/axios/lib/core/enhanceError.js":
  1450. /*!*****************************************************!*\
  1451. !*** ./node_modules/axios/lib/core/enhanceError.js ***!
  1452. \*****************************************************/
  1453. /***/ ((module) => {
  1454. "use strict";
  1455. /**
  1456. * Update an Error with the specified config, error code, and response.
  1457. *
  1458. * @param {Error} error The error to update.
  1459. * @param {Object} config The config.
  1460. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  1461. * @param {Object} [request] The request.
  1462. * @param {Object} [response] The response.
  1463. * @returns {Error} The error.
  1464. */
  1465. module.exports = function enhanceError(error, config, code, request, response) {
  1466. error.config = config;
  1467. if (code) {
  1468. error.code = code;
  1469. }
  1470. error.request = request;
  1471. error.response = response;
  1472. error.isAxiosError = true;
  1473. error.toJSON = function toJSON() {
  1474. return {
  1475. // Standard
  1476. message: this.message,
  1477. name: this.name,
  1478. // Microsoft
  1479. description: this.description,
  1480. number: this.number,
  1481. // Mozilla
  1482. fileName: this.fileName,
  1483. lineNumber: this.lineNumber,
  1484. columnNumber: this.columnNumber,
  1485. stack: this.stack,
  1486. // Axios
  1487. config: this.config,
  1488. code: this.code
  1489. };
  1490. };
  1491. return error;
  1492. };
  1493. /***/ }),
  1494. /***/ "./node_modules/axios/lib/core/mergeConfig.js":
  1495. /*!****************************************************!*\
  1496. !*** ./node_modules/axios/lib/core/mergeConfig.js ***!
  1497. \****************************************************/
  1498. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1499. "use strict";
  1500. var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js");
  1501. /**
  1502. * Config-specific merge-function which creates a new config-object
  1503. * by merging two configuration objects together.
  1504. *
  1505. * @param {Object} config1
  1506. * @param {Object} config2
  1507. * @returns {Object} New object resulting from merging config2 to config1
  1508. */
  1509. module.exports = function mergeConfig(config1, config2) {
  1510. // eslint-disable-next-line no-param-reassign
  1511. config2 = config2 || {};
  1512. var config = {};
  1513. var valueFromConfig2Keys = ['url', 'method', 'data'];
  1514. var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];
  1515. var defaultToConfig2Keys = [
  1516. 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',
  1517. 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
  1518. 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',
  1519. 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',
  1520. 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'
  1521. ];
  1522. var directMergeKeys = ['validateStatus'];
  1523. function getMergedValue(target, source) {
  1524. if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
  1525. return utils.merge(target, source);
  1526. } else if (utils.isPlainObject(source)) {
  1527. return utils.merge({}, source);
  1528. } else if (utils.isArray(source)) {
  1529. return source.slice();
  1530. }
  1531. return source;
  1532. }
  1533. function mergeDeepProperties(prop) {
  1534. if (!utils.isUndefined(config2[prop])) {
  1535. config[prop] = getMergedValue(config1[prop], config2[prop]);
  1536. } else if (!utils.isUndefined(config1[prop])) {
  1537. config[prop] = getMergedValue(undefined, config1[prop]);
  1538. }
  1539. }
  1540. utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
  1541. if (!utils.isUndefined(config2[prop])) {
  1542. config[prop] = getMergedValue(undefined, config2[prop]);
  1543. }
  1544. });
  1545. utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
  1546. utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
  1547. if (!utils.isUndefined(config2[prop])) {
  1548. config[prop] = getMergedValue(undefined, config2[prop]);
  1549. } else if (!utils.isUndefined(config1[prop])) {
  1550. config[prop] = getMergedValue(undefined, config1[prop]);
  1551. }
  1552. });
  1553. utils.forEach(directMergeKeys, function merge(prop) {
  1554. if (prop in config2) {
  1555. config[prop] = getMergedValue(config1[prop], config2[prop]);
  1556. } else if (prop in config1) {
  1557. config[prop] = getMergedValue(undefined, config1[prop]);
  1558. }
  1559. });
  1560. var axiosKeys = valueFromConfig2Keys
  1561. .concat(mergeDeepPropertiesKeys)
  1562. .concat(defaultToConfig2Keys)
  1563. .concat(directMergeKeys);
  1564. var otherKeys = Object
  1565. .keys(config1)
  1566. .concat(Object.keys(config2))
  1567. .filter(function filterAxiosKeys(key) {
  1568. return axiosKeys.indexOf(key) === -1;
  1569. });
  1570. utils.forEach(otherKeys, mergeDeepProperties);
  1571. return config;
  1572. };
  1573. /***/ }),
  1574. /***/ "./node_modules/axios/lib/core/settle.js":
  1575. /*!***********************************************!*\
  1576. !*** ./node_modules/axios/lib/core/settle.js ***!
  1577. \***********************************************/
  1578. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1579. "use strict";
  1580. var createError = __webpack_require__(/*! ./createError */ "./node_modules/axios/lib/core/createError.js");
  1581. /**
  1582. * Resolve or reject a Promise based on response status.
  1583. *
  1584. * @param {Function} resolve A function that resolves the promise.
  1585. * @param {Function} reject A function that rejects the promise.
  1586. * @param {object} response The response.
  1587. */
  1588. module.exports = function settle(resolve, reject, response) {
  1589. var validateStatus = response.config.validateStatus;
  1590. if (!response.status || !validateStatus || validateStatus(response.status)) {
  1591. resolve(response);
  1592. } else {
  1593. reject(createError(
  1594. 'Request failed with status code ' + response.status,
  1595. response.config,
  1596. null,
  1597. response.request,
  1598. response
  1599. ));
  1600. }
  1601. };
  1602. /***/ }),
  1603. /***/ "./node_modules/axios/lib/core/transformData.js":
  1604. /*!******************************************************!*\
  1605. !*** ./node_modules/axios/lib/core/transformData.js ***!
  1606. \******************************************************/
  1607. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1608. "use strict";
  1609. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1610. /**
  1611. * Transform the data for a request or a response
  1612. *
  1613. * @param {Object|String} data The data to be transformed
  1614. * @param {Array} headers The headers for the request or response
  1615. * @param {Array|Function} fns A single function or Array of functions
  1616. * @returns {*} The resulting transformed data
  1617. */
  1618. module.exports = function transformData(data, headers, fns) {
  1619. /*eslint no-param-reassign:0*/
  1620. utils.forEach(fns, function transform(fn) {
  1621. data = fn(data, headers);
  1622. });
  1623. return data;
  1624. };
  1625. /***/ }),
  1626. /***/ "./node_modules/axios/lib/defaults.js":
  1627. /*!********************************************!*\
  1628. !*** ./node_modules/axios/lib/defaults.js ***!
  1629. \********************************************/
  1630. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1631. "use strict";
  1632. /* provided dependency */ var process = __webpack_require__(/*! process/browser */ "./node_modules/process/browser.js");
  1633. var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js");
  1634. var normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ "./node_modules/axios/lib/helpers/normalizeHeaderName.js");
  1635. var DEFAULT_CONTENT_TYPE = {
  1636. 'Content-Type': 'application/x-www-form-urlencoded'
  1637. };
  1638. function setContentTypeIfUnset(headers, value) {
  1639. if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
  1640. headers['Content-Type'] = value;
  1641. }
  1642. }
  1643. function getDefaultAdapter() {
  1644. var adapter;
  1645. if (typeof XMLHttpRequest !== 'undefined') {
  1646. // For browsers use XHR adapter
  1647. adapter = __webpack_require__(/*! ./adapters/xhr */ "./node_modules/axios/lib/adapters/xhr.js");
  1648. } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
  1649. // For node use HTTP adapter
  1650. adapter = __webpack_require__(/*! ./adapters/http */ "./node_modules/axios/lib/adapters/xhr.js");
  1651. }
  1652. return adapter;
  1653. }
  1654. var defaults = {
  1655. adapter: getDefaultAdapter(),
  1656. transformRequest: [function transformRequest(data, headers) {
  1657. normalizeHeaderName(headers, 'Accept');
  1658. normalizeHeaderName(headers, 'Content-Type');
  1659. if (utils.isFormData(data) ||
  1660. utils.isArrayBuffer(data) ||
  1661. utils.isBuffer(data) ||
  1662. utils.isStream(data) ||
  1663. utils.isFile(data) ||
  1664. utils.isBlob(data)
  1665. ) {
  1666. return data;
  1667. }
  1668. if (utils.isArrayBufferView(data)) {
  1669. return data.buffer;
  1670. }
  1671. if (utils.isURLSearchParams(data)) {
  1672. setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
  1673. return data.toString();
  1674. }
  1675. if (utils.isObject(data)) {
  1676. setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
  1677. return JSON.stringify(data);
  1678. }
  1679. return data;
  1680. }],
  1681. transformResponse: [function transformResponse(data) {
  1682. /*eslint no-param-reassign:0*/
  1683. if (typeof data === 'string') {
  1684. try {
  1685. data = JSON.parse(data);
  1686. } catch (e) { /* Ignore */ }
  1687. }
  1688. return data;
  1689. }],
  1690. /**
  1691. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  1692. * timeout is not created.
  1693. */
  1694. timeout: 0,
  1695. xsrfCookieName: 'XSRF-TOKEN',
  1696. xsrfHeaderName: 'X-XSRF-TOKEN',
  1697. maxContentLength: -1,
  1698. maxBodyLength: -1,
  1699. validateStatus: function validateStatus(status) {
  1700. return status >= 200 && status < 300;
  1701. }
  1702. };
  1703. defaults.headers = {
  1704. common: {
  1705. 'Accept': 'application/json, text/plain, */*'
  1706. }
  1707. };
  1708. utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
  1709. defaults.headers[method] = {};
  1710. });
  1711. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  1712. defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
  1713. });
  1714. module.exports = defaults;
  1715. /***/ }),
  1716. /***/ "./node_modules/axios/lib/helpers/bind.js":
  1717. /*!************************************************!*\
  1718. !*** ./node_modules/axios/lib/helpers/bind.js ***!
  1719. \************************************************/
  1720. /***/ ((module) => {
  1721. "use strict";
  1722. module.exports = function bind(fn, thisArg) {
  1723. return function wrap() {
  1724. var args = new Array(arguments.length);
  1725. for (var i = 0; i < args.length; i++) {
  1726. args[i] = arguments[i];
  1727. }
  1728. return fn.apply(thisArg, args);
  1729. };
  1730. };
  1731. /***/ }),
  1732. /***/ "./node_modules/axios/lib/helpers/buildURL.js":
  1733. /*!****************************************************!*\
  1734. !*** ./node_modules/axios/lib/helpers/buildURL.js ***!
  1735. \****************************************************/
  1736. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1737. "use strict";
  1738. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1739. function encode(val) {
  1740. return encodeURIComponent(val).
  1741. replace(/%3A/gi, ':').
  1742. replace(/%24/g, '$').
  1743. replace(/%2C/gi, ',').
  1744. replace(/%20/g, '+').
  1745. replace(/%5B/gi, '[').
  1746. replace(/%5D/gi, ']');
  1747. }
  1748. /**
  1749. * Build a URL by appending params to the end
  1750. *
  1751. * @param {string} url The base of the url (e.g., http://www.google.com)
  1752. * @param {object} [params] The params to be appended
  1753. * @returns {string} The formatted url
  1754. */
  1755. module.exports = function buildURL(url, params, paramsSerializer) {
  1756. /*eslint no-param-reassign:0*/
  1757. if (!params) {
  1758. return url;
  1759. }
  1760. var serializedParams;
  1761. if (paramsSerializer) {
  1762. serializedParams = paramsSerializer(params);
  1763. } else if (utils.isURLSearchParams(params)) {
  1764. serializedParams = params.toString();
  1765. } else {
  1766. var parts = [];
  1767. utils.forEach(params, function serialize(val, key) {
  1768. if (val === null || typeof val === 'undefined') {
  1769. return;
  1770. }
  1771. if (utils.isArray(val)) {
  1772. key = key + '[]';
  1773. } else {
  1774. val = [val];
  1775. }
  1776. utils.forEach(val, function parseValue(v) {
  1777. if (utils.isDate(v)) {
  1778. v = v.toISOString();
  1779. } else if (utils.isObject(v)) {
  1780. v = JSON.stringify(v);
  1781. }
  1782. parts.push(encode(key) + '=' + encode(v));
  1783. });
  1784. });
  1785. serializedParams = parts.join('&');
  1786. }
  1787. if (serializedParams) {
  1788. var hashmarkIndex = url.indexOf('#');
  1789. if (hashmarkIndex !== -1) {
  1790. url = url.slice(0, hashmarkIndex);
  1791. }
  1792. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  1793. }
  1794. return url;
  1795. };
  1796. /***/ }),
  1797. /***/ "./node_modules/axios/lib/helpers/combineURLs.js":
  1798. /*!*******************************************************!*\
  1799. !*** ./node_modules/axios/lib/helpers/combineURLs.js ***!
  1800. \*******************************************************/
  1801. /***/ ((module) => {
  1802. "use strict";
  1803. /**
  1804. * Creates a new URL by combining the specified URLs
  1805. *
  1806. * @param {string} baseURL The base URL
  1807. * @param {string} relativeURL The relative URL
  1808. * @returns {string} The combined URL
  1809. */
  1810. module.exports = function combineURLs(baseURL, relativeURL) {
  1811. return relativeURL
  1812. ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
  1813. : baseURL;
  1814. };
  1815. /***/ }),
  1816. /***/ "./node_modules/axios/lib/helpers/cookies.js":
  1817. /*!***************************************************!*\
  1818. !*** ./node_modules/axios/lib/helpers/cookies.js ***!
  1819. \***************************************************/
  1820. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1821. "use strict";
  1822. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1823. module.exports = (
  1824. utils.isStandardBrowserEnv() ?
  1825. // Standard browser envs support document.cookie
  1826. (function standardBrowserEnv() {
  1827. return {
  1828. write: function write(name, value, expires, path, domain, secure) {
  1829. var cookie = [];
  1830. cookie.push(name + '=' + encodeURIComponent(value));
  1831. if (utils.isNumber(expires)) {
  1832. cookie.push('expires=' + new Date(expires).toGMTString());
  1833. }
  1834. if (utils.isString(path)) {
  1835. cookie.push('path=' + path);
  1836. }
  1837. if (utils.isString(domain)) {
  1838. cookie.push('domain=' + domain);
  1839. }
  1840. if (secure === true) {
  1841. cookie.push('secure');
  1842. }
  1843. document.cookie = cookie.join('; ');
  1844. },
  1845. read: function read(name) {
  1846. var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
  1847. return (match ? decodeURIComponent(match[3]) : null);
  1848. },
  1849. remove: function remove(name) {
  1850. this.write(name, '', Date.now() - 86400000);
  1851. }
  1852. };
  1853. })() :
  1854. // Non standard browser env (web workers, react-native) lack needed support.
  1855. (function nonStandardBrowserEnv() {
  1856. return {
  1857. write: function write() {},
  1858. read: function read() { return null; },
  1859. remove: function remove() {}
  1860. };
  1861. })()
  1862. );
  1863. /***/ }),
  1864. /***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js":
  1865. /*!*********************************************************!*\
  1866. !*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***!
  1867. \*********************************************************/
  1868. /***/ ((module) => {
  1869. "use strict";
  1870. /**
  1871. * Determines whether the specified URL is absolute
  1872. *
  1873. * @param {string} url The URL to test
  1874. * @returns {boolean} True if the specified URL is absolute, otherwise false
  1875. */
  1876. module.exports = function isAbsoluteURL(url) {
  1877. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  1878. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  1879. // by any combination of letters, digits, plus, period, or hyphen.
  1880. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
  1881. };
  1882. /***/ }),
  1883. /***/ "./node_modules/axios/lib/helpers/isAxiosError.js":
  1884. /*!********************************************************!*\
  1885. !*** ./node_modules/axios/lib/helpers/isAxiosError.js ***!
  1886. \********************************************************/
  1887. /***/ ((module) => {
  1888. "use strict";
  1889. /**
  1890. * Determines whether the payload is an error thrown by Axios
  1891. *
  1892. * @param {*} payload The value to test
  1893. * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
  1894. */
  1895. module.exports = function isAxiosError(payload) {
  1896. return (typeof payload === 'object') && (payload.isAxiosError === true);
  1897. };
  1898. /***/ }),
  1899. /***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js":
  1900. /*!***********************************************************!*\
  1901. !*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***!
  1902. \***********************************************************/
  1903. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1904. "use strict";
  1905. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1906. module.exports = (
  1907. utils.isStandardBrowserEnv() ?
  1908. // Standard browser envs have full support of the APIs needed to test
  1909. // whether the request URL is of the same origin as current location.
  1910. (function standardBrowserEnv() {
  1911. var msie = /(msie|trident)/i.test(navigator.userAgent);
  1912. var urlParsingNode = document.createElement('a');
  1913. var originURL;
  1914. /**
  1915. * Parse a URL to discover it's components
  1916. *
  1917. * @param {String} url The URL to be parsed
  1918. * @returns {Object}
  1919. */
  1920. function resolveURL(url) {
  1921. var href = url;
  1922. if (msie) {
  1923. // IE needs attribute set twice to normalize properties
  1924. urlParsingNode.setAttribute('href', href);
  1925. href = urlParsingNode.href;
  1926. }
  1927. urlParsingNode.setAttribute('href', href);
  1928. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  1929. return {
  1930. href: urlParsingNode.href,
  1931. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  1932. host: urlParsingNode.host,
  1933. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  1934. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  1935. hostname: urlParsingNode.hostname,
  1936. port: urlParsingNode.port,
  1937. pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
  1938. urlParsingNode.pathname :
  1939. '/' + urlParsingNode.pathname
  1940. };
  1941. }
  1942. originURL = resolveURL(window.location.href);
  1943. /**
  1944. * Determine if a URL shares the same origin as the current location
  1945. *
  1946. * @param {String} requestURL The URL to test
  1947. * @returns {boolean} True if URL shares the same origin, otherwise false
  1948. */
  1949. return function isURLSameOrigin(requestURL) {
  1950. var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
  1951. return (parsed.protocol === originURL.protocol &&
  1952. parsed.host === originURL.host);
  1953. };
  1954. })() :
  1955. // Non standard browser envs (web workers, react-native) lack needed support.
  1956. (function nonStandardBrowserEnv() {
  1957. return function isURLSameOrigin() {
  1958. return true;
  1959. };
  1960. })()
  1961. );
  1962. /***/ }),
  1963. /***/ "./node_modules/axios/lib/helpers/normalizeHeaderName.js":
  1964. /*!***************************************************************!*\
  1965. !*** ./node_modules/axios/lib/helpers/normalizeHeaderName.js ***!
  1966. \***************************************************************/
  1967. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1968. "use strict";
  1969. var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js");
  1970. module.exports = function normalizeHeaderName(headers, normalizedName) {
  1971. utils.forEach(headers, function processHeader(value, name) {
  1972. if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
  1973. headers[normalizedName] = value;
  1974. delete headers[name];
  1975. }
  1976. });
  1977. };
  1978. /***/ }),
  1979. /***/ "./node_modules/axios/lib/helpers/parseHeaders.js":
  1980. /*!********************************************************!*\
  1981. !*** ./node_modules/axios/lib/helpers/parseHeaders.js ***!
  1982. \********************************************************/
  1983. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1984. "use strict";
  1985. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1986. // Headers whose duplicates are ignored by node
  1987. // c.f. https://nodejs.org/api/http.html#http_message_headers
  1988. var ignoreDuplicateOf = [
  1989. 'age', 'authorization', 'content-length', 'content-type', 'etag',
  1990. 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  1991. 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  1992. 'referer', 'retry-after', 'user-agent'
  1993. ];
  1994. /**
  1995. * Parse headers into an object
  1996. *
  1997. * ```
  1998. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  1999. * Content-Type: application/json
  2000. * Connection: keep-alive
  2001. * Transfer-Encoding: chunked
  2002. * ```
  2003. *
  2004. * @param {String} headers Headers needing to be parsed
  2005. * @returns {Object} Headers parsed into an object
  2006. */
  2007. module.exports = function parseHeaders(headers) {
  2008. var parsed = {};
  2009. var key;
  2010. var val;
  2011. var i;
  2012. if (!headers) { return parsed; }
  2013. utils.forEach(headers.split('\n'), function parser(line) {
  2014. i = line.indexOf(':');
  2015. key = utils.trim(line.substr(0, i)).toLowerCase();
  2016. val = utils.trim(line.substr(i + 1));
  2017. if (key) {
  2018. if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
  2019. return;
  2020. }
  2021. if (key === 'set-cookie') {
  2022. parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
  2023. } else {
  2024. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  2025. }
  2026. }
  2027. });
  2028. return parsed;
  2029. };
  2030. /***/ }),
  2031. /***/ "./node_modules/axios/lib/helpers/spread.js":
  2032. /*!**************************************************!*\
  2033. !*** ./node_modules/axios/lib/helpers/spread.js ***!
  2034. \**************************************************/
  2035. /***/ ((module) => {
  2036. "use strict";
  2037. /**
  2038. * Syntactic sugar for invoking a function and expanding an array for arguments.
  2039. *
  2040. * Common use case would be to use `Function.prototype.apply`.
  2041. *
  2042. * ```js
  2043. * function f(x, y, z) {}
  2044. * var args = [1, 2, 3];
  2045. * f.apply(null, args);
  2046. * ```
  2047. *
  2048. * With `spread` this example can be re-written.
  2049. *
  2050. * ```js
  2051. * spread(function(x, y, z) {})([1, 2, 3]);
  2052. * ```
  2053. *
  2054. * @param {Function} callback
  2055. * @returns {Function}
  2056. */
  2057. module.exports = function spread(callback) {
  2058. return function wrap(arr) {
  2059. return callback.apply(null, arr);
  2060. };
  2061. };
  2062. /***/ }),
  2063. /***/ "./node_modules/axios/lib/utils.js":
  2064. /*!*****************************************!*\
  2065. !*** ./node_modules/axios/lib/utils.js ***!
  2066. \*****************************************/
  2067. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  2068. "use strict";
  2069. var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js");
  2070. /*global toString:true*/
  2071. // utils is a library of generic helper functions non-specific to axios
  2072. var toString = Object.prototype.toString;
  2073. /**
  2074. * Determine if a value is an Array
  2075. *
  2076. * @param {Object} val The value to test
  2077. * @returns {boolean} True if value is an Array, otherwise false
  2078. */
  2079. function isArray(val) {
  2080. return toString.call(val) === '[object Array]';
  2081. }
  2082. /**
  2083. * Determine if a value is undefined
  2084. *
  2085. * @param {Object} val The value to test
  2086. * @returns {boolean} True if the value is undefined, otherwise false
  2087. */
  2088. function isUndefined(val) {
  2089. return typeof val === 'undefined';
  2090. }
  2091. /**
  2092. * Determine if a value is a Buffer
  2093. *
  2094. * @param {Object} val The value to test
  2095. * @returns {boolean} True if value is a Buffer, otherwise false
  2096. */
  2097. function isBuffer(val) {
  2098. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
  2099. && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
  2100. }
  2101. /**
  2102. * Determine if a value is an ArrayBuffer
  2103. *
  2104. * @param {Object} val The value to test
  2105. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  2106. */
  2107. function isArrayBuffer(val) {
  2108. return toString.call(val) === '[object ArrayBuffer]';
  2109. }
  2110. /**
  2111. * Determine if a value is a FormData
  2112. *
  2113. * @param {Object} val The value to test
  2114. * @returns {boolean} True if value is an FormData, otherwise false
  2115. */
  2116. function isFormData(val) {
  2117. return (typeof FormData !== 'undefined') && (val instanceof FormData);
  2118. }
  2119. /**
  2120. * Determine if a value is a view on an ArrayBuffer
  2121. *
  2122. * @param {Object} val The value to test
  2123. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  2124. */
  2125. function isArrayBufferView(val) {
  2126. var result;
  2127. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  2128. result = ArrayBuffer.isView(val);
  2129. } else {
  2130. result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
  2131. }
  2132. return result;
  2133. }
  2134. /**
  2135. * Determine if a value is a String
  2136. *
  2137. * @param {Object} val The value to test
  2138. * @returns {boolean} True if value is a String, otherwise false
  2139. */
  2140. function isString(val) {
  2141. return typeof val === 'string';
  2142. }
  2143. /**
  2144. * Determine if a value is a Number
  2145. *
  2146. * @param {Object} val The value to test
  2147. * @returns {boolean} True if value is a Number, otherwise false
  2148. */
  2149. function isNumber(val) {
  2150. return typeof val === 'number';
  2151. }
  2152. /**
  2153. * Determine if a value is an Object
  2154. *
  2155. * @param {Object} val The value to test
  2156. * @returns {boolean} True if value is an Object, otherwise false
  2157. */
  2158. function isObject(val) {
  2159. return val !== null && typeof val === 'object';
  2160. }
  2161. /**
  2162. * Determine if a value is a plain Object
  2163. *
  2164. * @param {Object} val The value to test
  2165. * @return {boolean} True if value is a plain Object, otherwise false
  2166. */
  2167. function isPlainObject(val) {
  2168. if (toString.call(val) !== '[object Object]') {
  2169. return false;
  2170. }
  2171. var prototype = Object.getPrototypeOf(val);
  2172. return prototype === null || prototype === Object.prototype;
  2173. }
  2174. /**
  2175. * Determine if a value is a Date
  2176. *
  2177. * @param {Object} val The value to test
  2178. * @returns {boolean} True if value is a Date, otherwise false
  2179. */
  2180. function isDate(val) {
  2181. return toString.call(val) === '[object Date]';
  2182. }
  2183. /**
  2184. * Determine if a value is a File
  2185. *
  2186. * @param {Object} val The value to test
  2187. * @returns {boolean} True if value is a File, otherwise false
  2188. */
  2189. function isFile(val) {
  2190. return toString.call(val) === '[object File]';
  2191. }
  2192. /**
  2193. * Determine if a value is a Blob
  2194. *
  2195. * @param {Object} val The value to test
  2196. * @returns {boolean} True if value is a Blob, otherwise false
  2197. */
  2198. function isBlob(val) {
  2199. return toString.call(val) === '[object Blob]';
  2200. }
  2201. /**
  2202. * Determine if a value is a Function
  2203. *
  2204. * @param {Object} val The value to test
  2205. * @returns {boolean} True if value is a Function, otherwise false
  2206. */
  2207. function isFunction(val) {
  2208. return toString.call(val) === '[object Function]';
  2209. }
  2210. /**
  2211. * Determine if a value is a Stream
  2212. *
  2213. * @param {Object} val The value to test
  2214. * @returns {boolean} True if value is a Stream, otherwise false
  2215. */
  2216. function isStream(val) {
  2217. return isObject(val) && isFunction(val.pipe);
  2218. }
  2219. /**
  2220. * Determine if a value is a URLSearchParams object
  2221. *
  2222. * @param {Object} val The value to test
  2223. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  2224. */
  2225. function isURLSearchParams(val) {
  2226. return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
  2227. }
  2228. /**
  2229. * Trim excess whitespace off the beginning and end of a string
  2230. *
  2231. * @param {String} str The String to trim
  2232. * @returns {String} The String freed of excess whitespace
  2233. */
  2234. function trim(str) {
  2235. return str.replace(/^\s*/, '').replace(/\s*$/, '');
  2236. }
  2237. /**
  2238. * Determine if we're running in a standard browser environment
  2239. *
  2240. * This allows axios to run in a web worker, and react-native.
  2241. * Both environments support XMLHttpRequest, but not fully standard globals.
  2242. *
  2243. * web workers:
  2244. * typeof window -> undefined
  2245. * typeof document -> undefined
  2246. *
  2247. * react-native:
  2248. * navigator.product -> 'ReactNative'
  2249. * nativescript
  2250. * navigator.product -> 'NativeScript' or 'NS'
  2251. */
  2252. function isStandardBrowserEnv() {
  2253. if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
  2254. navigator.product === 'NativeScript' ||
  2255. navigator.product === 'NS')) {
  2256. return false;
  2257. }
  2258. return (
  2259. typeof window !== 'undefined' &&
  2260. typeof document !== 'undefined'
  2261. );
  2262. }
  2263. /**
  2264. * Iterate over an Array or an Object invoking a function for each item.
  2265. *
  2266. * If `obj` is an Array callback will be called passing
  2267. * the value, index, and complete array for each item.
  2268. *
  2269. * If 'obj' is an Object callback will be called passing
  2270. * the value, key, and complete object for each property.
  2271. *
  2272. * @param {Object|Array} obj The object to iterate
  2273. * @param {Function} fn The callback to invoke for each item
  2274. */
  2275. function forEach(obj, fn) {
  2276. // Don't bother if no value provided
  2277. if (obj === null || typeof obj === 'undefined') {
  2278. return;
  2279. }
  2280. // Force an array if not already something iterable
  2281. if (typeof obj !== 'object') {
  2282. /*eslint no-param-reassign:0*/
  2283. obj = [obj];
  2284. }
  2285. if (isArray(obj)) {
  2286. // Iterate over array values
  2287. for (var i = 0, l = obj.length; i < l; i++) {
  2288. fn.call(null, obj[i], i, obj);
  2289. }
  2290. } else {
  2291. // Iterate over object keys
  2292. for (var key in obj) {
  2293. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  2294. fn.call(null, obj[key], key, obj);
  2295. }
  2296. }
  2297. }
  2298. }
  2299. /**
  2300. * Accepts varargs expecting each argument to be an object, then
  2301. * immutably merges the properties of each object and returns result.
  2302. *
  2303. * When multiple objects contain the same key the later object in
  2304. * the arguments list will take precedence.
  2305. *
  2306. * Example:
  2307. *
  2308. * ```js
  2309. * var result = merge({foo: 123}, {foo: 456});
  2310. * console.log(result.foo); // outputs 456
  2311. * ```
  2312. *
  2313. * @param {Object} obj1 Object to merge
  2314. * @returns {Object} Result of all merge properties
  2315. */
  2316. function merge(/* obj1, obj2, obj3, ... */) {
  2317. var result = {};
  2318. function assignValue(val, key) {
  2319. if (isPlainObject(result[key]) && isPlainObject(val)) {
  2320. result[key] = merge(result[key], val);
  2321. } else if (isPlainObject(val)) {
  2322. result[key] = merge({}, val);
  2323. } else if (isArray(val)) {
  2324. result[key] = val.slice();
  2325. } else {
  2326. result[key] = val;
  2327. }
  2328. }
  2329. for (var i = 0, l = arguments.length; i < l; i++) {
  2330. forEach(arguments[i], assignValue);
  2331. }
  2332. return result;
  2333. }
  2334. /**
  2335. * Extends object a by mutably adding to it the properties of object b.
  2336. *
  2337. * @param {Object} a The object to be extended
  2338. * @param {Object} b The object to copy properties from
  2339. * @param {Object} thisArg The object to bind function to
  2340. * @return {Object} The resulting value of object a
  2341. */
  2342. function extend(a, b, thisArg) {
  2343. forEach(b, function assignValue(val, key) {
  2344. if (thisArg && typeof val === 'function') {
  2345. a[key] = bind(val, thisArg);
  2346. } else {
  2347. a[key] = val;
  2348. }
  2349. });
  2350. return a;
  2351. }
  2352. /**
  2353. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  2354. *
  2355. * @param {string} content with BOM
  2356. * @return {string} content value without BOM
  2357. */
  2358. function stripBOM(content) {
  2359. if (content.charCodeAt(0) === 0xFEFF) {
  2360. content = content.slice(1);
  2361. }
  2362. return content;
  2363. }
  2364. module.exports = {
  2365. isArray: isArray,
  2366. isArrayBuffer: isArrayBuffer,
  2367. isBuffer: isBuffer,
  2368. isFormData: isFormData,
  2369. isArrayBufferView: isArrayBufferView,
  2370. isString: isString,
  2371. isNumber: isNumber,
  2372. isObject: isObject,
  2373. isPlainObject: isPlainObject,
  2374. isUndefined: isUndefined,
  2375. isDate: isDate,
  2376. isFile: isFile,
  2377. isBlob: isBlob,
  2378. isFunction: isFunction,
  2379. isStream: isStream,
  2380. isURLSearchParams: isURLSearchParams,
  2381. isStandardBrowserEnv: isStandardBrowserEnv,
  2382. forEach: forEach,
  2383. merge: merge,
  2384. extend: extend,
  2385. trim: trim,
  2386. stripBOM: stripBOM
  2387. };
  2388. /***/ }),
  2389. /***/ "./resources/js/FormValidator.js":
  2390. /*!***************************************!*\
  2391. !*** ./resources/js/FormValidator.js ***!
  2392. \***************************************/
  2393. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  2394. "use strict";
  2395. __webpack_require__.r(__webpack_exports__);
  2396. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2397. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  2398. /* harmony export */ });
  2399. /* harmony import */ var validate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! validate.js */ "./node_modules/validate.js/validate.js");
  2400. /* harmony import */ var validate_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(validate_js__WEBPACK_IMPORTED_MODULE_0__);
  2401. /* harmony import */ var form_serialize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! form-serialize */ "./node_modules/form-serialize/index.js");
  2402. /* harmony import */ var form_serialize__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(form_serialize__WEBPACK_IMPORTED_MODULE_1__);
  2403. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2404. 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); } }
  2405. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  2406. /**
  2407. * Form Validator with RiotJS Components
  2408. *
  2409. *
  2410. *
  2411. *
  2412. */
  2413. var FormValidator = /*#__PURE__*/function () {
  2414. /**
  2415. *
  2416. * @param {[type]} formSelector [description]
  2417. * @param {[type]} constraits [description]
  2418. */
  2419. function FormValidator(formSelector, constraits, onSuccess) {
  2420. var _this = this;
  2421. _classCallCheck(this, FormValidator);
  2422. // getting selector to find form-element
  2423. this.formSelector = formSelector; // constraits for validate.js
  2424. this.constraits = constraits; // get form and elements
  2425. this.form = document.querySelector(this.formSelector);
  2426. if (!this.form) {
  2427. console.error('FormValidator: form not found, querySelector not found "' + this.formSelector + '"');
  2428. }
  2429. this.elements = this.form.querySelectorAll('field-error'); // adding submit event
  2430. this.form.addEventListener('submit', function (event) {
  2431. _this.onSubmit(event);
  2432. }); // adding event if a element is updated
  2433. this.form.addEventListener('field-update', function (event) {
  2434. _this.onFieldUpdate(event);
  2435. });
  2436. this.onSuccess = onSuccess;
  2437. }
  2438. /**
  2439. *
  2440. *
  2441. */
  2442. _createClass(FormValidator, [{
  2443. key: "setConstraits",
  2444. value: function setConstraits(constraits) {
  2445. this.constraits = constraits;
  2446. }
  2447. /**
  2448. *
  2449. *
  2450. */
  2451. }, {
  2452. key: "getConstraits",
  2453. value: function getConstraits(constraits) {
  2454. return this.constraits;
  2455. }
  2456. /**
  2457. *
  2458. * @param {[type]} event [description]
  2459. * @return {[type]} [description]
  2460. */
  2461. }, {
  2462. key: "onSubmit",
  2463. value: function onSubmit(event) {
  2464. var _this2 = this;
  2465. event.preventDefault();
  2466. var errors = validate_js__WEBPACK_IMPORTED_MODULE_0___default()(form_serialize__WEBPACK_IMPORTED_MODULE_1___default()(event.target, {
  2467. hash: true
  2468. }), this.constraits, {
  2469. fullMessages: false
  2470. });
  2471. if (errors) {
  2472. // send each element a event
  2473. this.elements.forEach(function (element) {
  2474. var elementErrors = false; // check for errors by name
  2475. if (errors[element.attributes.name.nodeValue]) {
  2476. elementErrors = errors[element.attributes.name.nodeValue];
  2477. }
  2478. _this2.dispatchCustomEvent(elementErrors, element);
  2479. });
  2480. } else {
  2481. this.onSuccess(event, form_serialize__WEBPACK_IMPORTED_MODULE_1___default()(event.target, {
  2482. hash: true
  2483. }));
  2484. }
  2485. }
  2486. /**
  2487. *
  2488. *
  2489. * @param {Event} event
  2490. *
  2491. */
  2492. }, {
  2493. key: "onFieldUpdate",
  2494. value: function onFieldUpdate(event) {
  2495. var _this3 = this;
  2496. // workaround, make sure that value for single is undefined if it is empty
  2497. if (event.detail.value == '') {
  2498. event.detail.value = undefined;
  2499. }
  2500. 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
  2501. this.elements.forEach(function (element) {
  2502. if (element.attributes.name.nodeValue == event.detail.name) {
  2503. _this3.dispatchCustomEvent(errors, element);
  2504. }
  2505. });
  2506. }
  2507. /**
  2508. * dispatch event to single element
  2509. *
  2510. * @param {Array} errors
  2511. * @param {Element} element
  2512. *
  2513. */
  2514. }, {
  2515. key: "dispatchCustomEvent",
  2516. value: function dispatchCustomEvent(errors, element) {
  2517. var detail = false;
  2518. if (errors) {
  2519. detail = errors;
  2520. }
  2521. var formValidationEvent = new CustomEvent('form-validation', {
  2522. 'detail': detail
  2523. });
  2524. element.dispatchEvent(formValidationEvent);
  2525. }
  2526. }]);
  2527. return FormValidator;
  2528. }();
  2529. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (FormValidator);
  2530. /***/ }),
  2531. /***/ "./node_modules/form-serialize/index.js":
  2532. /*!**********************************************!*\
  2533. !*** ./node_modules/form-serialize/index.js ***!
  2534. \**********************************************/
  2535. /***/ ((module) => {
  2536. // get successful control from form and assemble into object
  2537. // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
  2538. // types which indicate a submit action and are not successful controls
  2539. // these will be ignored
  2540. var k_r_submitter = /^(?:submit|button|image|reset|file)$/i;
  2541. // node names which could be successful controls
  2542. var k_r_success_contrls = /^(?:input|select|textarea|keygen)/i;
  2543. // Matches bracket notation.
  2544. var brackets = /(\[[^\[\]]*\])/g;
  2545. // serializes form fields
  2546. // @param form MUST be an HTMLForm element
  2547. // @param options is an optional argument to configure the serialization. Default output
  2548. // with no options specified is a url encoded string
  2549. // - hash: [true | false] Configure the output type. If true, the output will
  2550. // be a js object.
  2551. // - serializer: [function] Optional serializer function to override the default one.
  2552. // The function takes 3 arguments (result, key, value) and should return new result
  2553. // hash and url encoded str serializers are provided with this module
  2554. // - disabled: [true | false]. If true serialize disabled fields.
  2555. // - empty: [true | false]. If true serialize empty fields
  2556. function serialize(form, options) {
  2557. if (typeof options != 'object') {
  2558. options = { hash: !!options };
  2559. }
  2560. else if (options.hash === undefined) {
  2561. options.hash = true;
  2562. }
  2563. var result = (options.hash) ? {} : '';
  2564. var serializer = options.serializer || ((options.hash) ? hash_serializer : str_serialize);
  2565. var elements = form && form.elements ? form.elements : [];
  2566. //Object store each radio and set if it's empty or not
  2567. var radio_store = Object.create(null);
  2568. for (var i=0 ; i<elements.length ; ++i) {
  2569. var element = elements[i];
  2570. // ingore disabled fields
  2571. if ((!options.disabled && element.disabled) || !element.name) {
  2572. continue;
  2573. }
  2574. // ignore anyhting that is not considered a success field
  2575. if (!k_r_success_contrls.test(element.nodeName) ||
  2576. k_r_submitter.test(element.type)) {
  2577. continue;
  2578. }
  2579. var key = element.name;
  2580. var val = element.value;
  2581. // we can't just use element.value for checkboxes cause some browsers lie to us
  2582. // they say "on" for value when the box isn't checked
  2583. if ((element.type === 'checkbox' || element.type === 'radio') && !element.checked) {
  2584. val = undefined;
  2585. }
  2586. // If we want empty elements
  2587. if (options.empty) {
  2588. // for checkbox
  2589. if (element.type === 'checkbox' && !element.checked) {
  2590. val = '';
  2591. }
  2592. // for radio
  2593. if (element.type === 'radio') {
  2594. if (!radio_store[element.name] && !element.checked) {
  2595. radio_store[element.name] = false;
  2596. }
  2597. else if (element.checked) {
  2598. radio_store[element.name] = true;
  2599. }
  2600. }
  2601. // if options empty is true, continue only if its radio
  2602. if (val == undefined && element.type == 'radio') {
  2603. continue;
  2604. }
  2605. }
  2606. else {
  2607. // value-less fields are ignored unless options.empty is true
  2608. if (!val) {
  2609. continue;
  2610. }
  2611. }
  2612. // multi select boxes
  2613. if (element.type === 'select-multiple') {
  2614. val = [];
  2615. var selectOptions = element.options;
  2616. var isSelectedOptions = false;
  2617. for (var j=0 ; j<selectOptions.length ; ++j) {
  2618. var option = selectOptions[j];
  2619. var allowedEmpty = options.empty && !option.value;
  2620. var hasValue = (option.value || allowedEmpty);
  2621. if (option.selected && hasValue) {
  2622. isSelectedOptions = true;
  2623. // If using a hash serializer be sure to add the
  2624. // correct notation for an array in the multi-select
  2625. // context. Here the name attribute on the select element
  2626. // might be missing the trailing bracket pair. Both names
  2627. // "foo" and "foo[]" should be arrays.
  2628. if (options.hash && key.slice(key.length - 2) !== '[]') {
  2629. result = serializer(result, key + '[]', option.value);
  2630. }
  2631. else {
  2632. result = serializer(result, key, option.value);
  2633. }
  2634. }
  2635. }
  2636. // Serialize if no selected options and options.empty is true
  2637. if (!isSelectedOptions && options.empty) {
  2638. result = serializer(result, key, '');
  2639. }
  2640. continue;
  2641. }
  2642. result = serializer(result, key, val);
  2643. }
  2644. // Check for all empty radio buttons and serialize them with key=""
  2645. if (options.empty) {
  2646. for (var key in radio_store) {
  2647. if (!radio_store[key]) {
  2648. result = serializer(result, key, '');
  2649. }
  2650. }
  2651. }
  2652. return result;
  2653. }
  2654. function parse_keys(string) {
  2655. var keys = [];
  2656. var prefix = /^([^\[\]]*)/;
  2657. var children = new RegExp(brackets);
  2658. var match = prefix.exec(string);
  2659. if (match[1]) {
  2660. keys.push(match[1]);
  2661. }
  2662. while ((match = children.exec(string)) !== null) {
  2663. keys.push(match[1]);
  2664. }
  2665. return keys;
  2666. }
  2667. function hash_assign(result, keys, value) {
  2668. if (keys.length === 0) {
  2669. result = value;
  2670. return result;
  2671. }
  2672. var key = keys.shift();
  2673. var between = key.match(/^\[(.+?)\]$/);
  2674. if (key === '[]') {
  2675. result = result || [];
  2676. if (Array.isArray(result)) {
  2677. result.push(hash_assign(null, keys, value));
  2678. }
  2679. else {
  2680. // This might be the result of bad name attributes like "[][foo]",
  2681. // in this case the original `result` object will already be
  2682. // assigned to an object literal. Rather than coerce the object to
  2683. // an array, or cause an exception the attribute "_values" is
  2684. // assigned as an array.
  2685. result._values = result._values || [];
  2686. result._values.push(hash_assign(null, keys, value));
  2687. }
  2688. return result;
  2689. }
  2690. // Key is an attribute name and can be assigned directly.
  2691. if (!between) {
  2692. result[key] = hash_assign(result[key], keys, value);
  2693. }
  2694. else {
  2695. var string = between[1];
  2696. // +var converts the variable into a number
  2697. // better than parseInt because it doesn't truncate away trailing
  2698. // letters and actually fails if whole thing is not a number
  2699. var index = +string;
  2700. // If the characters between the brackets is not a number it is an
  2701. // attribute name and can be assigned directly.
  2702. if (isNaN(index)) {
  2703. result = result || {};
  2704. result[string] = hash_assign(result[string], keys, value);
  2705. }
  2706. else {
  2707. result = result || [];
  2708. result[index] = hash_assign(result[index], keys, value);
  2709. }
  2710. }
  2711. return result;
  2712. }
  2713. // Object/hash encoding serializer.
  2714. function hash_serializer(result, key, value) {
  2715. var matches = key.match(brackets);
  2716. // Has brackets? Use the recursive assignment function to walk the keys,
  2717. // construct any missing objects in the result tree and make the assignment
  2718. // at the end of the chain.
  2719. if (matches) {
  2720. var keys = parse_keys(key);
  2721. hash_assign(result, keys, value);
  2722. }
  2723. else {
  2724. // Non bracket notation can make assignments directly.
  2725. var existing = result[key];
  2726. // If the value has been assigned already (for instance when a radio and
  2727. // a checkbox have the same name attribute) convert the previous value
  2728. // into an array before pushing into it.
  2729. //
  2730. // NOTE: If this requirement were removed all hash creation and
  2731. // assignment could go through `hash_assign`.
  2732. if (existing) {
  2733. if (!Array.isArray(existing)) {
  2734. result[key] = [ existing ];
  2735. }
  2736. result[key].push(value);
  2737. }
  2738. else {
  2739. result[key] = value;
  2740. }
  2741. }
  2742. return result;
  2743. }
  2744. // urlform encoding serializer
  2745. function str_serialize(result, key, value) {
  2746. // encode newlines as \r\n cause the html spec says so
  2747. value = value.replace(/(\r)?\n/g, '\r\n');
  2748. value = encodeURIComponent(value);
  2749. // spaces should be '+' rather than '%20'.
  2750. value = value.replace(/%20/g, '+');
  2751. return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + value;
  2752. }
  2753. module.exports = serialize;
  2754. /***/ }),
  2755. /***/ "./node_modules/lodash.remove/index.js":
  2756. /*!*********************************************!*\
  2757. !*** ./node_modules/lodash.remove/index.js ***!
  2758. \*********************************************/
  2759. /***/ ((module, exports, __webpack_require__) => {
  2760. /* module decorator */ module = __webpack_require__.nmd(module);
  2761. /**
  2762. * lodash (Custom Build) <https://lodash.com/>
  2763. * Build: `lodash modularize exports="npm" -o ./`
  2764. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  2765. * Released under MIT license <https://lodash.com/license>
  2766. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  2767. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  2768. */
  2769. /** Used as the size to enable large array optimizations. */
  2770. var LARGE_ARRAY_SIZE = 200;
  2771. /** Used as the `TypeError` message for "Functions" methods. */
  2772. var FUNC_ERROR_TEXT = 'Expected a function';
  2773. /** Used to stand-in for `undefined` hash values. */
  2774. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  2775. /** Used to compose bitmasks for comparison styles. */
  2776. var UNORDERED_COMPARE_FLAG = 1,
  2777. PARTIAL_COMPARE_FLAG = 2;
  2778. /** Used as references for various `Number` constants. */
  2779. var INFINITY = 1 / 0,
  2780. MAX_SAFE_INTEGER = 9007199254740991;
  2781. /** `Object#toString` result references. */
  2782. var argsTag = '[object Arguments]',
  2783. arrayTag = '[object Array]',
  2784. boolTag = '[object Boolean]',
  2785. dateTag = '[object Date]',
  2786. errorTag = '[object Error]',
  2787. funcTag = '[object Function]',
  2788. genTag = '[object GeneratorFunction]',
  2789. mapTag = '[object Map]',
  2790. numberTag = '[object Number]',
  2791. objectTag = '[object Object]',
  2792. promiseTag = '[object Promise]',
  2793. regexpTag = '[object RegExp]',
  2794. setTag = '[object Set]',
  2795. stringTag = '[object String]',
  2796. symbolTag = '[object Symbol]',
  2797. weakMapTag = '[object WeakMap]';
  2798. var arrayBufferTag = '[object ArrayBuffer]',
  2799. dataViewTag = '[object DataView]',
  2800. float32Tag = '[object Float32Array]',
  2801. float64Tag = '[object Float64Array]',
  2802. int8Tag = '[object Int8Array]',
  2803. int16Tag = '[object Int16Array]',
  2804. int32Tag = '[object Int32Array]',
  2805. uint8Tag = '[object Uint8Array]',
  2806. uint8ClampedTag = '[object Uint8ClampedArray]',
  2807. uint16Tag = '[object Uint16Array]',
  2808. uint32Tag = '[object Uint32Array]';
  2809. /** Used to match property names within property paths. */
  2810. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  2811. reIsPlainProp = /^\w*$/,
  2812. reLeadingDot = /^\./,
  2813. rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  2814. /**
  2815. * Used to match `RegExp`
  2816. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  2817. */
  2818. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  2819. /** Used to match backslashes in property paths. */
  2820. var reEscapeChar = /\\(\\)?/g;
  2821. /** Used to detect host constructors (Safari). */
  2822. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  2823. /** Used to detect unsigned integer values. */
  2824. var reIsUint = /^(?:0|[1-9]\d*)$/;
  2825. /** Used to identify `toStringTag` values of typed arrays. */
  2826. var typedArrayTags = {};
  2827. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  2828. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  2829. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  2830. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  2831. typedArrayTags[uint32Tag] = true;
  2832. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  2833. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  2834. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  2835. typedArrayTags[errorTag] = typedArrayTags[funcTag] =
  2836. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  2837. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  2838. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  2839. typedArrayTags[weakMapTag] = false;
  2840. /** Detect free variable `global` from Node.js. */
  2841. var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g;
  2842. /** Detect free variable `self`. */
  2843. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  2844. /** Used as a reference to the global object. */
  2845. var root = freeGlobal || freeSelf || Function('return this')();
  2846. /** Detect free variable `exports`. */
  2847. var freeExports = true && exports && !exports.nodeType && exports;
  2848. /** Detect free variable `module`. */
  2849. var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module;
  2850. /** Detect the popular CommonJS extension `module.exports`. */
  2851. var moduleExports = freeModule && freeModule.exports === freeExports;
  2852. /** Detect free variable `process` from Node.js. */
  2853. var freeProcess = moduleExports && freeGlobal.process;
  2854. /** Used to access faster Node.js helpers. */
  2855. var nodeUtil = (function() {
  2856. try {
  2857. return freeProcess && freeProcess.binding('util');
  2858. } catch (e) {}
  2859. }());
  2860. /* Node.js helper references. */
  2861. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  2862. /**
  2863. * A specialized version of `_.some` for arrays without support for iteratee
  2864. * shorthands.
  2865. *
  2866. * @private
  2867. * @param {Array} [array] The array to iterate over.
  2868. * @param {Function} predicate The function invoked per iteration.
  2869. * @returns {boolean} Returns `true` if any element passes the predicate check,
  2870. * else `false`.
  2871. */
  2872. function arraySome(array, predicate) {
  2873. var index = -1,
  2874. length = array ? array.length : 0;
  2875. while (++index < length) {
  2876. if (predicate(array[index], index, array)) {
  2877. return true;
  2878. }
  2879. }
  2880. return false;
  2881. }
  2882. /**
  2883. * The base implementation of `_.property` without support for deep paths.
  2884. *
  2885. * @private
  2886. * @param {string} key The key of the property to get.
  2887. * @returns {Function} Returns the new accessor function.
  2888. */
  2889. function baseProperty(key) {
  2890. return function(object) {
  2891. return object == null ? undefined : object[key];
  2892. };
  2893. }
  2894. /**
  2895. * The base implementation of `_.times` without support for iteratee shorthands
  2896. * or max array length checks.
  2897. *
  2898. * @private
  2899. * @param {number} n The number of times to invoke `iteratee`.
  2900. * @param {Function} iteratee The function invoked per iteration.
  2901. * @returns {Array} Returns the array of results.
  2902. */
  2903. function baseTimes(n, iteratee) {
  2904. var index = -1,
  2905. result = Array(n);
  2906. while (++index < n) {
  2907. result[index] = iteratee(index);
  2908. }
  2909. return result;
  2910. }
  2911. /**
  2912. * The base implementation of `_.unary` without support for storing metadata.
  2913. *
  2914. * @private
  2915. * @param {Function} func The function to cap arguments for.
  2916. * @returns {Function} Returns the new capped function.
  2917. */
  2918. function baseUnary(func) {
  2919. return function(value) {
  2920. return func(value);
  2921. };
  2922. }
  2923. /**
  2924. * Gets the value at `key` of `object`.
  2925. *
  2926. * @private
  2927. * @param {Object} [object] The object to query.
  2928. * @param {string} key The key of the property to get.
  2929. * @returns {*} Returns the property value.
  2930. */
  2931. function getValue(object, key) {
  2932. return object == null ? undefined : object[key];
  2933. }
  2934. /**
  2935. * Checks if `value` is a host object in IE < 9.
  2936. *
  2937. * @private
  2938. * @param {*} value The value to check.
  2939. * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
  2940. */
  2941. function isHostObject(value) {
  2942. // Many host objects are `Object` objects that can coerce to strings
  2943. // despite having improperly defined `toString` methods.
  2944. var result = false;
  2945. if (value != null && typeof value.toString != 'function') {
  2946. try {
  2947. result = !!(value + '');
  2948. } catch (e) {}
  2949. }
  2950. return result;
  2951. }
  2952. /**
  2953. * Converts `map` to its key-value pairs.
  2954. *
  2955. * @private
  2956. * @param {Object} map The map to convert.
  2957. * @returns {Array} Returns the key-value pairs.
  2958. */
  2959. function mapToArray(map) {
  2960. var index = -1,
  2961. result = Array(map.size);
  2962. map.forEach(function(value, key) {
  2963. result[++index] = [key, value];
  2964. });
  2965. return result;
  2966. }
  2967. /**
  2968. * Creates a unary function that invokes `func` with its argument transformed.
  2969. *
  2970. * @private
  2971. * @param {Function} func The function to wrap.
  2972. * @param {Function} transform The argument transform.
  2973. * @returns {Function} Returns the new function.
  2974. */
  2975. function overArg(func, transform) {
  2976. return function(arg) {
  2977. return func(transform(arg));
  2978. };
  2979. }
  2980. /**
  2981. * Converts `set` to an array of its values.
  2982. *
  2983. * @private
  2984. * @param {Object} set The set to convert.
  2985. * @returns {Array} Returns the values.
  2986. */
  2987. function setToArray(set) {
  2988. var index = -1,
  2989. result = Array(set.size);
  2990. set.forEach(function(value) {
  2991. result[++index] = value;
  2992. });
  2993. return result;
  2994. }
  2995. /** Used for built-in method references. */
  2996. var arrayProto = Array.prototype,
  2997. funcProto = Function.prototype,
  2998. objectProto = Object.prototype;
  2999. /** Used to detect overreaching core-js shims. */
  3000. var coreJsData = root['__core-js_shared__'];
  3001. /** Used to detect methods masquerading as native. */
  3002. var maskSrcKey = (function() {
  3003. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  3004. return uid ? ('Symbol(src)_1.' + uid) : '';
  3005. }());
  3006. /** Used to resolve the decompiled source of functions. */
  3007. var funcToString = funcProto.toString;
  3008. /** Used to check objects for own properties. */
  3009. var hasOwnProperty = objectProto.hasOwnProperty;
  3010. /**
  3011. * Used to resolve the
  3012. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  3013. * of values.
  3014. */
  3015. var objectToString = objectProto.toString;
  3016. /** Used to detect if a method is native. */
  3017. var reIsNative = RegExp('^' +
  3018. funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  3019. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  3020. );
  3021. /** Built-in value references. */
  3022. var Symbol = root.Symbol,
  3023. Uint8Array = root.Uint8Array,
  3024. propertyIsEnumerable = objectProto.propertyIsEnumerable,
  3025. splice = arrayProto.splice;
  3026. /* Built-in method references for those with the same name as other `lodash` methods. */
  3027. var nativeKeys = overArg(Object.keys, Object);
  3028. /* Built-in method references that are verified to be native. */
  3029. var DataView = getNative(root, 'DataView'),
  3030. Map = getNative(root, 'Map'),
  3031. Promise = getNative(root, 'Promise'),
  3032. Set = getNative(root, 'Set'),
  3033. WeakMap = getNative(root, 'WeakMap'),
  3034. nativeCreate = getNative(Object, 'create');
  3035. /** Used to detect maps, sets, and weakmaps. */
  3036. var dataViewCtorString = toSource(DataView),
  3037. mapCtorString = toSource(Map),
  3038. promiseCtorString = toSource(Promise),
  3039. setCtorString = toSource(Set),
  3040. weakMapCtorString = toSource(WeakMap);
  3041. /** Used to convert symbols to primitives and strings. */
  3042. var symbolProto = Symbol ? Symbol.prototype : undefined,
  3043. symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
  3044. symbolToString = symbolProto ? symbolProto.toString : undefined;
  3045. /**
  3046. * Creates a hash object.
  3047. *
  3048. * @private
  3049. * @constructor
  3050. * @param {Array} [entries] The key-value pairs to cache.
  3051. */
  3052. function Hash(entries) {
  3053. var index = -1,
  3054. length = entries ? entries.length : 0;
  3055. this.clear();
  3056. while (++index < length) {
  3057. var entry = entries[index];
  3058. this.set(entry[0], entry[1]);
  3059. }
  3060. }
  3061. /**
  3062. * Removes all key-value entries from the hash.
  3063. *
  3064. * @private
  3065. * @name clear
  3066. * @memberOf Hash
  3067. */
  3068. function hashClear() {
  3069. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  3070. }
  3071. /**
  3072. * Removes `key` and its value from the hash.
  3073. *
  3074. * @private
  3075. * @name delete
  3076. * @memberOf Hash
  3077. * @param {Object} hash The hash to modify.
  3078. * @param {string} key The key of the value to remove.
  3079. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3080. */
  3081. function hashDelete(key) {
  3082. return this.has(key) && delete this.__data__[key];
  3083. }
  3084. /**
  3085. * Gets the hash value for `key`.
  3086. *
  3087. * @private
  3088. * @name get
  3089. * @memberOf Hash
  3090. * @param {string} key The key of the value to get.
  3091. * @returns {*} Returns the entry value.
  3092. */
  3093. function hashGet(key) {
  3094. var data = this.__data__;
  3095. if (nativeCreate) {
  3096. var result = data[key];
  3097. return result === HASH_UNDEFINED ? undefined : result;
  3098. }
  3099. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  3100. }
  3101. /**
  3102. * Checks if a hash value for `key` exists.
  3103. *
  3104. * @private
  3105. * @name has
  3106. * @memberOf Hash
  3107. * @param {string} key The key of the entry to check.
  3108. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3109. */
  3110. function hashHas(key) {
  3111. var data = this.__data__;
  3112. return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
  3113. }
  3114. /**
  3115. * Sets the hash `key` to `value`.
  3116. *
  3117. * @private
  3118. * @name set
  3119. * @memberOf Hash
  3120. * @param {string} key The key of the value to set.
  3121. * @param {*} value The value to set.
  3122. * @returns {Object} Returns the hash instance.
  3123. */
  3124. function hashSet(key, value) {
  3125. var data = this.__data__;
  3126. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  3127. return this;
  3128. }
  3129. // Add methods to `Hash`.
  3130. Hash.prototype.clear = hashClear;
  3131. Hash.prototype['delete'] = hashDelete;
  3132. Hash.prototype.get = hashGet;
  3133. Hash.prototype.has = hashHas;
  3134. Hash.prototype.set = hashSet;
  3135. /**
  3136. * Creates an list cache object.
  3137. *
  3138. * @private
  3139. * @constructor
  3140. * @param {Array} [entries] The key-value pairs to cache.
  3141. */
  3142. function ListCache(entries) {
  3143. var index = -1,
  3144. length = entries ? entries.length : 0;
  3145. this.clear();
  3146. while (++index < length) {
  3147. var entry = entries[index];
  3148. this.set(entry[0], entry[1]);
  3149. }
  3150. }
  3151. /**
  3152. * Removes all key-value entries from the list cache.
  3153. *
  3154. * @private
  3155. * @name clear
  3156. * @memberOf ListCache
  3157. */
  3158. function listCacheClear() {
  3159. this.__data__ = [];
  3160. }
  3161. /**
  3162. * Removes `key` and its value from the list cache.
  3163. *
  3164. * @private
  3165. * @name delete
  3166. * @memberOf ListCache
  3167. * @param {string} key The key of the value to remove.
  3168. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3169. */
  3170. function listCacheDelete(key) {
  3171. var data = this.__data__,
  3172. index = assocIndexOf(data, key);
  3173. if (index < 0) {
  3174. return false;
  3175. }
  3176. var lastIndex = data.length - 1;
  3177. if (index == lastIndex) {
  3178. data.pop();
  3179. } else {
  3180. splice.call(data, index, 1);
  3181. }
  3182. return true;
  3183. }
  3184. /**
  3185. * Gets the list cache value for `key`.
  3186. *
  3187. * @private
  3188. * @name get
  3189. * @memberOf ListCache
  3190. * @param {string} key The key of the value to get.
  3191. * @returns {*} Returns the entry value.
  3192. */
  3193. function listCacheGet(key) {
  3194. var data = this.__data__,
  3195. index = assocIndexOf(data, key);
  3196. return index < 0 ? undefined : data[index][1];
  3197. }
  3198. /**
  3199. * Checks if a list cache value for `key` exists.
  3200. *
  3201. * @private
  3202. * @name has
  3203. * @memberOf ListCache
  3204. * @param {string} key The key of the entry to check.
  3205. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3206. */
  3207. function listCacheHas(key) {
  3208. return assocIndexOf(this.__data__, key) > -1;
  3209. }
  3210. /**
  3211. * Sets the list cache `key` to `value`.
  3212. *
  3213. * @private
  3214. * @name set
  3215. * @memberOf ListCache
  3216. * @param {string} key The key of the value to set.
  3217. * @param {*} value The value to set.
  3218. * @returns {Object} Returns the list cache instance.
  3219. */
  3220. function listCacheSet(key, value) {
  3221. var data = this.__data__,
  3222. index = assocIndexOf(data, key);
  3223. if (index < 0) {
  3224. data.push([key, value]);
  3225. } else {
  3226. data[index][1] = value;
  3227. }
  3228. return this;
  3229. }
  3230. // Add methods to `ListCache`.
  3231. ListCache.prototype.clear = listCacheClear;
  3232. ListCache.prototype['delete'] = listCacheDelete;
  3233. ListCache.prototype.get = listCacheGet;
  3234. ListCache.prototype.has = listCacheHas;
  3235. ListCache.prototype.set = listCacheSet;
  3236. /**
  3237. * Creates a map cache object to store key-value pairs.
  3238. *
  3239. * @private
  3240. * @constructor
  3241. * @param {Array} [entries] The key-value pairs to cache.
  3242. */
  3243. function MapCache(entries) {
  3244. var index = -1,
  3245. length = entries ? entries.length : 0;
  3246. this.clear();
  3247. while (++index < length) {
  3248. var entry = entries[index];
  3249. this.set(entry[0], entry[1]);
  3250. }
  3251. }
  3252. /**
  3253. * Removes all key-value entries from the map.
  3254. *
  3255. * @private
  3256. * @name clear
  3257. * @memberOf MapCache
  3258. */
  3259. function mapCacheClear() {
  3260. this.__data__ = {
  3261. 'hash': new Hash,
  3262. 'map': new (Map || ListCache),
  3263. 'string': new Hash
  3264. };
  3265. }
  3266. /**
  3267. * Removes `key` and its value from the map.
  3268. *
  3269. * @private
  3270. * @name delete
  3271. * @memberOf MapCache
  3272. * @param {string} key The key of the value to remove.
  3273. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3274. */
  3275. function mapCacheDelete(key) {
  3276. return getMapData(this, key)['delete'](key);
  3277. }
  3278. /**
  3279. * Gets the map value for `key`.
  3280. *
  3281. * @private
  3282. * @name get
  3283. * @memberOf MapCache
  3284. * @param {string} key The key of the value to get.
  3285. * @returns {*} Returns the entry value.
  3286. */
  3287. function mapCacheGet(key) {
  3288. return getMapData(this, key).get(key);
  3289. }
  3290. /**
  3291. * Checks if a map value for `key` exists.
  3292. *
  3293. * @private
  3294. * @name has
  3295. * @memberOf MapCache
  3296. * @param {string} key The key of the entry to check.
  3297. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3298. */
  3299. function mapCacheHas(key) {
  3300. return getMapData(this, key).has(key);
  3301. }
  3302. /**
  3303. * Sets the map `key` to `value`.
  3304. *
  3305. * @private
  3306. * @name set
  3307. * @memberOf MapCache
  3308. * @param {string} key The key of the value to set.
  3309. * @param {*} value The value to set.
  3310. * @returns {Object} Returns the map cache instance.
  3311. */
  3312. function mapCacheSet(key, value) {
  3313. getMapData(this, key).set(key, value);
  3314. return this;
  3315. }
  3316. // Add methods to `MapCache`.
  3317. MapCache.prototype.clear = mapCacheClear;
  3318. MapCache.prototype['delete'] = mapCacheDelete;
  3319. MapCache.prototype.get = mapCacheGet;
  3320. MapCache.prototype.has = mapCacheHas;
  3321. MapCache.prototype.set = mapCacheSet;
  3322. /**
  3323. *
  3324. * Creates an array cache object to store unique values.
  3325. *
  3326. * @private
  3327. * @constructor
  3328. * @param {Array} [values] The values to cache.
  3329. */
  3330. function SetCache(values) {
  3331. var index = -1,
  3332. length = values ? values.length : 0;
  3333. this.__data__ = new MapCache;
  3334. while (++index < length) {
  3335. this.add(values[index]);
  3336. }
  3337. }
  3338. /**
  3339. * Adds `value` to the array cache.
  3340. *
  3341. * @private
  3342. * @name add
  3343. * @memberOf SetCache
  3344. * @alias push
  3345. * @param {*} value The value to cache.
  3346. * @returns {Object} Returns the cache instance.
  3347. */
  3348. function setCacheAdd(value) {
  3349. this.__data__.set(value, HASH_UNDEFINED);
  3350. return this;
  3351. }
  3352. /**
  3353. * Checks if `value` is in the array cache.
  3354. *
  3355. * @private
  3356. * @name has
  3357. * @memberOf SetCache
  3358. * @param {*} value The value to search for.
  3359. * @returns {number} Returns `true` if `value` is found, else `false`.
  3360. */
  3361. function setCacheHas(value) {
  3362. return this.__data__.has(value);
  3363. }
  3364. // Add methods to `SetCache`.
  3365. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
  3366. SetCache.prototype.has = setCacheHas;
  3367. /**
  3368. * Creates a stack cache object to store key-value pairs.
  3369. *
  3370. * @private
  3371. * @constructor
  3372. * @param {Array} [entries] The key-value pairs to cache.
  3373. */
  3374. function Stack(entries) {
  3375. this.__data__ = new ListCache(entries);
  3376. }
  3377. /**
  3378. * Removes all key-value entries from the stack.
  3379. *
  3380. * @private
  3381. * @name clear
  3382. * @memberOf Stack
  3383. */
  3384. function stackClear() {
  3385. this.__data__ = new ListCache;
  3386. }
  3387. /**
  3388. * Removes `key` and its value from the stack.
  3389. *
  3390. * @private
  3391. * @name delete
  3392. * @memberOf Stack
  3393. * @param {string} key The key of the value to remove.
  3394. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3395. */
  3396. function stackDelete(key) {
  3397. return this.__data__['delete'](key);
  3398. }
  3399. /**
  3400. * Gets the stack value for `key`.
  3401. *
  3402. * @private
  3403. * @name get
  3404. * @memberOf Stack
  3405. * @param {string} key The key of the value to get.
  3406. * @returns {*} Returns the entry value.
  3407. */
  3408. function stackGet(key) {
  3409. return this.__data__.get(key);
  3410. }
  3411. /**
  3412. * Checks if a stack value for `key` exists.
  3413. *
  3414. * @private
  3415. * @name has
  3416. * @memberOf Stack
  3417. * @param {string} key The key of the entry to check.
  3418. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3419. */
  3420. function stackHas(key) {
  3421. return this.__data__.has(key);
  3422. }
  3423. /**
  3424. * Sets the stack `key` to `value`.
  3425. *
  3426. * @private
  3427. * @name set
  3428. * @memberOf Stack
  3429. * @param {string} key The key of the value to set.
  3430. * @param {*} value The value to set.
  3431. * @returns {Object} Returns the stack cache instance.
  3432. */
  3433. function stackSet(key, value) {
  3434. var cache = this.__data__;
  3435. if (cache instanceof ListCache) {
  3436. var pairs = cache.__data__;
  3437. if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  3438. pairs.push([key, value]);
  3439. return this;
  3440. }
  3441. cache = this.__data__ = new MapCache(pairs);
  3442. }
  3443. cache.set(key, value);
  3444. return this;
  3445. }
  3446. // Add methods to `Stack`.
  3447. Stack.prototype.clear = stackClear;
  3448. Stack.prototype['delete'] = stackDelete;
  3449. Stack.prototype.get = stackGet;
  3450. Stack.prototype.has = stackHas;
  3451. Stack.prototype.set = stackSet;
  3452. /**
  3453. * Creates an array of the enumerable property names of the array-like `value`.
  3454. *
  3455. * @private
  3456. * @param {*} value The value to query.
  3457. * @param {boolean} inherited Specify returning inherited property names.
  3458. * @returns {Array} Returns the array of property names.
  3459. */
  3460. function arrayLikeKeys(value, inherited) {
  3461. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  3462. // Safari 9 makes `arguments.length` enumerable in strict mode.
  3463. var result = (isArray(value) || isArguments(value))
  3464. ? baseTimes(value.length, String)
  3465. : [];
  3466. var length = result.length,
  3467. skipIndexes = !!length;
  3468. for (var key in value) {
  3469. if ((inherited || hasOwnProperty.call(value, key)) &&
  3470. !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
  3471. result.push(key);
  3472. }
  3473. }
  3474. return result;
  3475. }
  3476. /**
  3477. * Gets the index at which the `key` is found in `array` of key-value pairs.
  3478. *
  3479. * @private
  3480. * @param {Array} array The array to inspect.
  3481. * @param {*} key The key to search for.
  3482. * @returns {number} Returns the index of the matched value, else `-1`.
  3483. */
  3484. function assocIndexOf(array, key) {
  3485. var length = array.length;
  3486. while (length--) {
  3487. if (eq(array[length][0], key)) {
  3488. return length;
  3489. }
  3490. }
  3491. return -1;
  3492. }
  3493. /**
  3494. * The base implementation of `_.get` without support for default values.
  3495. *
  3496. * @private
  3497. * @param {Object} object The object to query.
  3498. * @param {Array|string} path The path of the property to get.
  3499. * @returns {*} Returns the resolved value.
  3500. */
  3501. function baseGet(object, path) {
  3502. path = isKey(path, object) ? [path] : castPath(path);
  3503. var index = 0,
  3504. length = path.length;
  3505. while (object != null && index < length) {
  3506. object = object[toKey(path[index++])];
  3507. }
  3508. return (index && index == length) ? object : undefined;
  3509. }
  3510. /**
  3511. * The base implementation of `getTag`.
  3512. *
  3513. * @private
  3514. * @param {*} value The value to query.
  3515. * @returns {string} Returns the `toStringTag`.
  3516. */
  3517. function baseGetTag(value) {
  3518. return objectToString.call(value);
  3519. }
  3520. /**
  3521. * The base implementation of `_.hasIn` without support for deep paths.
  3522. *
  3523. * @private
  3524. * @param {Object} [object] The object to query.
  3525. * @param {Array|string} key The key to check.
  3526. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  3527. */
  3528. function baseHasIn(object, key) {
  3529. return object != null && key in Object(object);
  3530. }
  3531. /**
  3532. * The base implementation of `_.isEqual` which supports partial comparisons
  3533. * and tracks traversed objects.
  3534. *
  3535. * @private
  3536. * @param {*} value The value to compare.
  3537. * @param {*} other The other value to compare.
  3538. * @param {Function} [customizer] The function to customize comparisons.
  3539. * @param {boolean} [bitmask] The bitmask of comparison flags.
  3540. * The bitmask may be composed of the following flags:
  3541. * 1 - Unordered comparison
  3542. * 2 - Partial comparison
  3543. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  3544. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  3545. */
  3546. function baseIsEqual(value, other, customizer, bitmask, stack) {
  3547. if (value === other) {
  3548. return true;
  3549. }
  3550. if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
  3551. return value !== value && other !== other;
  3552. }
  3553. return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
  3554. }
  3555. /**
  3556. * A specialized version of `baseIsEqual` for arrays and objects which performs
  3557. * deep comparisons and tracks traversed objects enabling objects with circular
  3558. * references to be compared.
  3559. *
  3560. * @private
  3561. * @param {Object} object The object to compare.
  3562. * @param {Object} other The other object to compare.
  3563. * @param {Function} equalFunc The function to determine equivalents of values.
  3564. * @param {Function} [customizer] The function to customize comparisons.
  3565. * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
  3566. * for more details.
  3567. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  3568. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  3569. */
  3570. function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
  3571. var objIsArr = isArray(object),
  3572. othIsArr = isArray(other),
  3573. objTag = arrayTag,
  3574. othTag = arrayTag;
  3575. if (!objIsArr) {
  3576. objTag = getTag(object);
  3577. objTag = objTag == argsTag ? objectTag : objTag;
  3578. }
  3579. if (!othIsArr) {
  3580. othTag = getTag(other);
  3581. othTag = othTag == argsTag ? objectTag : othTag;
  3582. }
  3583. var objIsObj = objTag == objectTag && !isHostObject(object),
  3584. othIsObj = othTag == objectTag && !isHostObject(other),
  3585. isSameTag = objTag == othTag;
  3586. if (isSameTag && !objIsObj) {
  3587. stack || (stack = new Stack);
  3588. return (objIsArr || isTypedArray(object))
  3589. ? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
  3590. : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
  3591. }
  3592. if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
  3593. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  3594. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  3595. if (objIsWrapped || othIsWrapped) {
  3596. var objUnwrapped = objIsWrapped ? object.value() : object,
  3597. othUnwrapped = othIsWrapped ? other.value() : other;
  3598. stack || (stack = new Stack);
  3599. return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
  3600. }
  3601. }
  3602. if (!isSameTag) {
  3603. return false;
  3604. }
  3605. stack || (stack = new Stack);
  3606. return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
  3607. }
  3608. /**
  3609. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  3610. *
  3611. * @private
  3612. * @param {Object} object The object to inspect.
  3613. * @param {Object} source The object of property values to match.
  3614. * @param {Array} matchData The property names, values, and compare flags to match.
  3615. * @param {Function} [customizer] The function to customize comparisons.
  3616. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  3617. */
  3618. function baseIsMatch(object, source, matchData, customizer) {
  3619. var index = matchData.length,
  3620. length = index,
  3621. noCustomizer = !customizer;
  3622. if (object == null) {
  3623. return !length;
  3624. }
  3625. object = Object(object);
  3626. while (index--) {
  3627. var data = matchData[index];
  3628. if ((noCustomizer && data[2])
  3629. ? data[1] !== object[data[0]]
  3630. : !(data[0] in object)
  3631. ) {
  3632. return false;
  3633. }
  3634. }
  3635. while (++index < length) {
  3636. data = matchData[index];
  3637. var key = data[0],
  3638. objValue = object[key],
  3639. srcValue = data[1];
  3640. if (noCustomizer && data[2]) {
  3641. if (objValue === undefined && !(key in object)) {
  3642. return false;
  3643. }
  3644. } else {
  3645. var stack = new Stack;
  3646. if (customizer) {
  3647. var result = customizer(objValue, srcValue, key, object, source, stack);
  3648. }
  3649. if (!(result === undefined
  3650. ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
  3651. : result
  3652. )) {
  3653. return false;
  3654. }
  3655. }
  3656. }
  3657. return true;
  3658. }
  3659. /**
  3660. * The base implementation of `_.isNative` without bad shim checks.
  3661. *
  3662. * @private
  3663. * @param {*} value The value to check.
  3664. * @returns {boolean} Returns `true` if `value` is a native function,
  3665. * else `false`.
  3666. */
  3667. function baseIsNative(value) {
  3668. if (!isObject(value) || isMasked(value)) {
  3669. return false;
  3670. }
  3671. var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
  3672. return pattern.test(toSource(value));
  3673. }
  3674. /**
  3675. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  3676. *
  3677. * @private
  3678. * @param {*} value The value to check.
  3679. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3680. */
  3681. function baseIsTypedArray(value) {
  3682. return isObjectLike(value) &&
  3683. isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
  3684. }
  3685. /**
  3686. * The base implementation of `_.iteratee`.
  3687. *
  3688. * @private
  3689. * @param {*} [value=_.identity] The value to convert to an iteratee.
  3690. * @returns {Function} Returns the iteratee.
  3691. */
  3692. function baseIteratee(value) {
  3693. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  3694. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  3695. if (typeof value == 'function') {
  3696. return value;
  3697. }
  3698. if (value == null) {
  3699. return identity;
  3700. }
  3701. if (typeof value == 'object') {
  3702. return isArray(value)
  3703. ? baseMatchesProperty(value[0], value[1])
  3704. : baseMatches(value);
  3705. }
  3706. return property(value);
  3707. }
  3708. /**
  3709. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  3710. *
  3711. * @private
  3712. * @param {Object} object The object to query.
  3713. * @returns {Array} Returns the array of property names.
  3714. */
  3715. function baseKeys(object) {
  3716. if (!isPrototype(object)) {
  3717. return nativeKeys(object);
  3718. }
  3719. var result = [];
  3720. for (var key in Object(object)) {
  3721. if (hasOwnProperty.call(object, key) && key != 'constructor') {
  3722. result.push(key);
  3723. }
  3724. }
  3725. return result;
  3726. }
  3727. /**
  3728. * The base implementation of `_.matches` which doesn't clone `source`.
  3729. *
  3730. * @private
  3731. * @param {Object} source The object of property values to match.
  3732. * @returns {Function} Returns the new spec function.
  3733. */
  3734. function baseMatches(source) {
  3735. var matchData = getMatchData(source);
  3736. if (matchData.length == 1 && matchData[0][2]) {
  3737. return matchesStrictComparable(matchData[0][0], matchData[0][1]);
  3738. }
  3739. return function(object) {
  3740. return object === source || baseIsMatch(object, source, matchData);
  3741. };
  3742. }
  3743. /**
  3744. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  3745. *
  3746. * @private
  3747. * @param {string} path The path of the property to get.
  3748. * @param {*} srcValue The value to match.
  3749. * @returns {Function} Returns the new spec function.
  3750. */
  3751. function baseMatchesProperty(path, srcValue) {
  3752. if (isKey(path) && isStrictComparable(srcValue)) {
  3753. return matchesStrictComparable(toKey(path), srcValue);
  3754. }
  3755. return function(object) {
  3756. var objValue = get(object, path);
  3757. return (objValue === undefined && objValue === srcValue)
  3758. ? hasIn(object, path)
  3759. : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
  3760. };
  3761. }
  3762. /**
  3763. * A specialized version of `baseProperty` which supports deep paths.
  3764. *
  3765. * @private
  3766. * @param {Array|string} path The path of the property to get.
  3767. * @returns {Function} Returns the new accessor function.
  3768. */
  3769. function basePropertyDeep(path) {
  3770. return function(object) {
  3771. return baseGet(object, path);
  3772. };
  3773. }
  3774. /**
  3775. * The base implementation of `_.pullAt` without support for individual
  3776. * indexes or capturing the removed elements.
  3777. *
  3778. * @private
  3779. * @param {Array} array The array to modify.
  3780. * @param {number[]} indexes The indexes of elements to remove.
  3781. * @returns {Array} Returns `array`.
  3782. */
  3783. function basePullAt(array, indexes) {
  3784. var length = array ? indexes.length : 0,
  3785. lastIndex = length - 1;
  3786. while (length--) {
  3787. var index = indexes[length];
  3788. if (length == lastIndex || index !== previous) {
  3789. var previous = index;
  3790. if (isIndex(index)) {
  3791. splice.call(array, index, 1);
  3792. }
  3793. else if (!isKey(index, array)) {
  3794. var path = castPath(index),
  3795. object = parent(array, path);
  3796. if (object != null) {
  3797. delete object[toKey(last(path))];
  3798. }
  3799. }
  3800. else {
  3801. delete array[toKey(index)];
  3802. }
  3803. }
  3804. }
  3805. return array;
  3806. }
  3807. /**
  3808. * The base implementation of `_.slice` without an iteratee call guard.
  3809. *
  3810. * @private
  3811. * @param {Array} array The array to slice.
  3812. * @param {number} [start=0] The start position.
  3813. * @param {number} [end=array.length] The end position.
  3814. * @returns {Array} Returns the slice of `array`.
  3815. */
  3816. function baseSlice(array, start, end) {
  3817. var index = -1,
  3818. length = array.length;
  3819. if (start < 0) {
  3820. start = -start > length ? 0 : (length + start);
  3821. }
  3822. end = end > length ? length : end;
  3823. if (end < 0) {
  3824. end += length;
  3825. }
  3826. length = start > end ? 0 : ((end - start) >>> 0);
  3827. start >>>= 0;
  3828. var result = Array(length);
  3829. while (++index < length) {
  3830. result[index] = array[index + start];
  3831. }
  3832. return result;
  3833. }
  3834. /**
  3835. * The base implementation of `_.toString` which doesn't convert nullish
  3836. * values to empty strings.
  3837. *
  3838. * @private
  3839. * @param {*} value The value to process.
  3840. * @returns {string} Returns the string.
  3841. */
  3842. function baseToString(value) {
  3843. // Exit early for strings to avoid a performance hit in some environments.
  3844. if (typeof value == 'string') {
  3845. return value;
  3846. }
  3847. if (isSymbol(value)) {
  3848. return symbolToString ? symbolToString.call(value) : '';
  3849. }
  3850. var result = (value + '');
  3851. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  3852. }
  3853. /**
  3854. * Casts `value` to a path array if it's not one.
  3855. *
  3856. * @private
  3857. * @param {*} value The value to inspect.
  3858. * @returns {Array} Returns the cast property path array.
  3859. */
  3860. function castPath(value) {
  3861. return isArray(value) ? value : stringToPath(value);
  3862. }
  3863. /**
  3864. * A specialized version of `baseIsEqualDeep` for arrays with support for
  3865. * partial deep comparisons.
  3866. *
  3867. * @private
  3868. * @param {Array} array The array to compare.
  3869. * @param {Array} other The other array to compare.
  3870. * @param {Function} equalFunc The function to determine equivalents of values.
  3871. * @param {Function} customizer The function to customize comparisons.
  3872. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
  3873. * for more details.
  3874. * @param {Object} stack Tracks traversed `array` and `other` objects.
  3875. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  3876. */
  3877. function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
  3878. var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
  3879. arrLength = array.length,
  3880. othLength = other.length;
  3881. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  3882. return false;
  3883. }
  3884. // Assume cyclic values are equal.
  3885. var stacked = stack.get(array);
  3886. if (stacked && stack.get(other)) {
  3887. return stacked == other;
  3888. }
  3889. var index = -1,
  3890. result = true,
  3891. seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined;
  3892. stack.set(array, other);
  3893. stack.set(other, array);
  3894. // Ignore non-index properties.
  3895. while (++index < arrLength) {
  3896. var arrValue = array[index],
  3897. othValue = other[index];
  3898. if (customizer) {
  3899. var compared = isPartial
  3900. ? customizer(othValue, arrValue, index, other, array, stack)
  3901. : customizer(arrValue, othValue, index, array, other, stack);
  3902. }
  3903. if (compared !== undefined) {
  3904. if (compared) {
  3905. continue;
  3906. }
  3907. result = false;
  3908. break;
  3909. }
  3910. // Recursively compare arrays (susceptible to call stack limits).
  3911. if (seen) {
  3912. if (!arraySome(other, function(othValue, othIndex) {
  3913. if (!seen.has(othIndex) &&
  3914. (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
  3915. return seen.add(othIndex);
  3916. }
  3917. })) {
  3918. result = false;
  3919. break;
  3920. }
  3921. } else if (!(
  3922. arrValue === othValue ||
  3923. equalFunc(arrValue, othValue, customizer, bitmask, stack)
  3924. )) {
  3925. result = false;
  3926. break;
  3927. }
  3928. }
  3929. stack['delete'](array);
  3930. stack['delete'](other);
  3931. return result;
  3932. }
  3933. /**
  3934. * A specialized version of `baseIsEqualDeep` for comparing objects of
  3935. * the same `toStringTag`.
  3936. *
  3937. * **Note:** This function only supports comparing values with tags of
  3938. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  3939. *
  3940. * @private
  3941. * @param {Object} object The object to compare.
  3942. * @param {Object} other The other object to compare.
  3943. * @param {string} tag The `toStringTag` of the objects to compare.
  3944. * @param {Function} equalFunc The function to determine equivalents of values.
  3945. * @param {Function} customizer The function to customize comparisons.
  3946. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
  3947. * for more details.
  3948. * @param {Object} stack Tracks traversed `object` and `other` objects.
  3949. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  3950. */
  3951. function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
  3952. switch (tag) {
  3953. case dataViewTag:
  3954. if ((object.byteLength != other.byteLength) ||
  3955. (object.byteOffset != other.byteOffset)) {
  3956. return false;
  3957. }
  3958. object = object.buffer;
  3959. other = other.buffer;
  3960. case arrayBufferTag:
  3961. if ((object.byteLength != other.byteLength) ||
  3962. !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
  3963. return false;
  3964. }
  3965. return true;
  3966. case boolTag:
  3967. case dateTag:
  3968. case numberTag:
  3969. // Coerce booleans to `1` or `0` and dates to milliseconds.
  3970. // Invalid dates are coerced to `NaN`.
  3971. return eq(+object, +other);
  3972. case errorTag:
  3973. return object.name == other.name && object.message == other.message;
  3974. case regexpTag:
  3975. case stringTag:
  3976. // Coerce regexes to strings and treat strings, primitives and objects,
  3977. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  3978. // for more details.
  3979. return object == (other + '');
  3980. case mapTag:
  3981. var convert = mapToArray;
  3982. case setTag:
  3983. var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
  3984. convert || (convert = setToArray);
  3985. if (object.size != other.size && !isPartial) {
  3986. return false;
  3987. }
  3988. // Assume cyclic values are equal.
  3989. var stacked = stack.get(object);
  3990. if (stacked) {
  3991. return stacked == other;
  3992. }
  3993. bitmask |= UNORDERED_COMPARE_FLAG;
  3994. // Recursively compare objects (susceptible to call stack limits).
  3995. stack.set(object, other);
  3996. var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
  3997. stack['delete'](object);
  3998. return result;
  3999. case symbolTag:
  4000. if (symbolValueOf) {
  4001. return symbolValueOf.call(object) == symbolValueOf.call(other);
  4002. }
  4003. }
  4004. return false;
  4005. }
  4006. /**
  4007. * A specialized version of `baseIsEqualDeep` for objects with support for
  4008. * partial deep comparisons.
  4009. *
  4010. * @private
  4011. * @param {Object} object The object to compare.
  4012. * @param {Object} other The other object to compare.
  4013. * @param {Function} equalFunc The function to determine equivalents of values.
  4014. * @param {Function} customizer The function to customize comparisons.
  4015. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
  4016. * for more details.
  4017. * @param {Object} stack Tracks traversed `object` and `other` objects.
  4018. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  4019. */
  4020. function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
  4021. var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
  4022. objProps = keys(object),
  4023. objLength = objProps.length,
  4024. othProps = keys(other),
  4025. othLength = othProps.length;
  4026. if (objLength != othLength && !isPartial) {
  4027. return false;
  4028. }
  4029. var index = objLength;
  4030. while (index--) {
  4031. var key = objProps[index];
  4032. if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
  4033. return false;
  4034. }
  4035. }
  4036. // Assume cyclic values are equal.
  4037. var stacked = stack.get(object);
  4038. if (stacked && stack.get(other)) {
  4039. return stacked == other;
  4040. }
  4041. var result = true;
  4042. stack.set(object, other);
  4043. stack.set(other, object);
  4044. var skipCtor = isPartial;
  4045. while (++index < objLength) {
  4046. key = objProps[index];
  4047. var objValue = object[key],
  4048. othValue = other[key];
  4049. if (customizer) {
  4050. var compared = isPartial
  4051. ? customizer(othValue, objValue, key, other, object, stack)
  4052. : customizer(objValue, othValue, key, object, other, stack);
  4053. }
  4054. // Recursively compare objects (susceptible to call stack limits).
  4055. if (!(compared === undefined
  4056. ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
  4057. : compared
  4058. )) {
  4059. result = false;
  4060. break;
  4061. }
  4062. skipCtor || (skipCtor = key == 'constructor');
  4063. }
  4064. if (result && !skipCtor) {
  4065. var objCtor = object.constructor,
  4066. othCtor = other.constructor;
  4067. // Non `Object` object instances with different constructors are not equal.
  4068. if (objCtor != othCtor &&
  4069. ('constructor' in object && 'constructor' in other) &&
  4070. !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
  4071. typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  4072. result = false;
  4073. }
  4074. }
  4075. stack['delete'](object);
  4076. stack['delete'](other);
  4077. return result;
  4078. }
  4079. /**
  4080. * Gets the data for `map`.
  4081. *
  4082. * @private
  4083. * @param {Object} map The map to query.
  4084. * @param {string} key The reference key.
  4085. * @returns {*} Returns the map data.
  4086. */
  4087. function getMapData(map, key) {
  4088. var data = map.__data__;
  4089. return isKeyable(key)
  4090. ? data[typeof key == 'string' ? 'string' : 'hash']
  4091. : data.map;
  4092. }
  4093. /**
  4094. * Gets the property names, values, and compare flags of `object`.
  4095. *
  4096. * @private
  4097. * @param {Object} object The object to query.
  4098. * @returns {Array} Returns the match data of `object`.
  4099. */
  4100. function getMatchData(object) {
  4101. var result = keys(object),
  4102. length = result.length;
  4103. while (length--) {
  4104. var key = result[length],
  4105. value = object[key];
  4106. result[length] = [key, value, isStrictComparable(value)];
  4107. }
  4108. return result;
  4109. }
  4110. /**
  4111. * Gets the native function at `key` of `object`.
  4112. *
  4113. * @private
  4114. * @param {Object} object The object to query.
  4115. * @param {string} key The key of the method to get.
  4116. * @returns {*} Returns the function if it's native, else `undefined`.
  4117. */
  4118. function getNative(object, key) {
  4119. var value = getValue(object, key);
  4120. return baseIsNative(value) ? value : undefined;
  4121. }
  4122. /**
  4123. * Gets the `toStringTag` of `value`.
  4124. *
  4125. * @private
  4126. * @param {*} value The value to query.
  4127. * @returns {string} Returns the `toStringTag`.
  4128. */
  4129. var getTag = baseGetTag;
  4130. // Fallback for data views, maps, sets, and weak maps in IE 11,
  4131. // for data views in Edge < 14, and promises in Node.js.
  4132. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
  4133. (Map && getTag(new Map) != mapTag) ||
  4134. (Promise && getTag(Promise.resolve()) != promiseTag) ||
  4135. (Set && getTag(new Set) != setTag) ||
  4136. (WeakMap && getTag(new WeakMap) != weakMapTag)) {
  4137. getTag = function(value) {
  4138. var result = objectToString.call(value),
  4139. Ctor = result == objectTag ? value.constructor : undefined,
  4140. ctorString = Ctor ? toSource(Ctor) : undefined;
  4141. if (ctorString) {
  4142. switch (ctorString) {
  4143. case dataViewCtorString: return dataViewTag;
  4144. case mapCtorString: return mapTag;
  4145. case promiseCtorString: return promiseTag;
  4146. case setCtorString: return setTag;
  4147. case weakMapCtorString: return weakMapTag;
  4148. }
  4149. }
  4150. return result;
  4151. };
  4152. }
  4153. /**
  4154. * Checks if `path` exists on `object`.
  4155. *
  4156. * @private
  4157. * @param {Object} object The object to query.
  4158. * @param {Array|string} path The path to check.
  4159. * @param {Function} hasFunc The function to check properties.
  4160. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  4161. */
  4162. function hasPath(object, path, hasFunc) {
  4163. path = isKey(path, object) ? [path] : castPath(path);
  4164. var result,
  4165. index = -1,
  4166. length = path.length;
  4167. while (++index < length) {
  4168. var key = toKey(path[index]);
  4169. if (!(result = object != null && hasFunc(object, key))) {
  4170. break;
  4171. }
  4172. object = object[key];
  4173. }
  4174. if (result) {
  4175. return result;
  4176. }
  4177. var length = object ? object.length : 0;
  4178. return !!length && isLength(length) && isIndex(key, length) &&
  4179. (isArray(object) || isArguments(object));
  4180. }
  4181. /**
  4182. * Checks if `value` is a valid array-like index.
  4183. *
  4184. * @private
  4185. * @param {*} value The value to check.
  4186. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  4187. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  4188. */
  4189. function isIndex(value, length) {
  4190. length = length == null ? MAX_SAFE_INTEGER : length;
  4191. return !!length &&
  4192. (typeof value == 'number' || reIsUint.test(value)) &&
  4193. (value > -1 && value % 1 == 0 && value < length);
  4194. }
  4195. /**
  4196. * Checks if `value` is a property name and not a property path.
  4197. *
  4198. * @private
  4199. * @param {*} value The value to check.
  4200. * @param {Object} [object] The object to query keys on.
  4201. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  4202. */
  4203. function isKey(value, object) {
  4204. if (isArray(value)) {
  4205. return false;
  4206. }
  4207. var type = typeof value;
  4208. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  4209. value == null || isSymbol(value)) {
  4210. return true;
  4211. }
  4212. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  4213. (object != null && value in Object(object));
  4214. }
  4215. /**
  4216. * Checks if `value` is suitable for use as unique object key.
  4217. *
  4218. * @private
  4219. * @param {*} value The value to check.
  4220. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  4221. */
  4222. function isKeyable(value) {
  4223. var type = typeof value;
  4224. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  4225. ? (value !== '__proto__')
  4226. : (value === null);
  4227. }
  4228. /**
  4229. * Checks if `func` has its source masked.
  4230. *
  4231. * @private
  4232. * @param {Function} func The function to check.
  4233. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  4234. */
  4235. function isMasked(func) {
  4236. return !!maskSrcKey && (maskSrcKey in func);
  4237. }
  4238. /**
  4239. * Checks if `value` is likely a prototype object.
  4240. *
  4241. * @private
  4242. * @param {*} value The value to check.
  4243. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  4244. */
  4245. function isPrototype(value) {
  4246. var Ctor = value && value.constructor,
  4247. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
  4248. return value === proto;
  4249. }
  4250. /**
  4251. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  4252. *
  4253. * @private
  4254. * @param {*} value The value to check.
  4255. * @returns {boolean} Returns `true` if `value` if suitable for strict
  4256. * equality comparisons, else `false`.
  4257. */
  4258. function isStrictComparable(value) {
  4259. return value === value && !isObject(value);
  4260. }
  4261. /**
  4262. * A specialized version of `matchesProperty` for source values suitable
  4263. * for strict equality comparisons, i.e. `===`.
  4264. *
  4265. * @private
  4266. * @param {string} key The key of the property to get.
  4267. * @param {*} srcValue The value to match.
  4268. * @returns {Function} Returns the new spec function.
  4269. */
  4270. function matchesStrictComparable(key, srcValue) {
  4271. return function(object) {
  4272. if (object == null) {
  4273. return false;
  4274. }
  4275. return object[key] === srcValue &&
  4276. (srcValue !== undefined || (key in Object(object)));
  4277. };
  4278. }
  4279. /**
  4280. * Gets the parent value at `path` of `object`.
  4281. *
  4282. * @private
  4283. * @param {Object} object The object to query.
  4284. * @param {Array} path The path to get the parent value of.
  4285. * @returns {*} Returns the parent value.
  4286. */
  4287. function parent(object, path) {
  4288. return path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
  4289. }
  4290. /**
  4291. * Converts `string` to a property path array.
  4292. *
  4293. * @private
  4294. * @param {string} string The string to convert.
  4295. * @returns {Array} Returns the property path array.
  4296. */
  4297. var stringToPath = memoize(function(string) {
  4298. string = toString(string);
  4299. var result = [];
  4300. if (reLeadingDot.test(string)) {
  4301. result.push('');
  4302. }
  4303. string.replace(rePropName, function(match, number, quote, string) {
  4304. result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
  4305. });
  4306. return result;
  4307. });
  4308. /**
  4309. * Converts `value` to a string key if it's not a string or symbol.
  4310. *
  4311. * @private
  4312. * @param {*} value The value to inspect.
  4313. * @returns {string|symbol} Returns the key.
  4314. */
  4315. function toKey(value) {
  4316. if (typeof value == 'string' || isSymbol(value)) {
  4317. return value;
  4318. }
  4319. var result = (value + '');
  4320. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  4321. }
  4322. /**
  4323. * Converts `func` to its source code.
  4324. *
  4325. * @private
  4326. * @param {Function} func The function to process.
  4327. * @returns {string} Returns the source code.
  4328. */
  4329. function toSource(func) {
  4330. if (func != null) {
  4331. try {
  4332. return funcToString.call(func);
  4333. } catch (e) {}
  4334. try {
  4335. return (func + '');
  4336. } catch (e) {}
  4337. }
  4338. return '';
  4339. }
  4340. /**
  4341. * Gets the last element of `array`.
  4342. *
  4343. * @static
  4344. * @memberOf _
  4345. * @since 0.1.0
  4346. * @category Array
  4347. * @param {Array} array The array to query.
  4348. * @returns {*} Returns the last element of `array`.
  4349. * @example
  4350. *
  4351. * _.last([1, 2, 3]);
  4352. * // => 3
  4353. */
  4354. function last(array) {
  4355. var length = array ? array.length : 0;
  4356. return length ? array[length - 1] : undefined;
  4357. }
  4358. /**
  4359. * Removes all elements from `array` that `predicate` returns truthy for
  4360. * and returns an array of the removed elements. The predicate is invoked
  4361. * with three arguments: (value, index, array).
  4362. *
  4363. * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
  4364. * to pull elements from an array by value.
  4365. *
  4366. * @static
  4367. * @memberOf _
  4368. * @since 2.0.0
  4369. * @category Array
  4370. * @param {Array} array The array to modify.
  4371. * @param {Function} [predicate=_.identity]
  4372. * The function invoked per iteration.
  4373. * @returns {Array} Returns the new array of removed elements.
  4374. * @example
  4375. *
  4376. * var array = [1, 2, 3, 4];
  4377. * var evens = _.remove(array, function(n) {
  4378. * return n % 2 == 0;
  4379. * });
  4380. *
  4381. * console.log(array);
  4382. * // => [1, 3]
  4383. *
  4384. * console.log(evens);
  4385. * // => [2, 4]
  4386. */
  4387. function remove(array, predicate) {
  4388. var result = [];
  4389. if (!(array && array.length)) {
  4390. return result;
  4391. }
  4392. var index = -1,
  4393. indexes = [],
  4394. length = array.length;
  4395. predicate = baseIteratee(predicate, 3);
  4396. while (++index < length) {
  4397. var value = array[index];
  4398. if (predicate(value, index, array)) {
  4399. result.push(value);
  4400. indexes.push(index);
  4401. }
  4402. }
  4403. basePullAt(array, indexes);
  4404. return result;
  4405. }
  4406. /**
  4407. * Creates a function that memoizes the result of `func`. If `resolver` is
  4408. * provided, it determines the cache key for storing the result based on the
  4409. * arguments provided to the memoized function. By default, the first argument
  4410. * provided to the memoized function is used as the map cache key. The `func`
  4411. * is invoked with the `this` binding of the memoized function.
  4412. *
  4413. * **Note:** The cache is exposed as the `cache` property on the memoized
  4414. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  4415. * constructor with one whose instances implement the
  4416. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  4417. * method interface of `delete`, `get`, `has`, and `set`.
  4418. *
  4419. * @static
  4420. * @memberOf _
  4421. * @since 0.1.0
  4422. * @category Function
  4423. * @param {Function} func The function to have its output memoized.
  4424. * @param {Function} [resolver] The function to resolve the cache key.
  4425. * @returns {Function} Returns the new memoized function.
  4426. * @example
  4427. *
  4428. * var object = { 'a': 1, 'b': 2 };
  4429. * var other = { 'c': 3, 'd': 4 };
  4430. *
  4431. * var values = _.memoize(_.values);
  4432. * values(object);
  4433. * // => [1, 2]
  4434. *
  4435. * values(other);
  4436. * // => [3, 4]
  4437. *
  4438. * object.a = 2;
  4439. * values(object);
  4440. * // => [1, 2]
  4441. *
  4442. * // Modify the result cache.
  4443. * values.cache.set(object, ['a', 'b']);
  4444. * values(object);
  4445. * // => ['a', 'b']
  4446. *
  4447. * // Replace `_.memoize.Cache`.
  4448. * _.memoize.Cache = WeakMap;
  4449. */
  4450. function memoize(func, resolver) {
  4451. if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
  4452. throw new TypeError(FUNC_ERROR_TEXT);
  4453. }
  4454. var memoized = function() {
  4455. var args = arguments,
  4456. key = resolver ? resolver.apply(this, args) : args[0],
  4457. cache = memoized.cache;
  4458. if (cache.has(key)) {
  4459. return cache.get(key);
  4460. }
  4461. var result = func.apply(this, args);
  4462. memoized.cache = cache.set(key, result);
  4463. return result;
  4464. };
  4465. memoized.cache = new (memoize.Cache || MapCache);
  4466. return memoized;
  4467. }
  4468. // Assign cache to `_.memoize`.
  4469. memoize.Cache = MapCache;
  4470. /**
  4471. * Performs a
  4472. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  4473. * comparison between two values to determine if they are equivalent.
  4474. *
  4475. * @static
  4476. * @memberOf _
  4477. * @since 4.0.0
  4478. * @category Lang
  4479. * @param {*} value The value to compare.
  4480. * @param {*} other The other value to compare.
  4481. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  4482. * @example
  4483. *
  4484. * var object = { 'a': 1 };
  4485. * var other = { 'a': 1 };
  4486. *
  4487. * _.eq(object, object);
  4488. * // => true
  4489. *
  4490. * _.eq(object, other);
  4491. * // => false
  4492. *
  4493. * _.eq('a', 'a');
  4494. * // => true
  4495. *
  4496. * _.eq('a', Object('a'));
  4497. * // => false
  4498. *
  4499. * _.eq(NaN, NaN);
  4500. * // => true
  4501. */
  4502. function eq(value, other) {
  4503. return value === other || (value !== value && other !== other);
  4504. }
  4505. /**
  4506. * Checks if `value` is likely an `arguments` object.
  4507. *
  4508. * @static
  4509. * @memberOf _
  4510. * @since 0.1.0
  4511. * @category Lang
  4512. * @param {*} value The value to check.
  4513. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  4514. * else `false`.
  4515. * @example
  4516. *
  4517. * _.isArguments(function() { return arguments; }());
  4518. * // => true
  4519. *
  4520. * _.isArguments([1, 2, 3]);
  4521. * // => false
  4522. */
  4523. function isArguments(value) {
  4524. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  4525. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
  4526. (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
  4527. }
  4528. /**
  4529. * Checks if `value` is classified as an `Array` object.
  4530. *
  4531. * @static
  4532. * @memberOf _
  4533. * @since 0.1.0
  4534. * @category Lang
  4535. * @param {*} value The value to check.
  4536. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  4537. * @example
  4538. *
  4539. * _.isArray([1, 2, 3]);
  4540. * // => true
  4541. *
  4542. * _.isArray(document.body.children);
  4543. * // => false
  4544. *
  4545. * _.isArray('abc');
  4546. * // => false
  4547. *
  4548. * _.isArray(_.noop);
  4549. * // => false
  4550. */
  4551. var isArray = Array.isArray;
  4552. /**
  4553. * Checks if `value` is array-like. A value is considered array-like if it's
  4554. * not a function and has a `value.length` that's an integer greater than or
  4555. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  4556. *
  4557. * @static
  4558. * @memberOf _
  4559. * @since 4.0.0
  4560. * @category Lang
  4561. * @param {*} value The value to check.
  4562. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  4563. * @example
  4564. *
  4565. * _.isArrayLike([1, 2, 3]);
  4566. * // => true
  4567. *
  4568. * _.isArrayLike(document.body.children);
  4569. * // => true
  4570. *
  4571. * _.isArrayLike('abc');
  4572. * // => true
  4573. *
  4574. * _.isArrayLike(_.noop);
  4575. * // => false
  4576. */
  4577. function isArrayLike(value) {
  4578. return value != null && isLength(value.length) && !isFunction(value);
  4579. }
  4580. /**
  4581. * This method is like `_.isArrayLike` except that it also checks if `value`
  4582. * is an object.
  4583. *
  4584. * @static
  4585. * @memberOf _
  4586. * @since 4.0.0
  4587. * @category Lang
  4588. * @param {*} value The value to check.
  4589. * @returns {boolean} Returns `true` if `value` is an array-like object,
  4590. * else `false`.
  4591. * @example
  4592. *
  4593. * _.isArrayLikeObject([1, 2, 3]);
  4594. * // => true
  4595. *
  4596. * _.isArrayLikeObject(document.body.children);
  4597. * // => true
  4598. *
  4599. * _.isArrayLikeObject('abc');
  4600. * // => false
  4601. *
  4602. * _.isArrayLikeObject(_.noop);
  4603. * // => false
  4604. */
  4605. function isArrayLikeObject(value) {
  4606. return isObjectLike(value) && isArrayLike(value);
  4607. }
  4608. /**
  4609. * Checks if `value` is classified as a `Function` object.
  4610. *
  4611. * @static
  4612. * @memberOf _
  4613. * @since 0.1.0
  4614. * @category Lang
  4615. * @param {*} value The value to check.
  4616. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  4617. * @example
  4618. *
  4619. * _.isFunction(_);
  4620. * // => true
  4621. *
  4622. * _.isFunction(/abc/);
  4623. * // => false
  4624. */
  4625. function isFunction(value) {
  4626. // The use of `Object#toString` avoids issues with the `typeof` operator
  4627. // in Safari 8-9 which returns 'object' for typed array and other constructors.
  4628. var tag = isObject(value) ? objectToString.call(value) : '';
  4629. return tag == funcTag || tag == genTag;
  4630. }
  4631. /**
  4632. * Checks if `value` is a valid array-like length.
  4633. *
  4634. * **Note:** This method is loosely based on
  4635. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  4636. *
  4637. * @static
  4638. * @memberOf _
  4639. * @since 4.0.0
  4640. * @category Lang
  4641. * @param {*} value The value to check.
  4642. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  4643. * @example
  4644. *
  4645. * _.isLength(3);
  4646. * // => true
  4647. *
  4648. * _.isLength(Number.MIN_VALUE);
  4649. * // => false
  4650. *
  4651. * _.isLength(Infinity);
  4652. * // => false
  4653. *
  4654. * _.isLength('3');
  4655. * // => false
  4656. */
  4657. function isLength(value) {
  4658. return typeof value == 'number' &&
  4659. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  4660. }
  4661. /**
  4662. * Checks if `value` is the
  4663. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  4664. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  4665. *
  4666. * @static
  4667. * @memberOf _
  4668. * @since 0.1.0
  4669. * @category Lang
  4670. * @param {*} value The value to check.
  4671. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  4672. * @example
  4673. *
  4674. * _.isObject({});
  4675. * // => true
  4676. *
  4677. * _.isObject([1, 2, 3]);
  4678. * // => true
  4679. *
  4680. * _.isObject(_.noop);
  4681. * // => true
  4682. *
  4683. * _.isObject(null);
  4684. * // => false
  4685. */
  4686. function isObject(value) {
  4687. var type = typeof value;
  4688. return !!value && (type == 'object' || type == 'function');
  4689. }
  4690. /**
  4691. * Checks if `value` is object-like. A value is object-like if it's not `null`
  4692. * and has a `typeof` result of "object".
  4693. *
  4694. * @static
  4695. * @memberOf _
  4696. * @since 4.0.0
  4697. * @category Lang
  4698. * @param {*} value The value to check.
  4699. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  4700. * @example
  4701. *
  4702. * _.isObjectLike({});
  4703. * // => true
  4704. *
  4705. * _.isObjectLike([1, 2, 3]);
  4706. * // => true
  4707. *
  4708. * _.isObjectLike(_.noop);
  4709. * // => false
  4710. *
  4711. * _.isObjectLike(null);
  4712. * // => false
  4713. */
  4714. function isObjectLike(value) {
  4715. return !!value && typeof value == 'object';
  4716. }
  4717. /**
  4718. * Checks if `value` is classified as a `Symbol` primitive or object.
  4719. *
  4720. * @static
  4721. * @memberOf _
  4722. * @since 4.0.0
  4723. * @category Lang
  4724. * @param {*} value The value to check.
  4725. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  4726. * @example
  4727. *
  4728. * _.isSymbol(Symbol.iterator);
  4729. * // => true
  4730. *
  4731. * _.isSymbol('abc');
  4732. * // => false
  4733. */
  4734. function isSymbol(value) {
  4735. return typeof value == 'symbol' ||
  4736. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  4737. }
  4738. /**
  4739. * Checks if `value` is classified as a typed array.
  4740. *
  4741. * @static
  4742. * @memberOf _
  4743. * @since 3.0.0
  4744. * @category Lang
  4745. * @param {*} value The value to check.
  4746. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  4747. * @example
  4748. *
  4749. * _.isTypedArray(new Uint8Array);
  4750. * // => true
  4751. *
  4752. * _.isTypedArray([]);
  4753. * // => false
  4754. */
  4755. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  4756. /**
  4757. * Converts `value` to a string. An empty string is returned for `null`
  4758. * and `undefined` values. The sign of `-0` is preserved.
  4759. *
  4760. * @static
  4761. * @memberOf _
  4762. * @since 4.0.0
  4763. * @category Lang
  4764. * @param {*} value The value to process.
  4765. * @returns {string} Returns the string.
  4766. * @example
  4767. *
  4768. * _.toString(null);
  4769. * // => ''
  4770. *
  4771. * _.toString(-0);
  4772. * // => '-0'
  4773. *
  4774. * _.toString([1, 2, 3]);
  4775. * // => '1,2,3'
  4776. */
  4777. function toString(value) {
  4778. return value == null ? '' : baseToString(value);
  4779. }
  4780. /**
  4781. * Gets the value at `path` of `object`. If the resolved value is
  4782. * `undefined`, the `defaultValue` is returned in its place.
  4783. *
  4784. * @static
  4785. * @memberOf _
  4786. * @since 3.7.0
  4787. * @category Object
  4788. * @param {Object} object The object to query.
  4789. * @param {Array|string} path The path of the property to get.
  4790. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  4791. * @returns {*} Returns the resolved value.
  4792. * @example
  4793. *
  4794. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  4795. *
  4796. * _.get(object, 'a[0].b.c');
  4797. * // => 3
  4798. *
  4799. * _.get(object, ['a', '0', 'b', 'c']);
  4800. * // => 3
  4801. *
  4802. * _.get(object, 'a.b.c', 'default');
  4803. * // => 'default'
  4804. */
  4805. function get(object, path, defaultValue) {
  4806. var result = object == null ? undefined : baseGet(object, path);
  4807. return result === undefined ? defaultValue : result;
  4808. }
  4809. /**
  4810. * Checks if `path` is a direct or inherited property of `object`.
  4811. *
  4812. * @static
  4813. * @memberOf _
  4814. * @since 4.0.0
  4815. * @category Object
  4816. * @param {Object} object The object to query.
  4817. * @param {Array|string} path The path to check.
  4818. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  4819. * @example
  4820. *
  4821. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  4822. *
  4823. * _.hasIn(object, 'a');
  4824. * // => true
  4825. *
  4826. * _.hasIn(object, 'a.b');
  4827. * // => true
  4828. *
  4829. * _.hasIn(object, ['a', 'b']);
  4830. * // => true
  4831. *
  4832. * _.hasIn(object, 'b');
  4833. * // => false
  4834. */
  4835. function hasIn(object, path) {
  4836. return object != null && hasPath(object, path, baseHasIn);
  4837. }
  4838. /**
  4839. * Creates an array of the own enumerable property names of `object`.
  4840. *
  4841. * **Note:** Non-object values are coerced to objects. See the
  4842. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  4843. * for more details.
  4844. *
  4845. * @static
  4846. * @since 0.1.0
  4847. * @memberOf _
  4848. * @category Object
  4849. * @param {Object} object The object to query.
  4850. * @returns {Array} Returns the array of property names.
  4851. * @example
  4852. *
  4853. * function Foo() {
  4854. * this.a = 1;
  4855. * this.b = 2;
  4856. * }
  4857. *
  4858. * Foo.prototype.c = 3;
  4859. *
  4860. * _.keys(new Foo);
  4861. * // => ['a', 'b'] (iteration order is not guaranteed)
  4862. *
  4863. * _.keys('hi');
  4864. * // => ['0', '1']
  4865. */
  4866. function keys(object) {
  4867. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  4868. }
  4869. /**
  4870. * This method returns the first argument it receives.
  4871. *
  4872. * @static
  4873. * @since 0.1.0
  4874. * @memberOf _
  4875. * @category Util
  4876. * @param {*} value Any value.
  4877. * @returns {*} Returns `value`.
  4878. * @example
  4879. *
  4880. * var object = { 'a': 1 };
  4881. *
  4882. * console.log(_.identity(object) === object);
  4883. * // => true
  4884. */
  4885. function identity(value) {
  4886. return value;
  4887. }
  4888. /**
  4889. * Creates a function that returns the value at `path` of a given object.
  4890. *
  4891. * @static
  4892. * @memberOf _
  4893. * @since 2.4.0
  4894. * @category Util
  4895. * @param {Array|string} path The path of the property to get.
  4896. * @returns {Function} Returns the new accessor function.
  4897. * @example
  4898. *
  4899. * var objects = [
  4900. * { 'a': { 'b': 2 } },
  4901. * { 'a': { 'b': 1 } }
  4902. * ];
  4903. *
  4904. * _.map(objects, _.property('a.b'));
  4905. * // => [2, 1]
  4906. *
  4907. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  4908. * // => [1, 2]
  4909. */
  4910. function property(path) {
  4911. return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
  4912. }
  4913. module.exports = remove;
  4914. /***/ }),
  4915. /***/ "./node_modules/process/browser.js":
  4916. /*!*****************************************!*\
  4917. !*** ./node_modules/process/browser.js ***!
  4918. \*****************************************/
  4919. /***/ ((module) => {
  4920. // shim for using process in browser
  4921. var process = module.exports = {};
  4922. // cached from whatever global is present so that test runners that stub it
  4923. // don't break things. But we need to wrap it in a try catch in case it is
  4924. // wrapped in strict mode code which doesn't define any globals. It's inside a
  4925. // function because try/catches deoptimize in certain engines.
  4926. var cachedSetTimeout;
  4927. var cachedClearTimeout;
  4928. function defaultSetTimout() {
  4929. throw new Error('setTimeout has not been defined');
  4930. }
  4931. function defaultClearTimeout () {
  4932. throw new Error('clearTimeout has not been defined');
  4933. }
  4934. (function () {
  4935. try {
  4936. if (typeof setTimeout === 'function') {
  4937. cachedSetTimeout = setTimeout;
  4938. } else {
  4939. cachedSetTimeout = defaultSetTimout;
  4940. }
  4941. } catch (e) {
  4942. cachedSetTimeout = defaultSetTimout;
  4943. }
  4944. try {
  4945. if (typeof clearTimeout === 'function') {
  4946. cachedClearTimeout = clearTimeout;
  4947. } else {
  4948. cachedClearTimeout = defaultClearTimeout;
  4949. }
  4950. } catch (e) {
  4951. cachedClearTimeout = defaultClearTimeout;
  4952. }
  4953. } ())
  4954. function runTimeout(fun) {
  4955. if (cachedSetTimeout === setTimeout) {
  4956. //normal enviroments in sane situations
  4957. return setTimeout(fun, 0);
  4958. }
  4959. // if setTimeout wasn't available but was latter defined
  4960. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  4961. cachedSetTimeout = setTimeout;
  4962. return setTimeout(fun, 0);
  4963. }
  4964. try {
  4965. // when when somebody has screwed with setTimeout but no I.E. maddness
  4966. return cachedSetTimeout(fun, 0);
  4967. } catch(e){
  4968. try {
  4969. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  4970. return cachedSetTimeout.call(null, fun, 0);
  4971. } catch(e){
  4972. // 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
  4973. return cachedSetTimeout.call(this, fun, 0);
  4974. }
  4975. }
  4976. }
  4977. function runClearTimeout(marker) {
  4978. if (cachedClearTimeout === clearTimeout) {
  4979. //normal enviroments in sane situations
  4980. return clearTimeout(marker);
  4981. }
  4982. // if clearTimeout wasn't available but was latter defined
  4983. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  4984. cachedClearTimeout = clearTimeout;
  4985. return clearTimeout(marker);
  4986. }
  4987. try {
  4988. // when when somebody has screwed with setTimeout but no I.E. maddness
  4989. return cachedClearTimeout(marker);
  4990. } catch (e){
  4991. try {
  4992. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  4993. return cachedClearTimeout.call(null, marker);
  4994. } catch (e){
  4995. // 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.
  4996. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  4997. return cachedClearTimeout.call(this, marker);
  4998. }
  4999. }
  5000. }
  5001. var queue = [];
  5002. var draining = false;
  5003. var currentQueue;
  5004. var queueIndex = -1;
  5005. function cleanUpNextTick() {
  5006. if (!draining || !currentQueue) {
  5007. return;
  5008. }
  5009. draining = false;
  5010. if (currentQueue.length) {
  5011. queue = currentQueue.concat(queue);
  5012. } else {
  5013. queueIndex = -1;
  5014. }
  5015. if (queue.length) {
  5016. drainQueue();
  5017. }
  5018. }
  5019. function drainQueue() {
  5020. if (draining) {
  5021. return;
  5022. }
  5023. var timeout = runTimeout(cleanUpNextTick);
  5024. draining = true;
  5025. var len = queue.length;
  5026. while(len) {
  5027. currentQueue = queue;
  5028. queue = [];
  5029. while (++queueIndex < len) {
  5030. if (currentQueue) {
  5031. currentQueue[queueIndex].run();
  5032. }
  5033. }
  5034. queueIndex = -1;
  5035. len = queue.length;
  5036. }
  5037. currentQueue = null;
  5038. draining = false;
  5039. runClearTimeout(timeout);
  5040. }
  5041. process.nextTick = function (fun) {
  5042. var args = new Array(arguments.length - 1);
  5043. if (arguments.length > 1) {
  5044. for (var i = 1; i < arguments.length; i++) {
  5045. args[i - 1] = arguments[i];
  5046. }
  5047. }
  5048. queue.push(new Item(fun, args));
  5049. if (queue.length === 1 && !draining) {
  5050. runTimeout(drainQueue);
  5051. }
  5052. };
  5053. // v8 likes predictible objects
  5054. function Item(fun, array) {
  5055. this.fun = fun;
  5056. this.array = array;
  5057. }
  5058. Item.prototype.run = function () {
  5059. this.fun.apply(null, this.array);
  5060. };
  5061. process.title = 'browser';
  5062. process.browser = true;
  5063. process.env = {};
  5064. process.argv = [];
  5065. process.version = ''; // empty string to avoid regexp issues
  5066. process.versions = {};
  5067. function noop() {}
  5068. process.on = noop;
  5069. process.addListener = noop;
  5070. process.once = noop;
  5071. process.off = noop;
  5072. process.removeListener = noop;
  5073. process.removeAllListeners = noop;
  5074. process.emit = noop;
  5075. process.prependListener = noop;
  5076. process.prependOnceListener = noop;
  5077. process.listeners = function (name) { return [] }
  5078. process.binding = function (name) {
  5079. throw new Error('process.binding is not supported');
  5080. };
  5081. process.cwd = function () { return '/' };
  5082. process.chdir = function (dir) {
  5083. throw new Error('process.chdir is not supported');
  5084. };
  5085. process.umask = function() { return 0; };
  5086. /***/ }),
  5087. /***/ "./node_modules/riot/riot.esm.js":
  5088. /*!***************************************!*\
  5089. !*** ./node_modules/riot/riot.esm.js ***!
  5090. \***************************************/
  5091. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  5092. "use strict";
  5093. __webpack_require__.r(__webpack_exports__);
  5094. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  5095. /* harmony export */ "__": () => (/* binding */ __),
  5096. /* harmony export */ "component": () => (/* binding */ component),
  5097. /* harmony export */ "install": () => (/* binding */ install),
  5098. /* harmony export */ "mount": () => (/* binding */ mount),
  5099. /* harmony export */ "pure": () => (/* binding */ pure),
  5100. /* harmony export */ "register": () => (/* binding */ register),
  5101. /* harmony export */ "uninstall": () => (/* binding */ uninstall),
  5102. /* harmony export */ "unmount": () => (/* binding */ unmount),
  5103. /* harmony export */ "unregister": () => (/* binding */ unregister),
  5104. /* harmony export */ "version": () => (/* binding */ version),
  5105. /* harmony export */ "withTypes": () => (/* binding */ withTypes)
  5106. /* harmony export */ });
  5107. /* Riot v6.0.1, @license MIT */
  5108. /**
  5109. * Convert a string from camel case to dash-case
  5110. * @param {string} string - probably a component tag name
  5111. * @returns {string} component name normalized
  5112. */
  5113. function camelToDashCase(string) {
  5114. return string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  5115. }
  5116. /**
  5117. * Convert a string containing dashes to camel case
  5118. * @param {string} string - input string
  5119. * @returns {string} my-string -> myString
  5120. */
  5121. function dashToCamelCase(string) {
  5122. return string.replace(/-(\w)/g, (_, c) => c.toUpperCase());
  5123. }
  5124. /**
  5125. * Get all the element attributes as object
  5126. * @param {HTMLElement} element - DOM node we want to parse
  5127. * @returns {Object} all the attributes found as a key value pairs
  5128. */
  5129. function DOMattributesToObject(element) {
  5130. return Array.from(element.attributes).reduce((acc, attribute) => {
  5131. acc[dashToCamelCase(attribute.name)] = attribute.value;
  5132. return acc;
  5133. }, {});
  5134. }
  5135. /**
  5136. * Move all the child nodes from a source tag to another
  5137. * @param {HTMLElement} source - source node
  5138. * @param {HTMLElement} target - target node
  5139. * @returns {undefined} it's a void method ¯\_()_/¯
  5140. */
  5141. // Ignore this helper because it's needed only for svg tags
  5142. function moveChildren(source, target) {
  5143. if (source.firstChild) {
  5144. target.appendChild(source.firstChild);
  5145. moveChildren(source, target);
  5146. }
  5147. }
  5148. /**
  5149. * Remove the child nodes from any DOM node
  5150. * @param {HTMLElement} node - target node
  5151. * @returns {undefined}
  5152. */
  5153. function cleanNode(node) {
  5154. clearChildren(node.childNodes);
  5155. }
  5156. /**
  5157. * Clear multiple children in a node
  5158. * @param {HTMLElement[]} children - direct children nodes
  5159. * @returns {undefined}
  5160. */
  5161. function clearChildren(children) {
  5162. Array.from(children).forEach(removeChild);
  5163. }
  5164. /**
  5165. * Remove a node
  5166. * @param {HTMLElement}node - node to remove
  5167. * @returns {undefined}
  5168. */
  5169. const removeChild = node => node && node.parentNode && node.parentNode.removeChild(node);
  5170. /**
  5171. * Insert before a node
  5172. * @param {HTMLElement} newNode - node to insert
  5173. * @param {HTMLElement} refNode - ref child
  5174. * @returns {undefined}
  5175. */
  5176. const insertBefore = (newNode, refNode) => refNode && refNode.parentNode && refNode.parentNode.insertBefore(newNode, refNode);
  5177. /**
  5178. * Replace a node
  5179. * @param {HTMLElement} newNode - new node to add to the DOM
  5180. * @param {HTMLElement} replaced - node to replace
  5181. * @returns {undefined}
  5182. */
  5183. const replaceChild = (newNode, replaced) => replaced && replaced.parentNode && replaced.parentNode.replaceChild(newNode, replaced);
  5184. // Riot.js constants that can be used accross more modules
  5185. const COMPONENTS_IMPLEMENTATION_MAP$1 = new Map(),
  5186. DOM_COMPONENT_INSTANCE_PROPERTY$1 = Symbol('riot-component'),
  5187. PLUGINS_SET$1 = new Set(),
  5188. IS_DIRECTIVE = 'is',
  5189. VALUE_ATTRIBUTE = 'value',
  5190. MOUNT_METHOD_KEY = 'mount',
  5191. UPDATE_METHOD_KEY = 'update',
  5192. UNMOUNT_METHOD_KEY = 'unmount',
  5193. SHOULD_UPDATE_KEY = 'shouldUpdate',
  5194. ON_BEFORE_MOUNT_KEY = 'onBeforeMount',
  5195. ON_MOUNTED_KEY = 'onMounted',
  5196. ON_BEFORE_UPDATE_KEY = 'onBeforeUpdate',
  5197. ON_UPDATED_KEY = 'onUpdated',
  5198. ON_BEFORE_UNMOUNT_KEY = 'onBeforeUnmount',
  5199. ON_UNMOUNTED_KEY = 'onUnmounted',
  5200. PROPS_KEY = 'props',
  5201. STATE_KEY = 'state',
  5202. SLOTS_KEY = 'slots',
  5203. ROOT_KEY = 'root',
  5204. IS_PURE_SYMBOL = Symbol('pure'),
  5205. IS_COMPONENT_UPDATING = Symbol('is_updating'),
  5206. PARENT_KEY_SYMBOL = Symbol('parent'),
  5207. ATTRIBUTES_KEY_SYMBOL = Symbol('attributes'),
  5208. TEMPLATE_KEY_SYMBOL = Symbol('template');
  5209. var globals = /*#__PURE__*/Object.freeze({
  5210. __proto__: null,
  5211. COMPONENTS_IMPLEMENTATION_MAP: COMPONENTS_IMPLEMENTATION_MAP$1,
  5212. DOM_COMPONENT_INSTANCE_PROPERTY: DOM_COMPONENT_INSTANCE_PROPERTY$1,
  5213. PLUGINS_SET: PLUGINS_SET$1,
  5214. IS_DIRECTIVE: IS_DIRECTIVE,
  5215. VALUE_ATTRIBUTE: VALUE_ATTRIBUTE,
  5216. MOUNT_METHOD_KEY: MOUNT_METHOD_KEY,
  5217. UPDATE_METHOD_KEY: UPDATE_METHOD_KEY,
  5218. UNMOUNT_METHOD_KEY: UNMOUNT_METHOD_KEY,
  5219. SHOULD_UPDATE_KEY: SHOULD_UPDATE_KEY,
  5220. ON_BEFORE_MOUNT_KEY: ON_BEFORE_MOUNT_KEY,
  5221. ON_MOUNTED_KEY: ON_MOUNTED_KEY,
  5222. ON_BEFORE_UPDATE_KEY: ON_BEFORE_UPDATE_KEY,
  5223. ON_UPDATED_KEY: ON_UPDATED_KEY,
  5224. ON_BEFORE_UNMOUNT_KEY: ON_BEFORE_UNMOUNT_KEY,
  5225. ON_UNMOUNTED_KEY: ON_UNMOUNTED_KEY,
  5226. PROPS_KEY: PROPS_KEY,
  5227. STATE_KEY: STATE_KEY,
  5228. SLOTS_KEY: SLOTS_KEY,
  5229. ROOT_KEY: ROOT_KEY,
  5230. IS_PURE_SYMBOL: IS_PURE_SYMBOL,
  5231. IS_COMPONENT_UPDATING: IS_COMPONENT_UPDATING,
  5232. PARENT_KEY_SYMBOL: PARENT_KEY_SYMBOL,
  5233. ATTRIBUTES_KEY_SYMBOL: ATTRIBUTES_KEY_SYMBOL,
  5234. TEMPLATE_KEY_SYMBOL: TEMPLATE_KEY_SYMBOL
  5235. });
  5236. const EACH = 0;
  5237. const IF = 1;
  5238. const SIMPLE = 2;
  5239. const TAG = 3;
  5240. const SLOT = 4;
  5241. var bindingTypes = {
  5242. EACH,
  5243. IF,
  5244. SIMPLE,
  5245. TAG,
  5246. SLOT
  5247. };
  5248. const ATTRIBUTE = 0;
  5249. const EVENT = 1;
  5250. const TEXT = 2;
  5251. const VALUE = 3;
  5252. var expressionTypes = {
  5253. ATTRIBUTE,
  5254. EVENT,
  5255. TEXT,
  5256. VALUE
  5257. };
  5258. const HEAD_SYMBOL = Symbol('head');
  5259. const TAIL_SYMBOL = Symbol('tail');
  5260. /**
  5261. * Create the <template> fragments text nodes
  5262. * @return {Object} {{head: Text, tail: Text}}
  5263. */
  5264. function createHeadTailPlaceholders() {
  5265. const head = document.createTextNode('');
  5266. const tail = document.createTextNode('');
  5267. head[HEAD_SYMBOL] = true;
  5268. tail[TAIL_SYMBOL] = true;
  5269. return {
  5270. head,
  5271. tail
  5272. };
  5273. }
  5274. /**
  5275. * Create the template meta object in case of <template> fragments
  5276. * @param {TemplateChunk} componentTemplate - template chunk object
  5277. * @returns {Object} the meta property that will be passed to the mount function of the TemplateChunk
  5278. */
  5279. function createTemplateMeta(componentTemplate) {
  5280. const fragment = componentTemplate.dom.cloneNode(true);
  5281. const {
  5282. head,
  5283. tail
  5284. } = createHeadTailPlaceholders();
  5285. return {
  5286. avoidDOMInjection: true,
  5287. fragment,
  5288. head,
  5289. tail,
  5290. children: [head, ...Array.from(fragment.childNodes), tail]
  5291. };
  5292. }
  5293. /**
  5294. * Helper function to set an immutable property
  5295. * @param {Object} source - object where the new property will be set
  5296. * @param {string} key - object key where the new property will be stored
  5297. * @param {*} value - value of the new property
  5298. * @param {Object} options - set the propery overriding the default options
  5299. * @returns {Object} - the original object modified
  5300. */
  5301. function defineProperty(source, key, value, options) {
  5302. if (options === void 0) {
  5303. options = {};
  5304. }
  5305. /* eslint-disable fp/no-mutating-methods */
  5306. Object.defineProperty(source, key, Object.assign({
  5307. value,
  5308. enumerable: false,
  5309. writable: false,
  5310. configurable: true
  5311. }, options));
  5312. /* eslint-enable fp/no-mutating-methods */
  5313. return source;
  5314. }
  5315. /**
  5316. * Define multiple properties on a target object
  5317. * @param {Object} source - object where the new properties will be set
  5318. * @param {Object} properties - object containing as key pair the key + value properties
  5319. * @param {Object} options - set the propery overriding the default options
  5320. * @returns {Object} the original object modified
  5321. */
  5322. function defineProperties(source, properties, options) {
  5323. Object.entries(properties).forEach(_ref => {
  5324. let [key, value] = _ref;
  5325. defineProperty(source, key, value, options);
  5326. });
  5327. return source;
  5328. }
  5329. /**
  5330. * Define default properties if they don't exist on the source object
  5331. * @param {Object} source - object that will receive the default properties
  5332. * @param {Object} defaults - object containing additional optional keys
  5333. * @returns {Object} the original object received enhanced
  5334. */
  5335. function defineDefaults(source, defaults) {
  5336. Object.entries(defaults).forEach(_ref2 => {
  5337. let [key, value] = _ref2;
  5338. if (!source[key]) source[key] = value;
  5339. });
  5340. return source;
  5341. }
  5342. /**
  5343. * Get the current <template> fragment children located in between the head and tail comments
  5344. * @param {Comment} head - head comment node
  5345. * @param {Comment} tail - tail comment node
  5346. * @return {Array[]} children list of the nodes found in this template fragment
  5347. */
  5348. function getFragmentChildren(_ref) {
  5349. let {
  5350. head,
  5351. tail
  5352. } = _ref;
  5353. const nodes = walkNodes([head], head.nextSibling, n => n === tail, false);
  5354. nodes.push(tail);
  5355. return nodes;
  5356. }
  5357. /**
  5358. * Recursive function to walk all the <template> children nodes
  5359. * @param {Array[]} children - children nodes collection
  5360. * @param {ChildNode} node - current node
  5361. * @param {Function} check - exit function check
  5362. * @param {boolean} isFilterActive - filter flag to skip nodes managed by other bindings
  5363. * @returns {Array[]} children list of the nodes found in this template fragment
  5364. */
  5365. function walkNodes(children, node, check, isFilterActive) {
  5366. const {
  5367. nextSibling
  5368. } = node; // filter tail and head nodes together with all the nodes in between
  5369. // this is needed only to fix a really ugly edge case https://github.com/riot/riot/issues/2892
  5370. if (!isFilterActive && !node[HEAD_SYMBOL] && !node[TAIL_SYMBOL]) {
  5371. children.push(node);
  5372. }
  5373. if (!nextSibling || check(node)) return children;
  5374. return walkNodes(children, nextSibling, check, // activate the filters to skip nodes between <template> fragments that will be managed by other bindings
  5375. isFilterActive && !node[TAIL_SYMBOL] || nextSibling[HEAD_SYMBOL]);
  5376. }
  5377. /**
  5378. * Quick type checking
  5379. * @param {*} element - anything
  5380. * @param {string} type - type definition
  5381. * @returns {boolean} true if the type corresponds
  5382. */
  5383. function checkType(element, type) {
  5384. return typeof element === type;
  5385. }
  5386. /**
  5387. * Check if an element is part of an svg
  5388. * @param {HTMLElement} el - element to check
  5389. * @returns {boolean} true if we are in an svg context
  5390. */
  5391. function isSvg(el) {
  5392. const owner = el.ownerSVGElement;
  5393. return !!owner || owner === null;
  5394. }
  5395. /**
  5396. * Check if an element is a template tag
  5397. * @param {HTMLElement} el - element to check
  5398. * @returns {boolean} true if it's a <template>
  5399. */
  5400. function isTemplate(el) {
  5401. return el.tagName.toLowerCase() === 'template';
  5402. }
  5403. /**
  5404. * Check that will be passed if its argument is a function
  5405. * @param {*} value - value to check
  5406. * @returns {boolean} - true if the value is a function
  5407. */
  5408. function isFunction(value) {
  5409. return checkType(value, 'function');
  5410. }
  5411. /**
  5412. * Check if a value is a Boolean
  5413. * @param {*} value - anything
  5414. * @returns {boolean} true only for the value is a boolean
  5415. */
  5416. function isBoolean(value) {
  5417. return checkType(value, 'boolean');
  5418. }
  5419. /**
  5420. * Check if a value is an Object
  5421. * @param {*} value - anything
  5422. * @returns {boolean} true only for the value is an object
  5423. */
  5424. function isObject(value) {
  5425. return !isNil(value) && value.constructor === Object;
  5426. }
  5427. /**
  5428. * Check if a value is null or undefined
  5429. * @param {*} value - anything
  5430. * @returns {boolean} true only for the 'undefined' and 'null' types
  5431. */
  5432. function isNil(value) {
  5433. return value === null || value === undefined;
  5434. }
  5435. /**
  5436. * ISC License
  5437. *
  5438. * Copyright (c) 2020, Andrea Giammarchi, @WebReflection
  5439. *
  5440. * Permission to use, copy, modify, and/or distribute this software for any
  5441. * purpose with or without fee is hereby granted, provided that the above
  5442. * copyright notice and this permission notice appear in all copies.
  5443. *
  5444. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  5445. * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  5446. * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  5447. * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  5448. * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  5449. * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  5450. * PERFORMANCE OF THIS SOFTWARE.
  5451. */
  5452. // fork of https://github.com/WebReflection/udomdiff version 1.1.0
  5453. // due to https://github.com/WebReflection/udomdiff/pull/2
  5454. /* eslint-disable */
  5455. /**
  5456. * @param {Node[]} a The list of current/live children
  5457. * @param {Node[]} b The list of future children
  5458. * @param {(entry: Node, action: number) => Node} get
  5459. * The callback invoked per each entry related DOM operation.
  5460. * @param {Node} [before] The optional node used as anchor to insert before.
  5461. * @returns {Node[]} The same list of future children.
  5462. */
  5463. var udomdiff = ((a, b, get, before) => {
  5464. const bLength = b.length;
  5465. let aEnd = a.length;
  5466. let bEnd = bLength;
  5467. let aStart = 0;
  5468. let bStart = 0;
  5469. let map = null;
  5470. while (aStart < aEnd || bStart < bEnd) {
  5471. // append head, tail, or nodes in between: fast path
  5472. if (aEnd === aStart) {
  5473. // we could be in a situation where the rest of nodes that
  5474. // need to be added are not at the end, and in such case
  5475. // the node to `insertBefore`, if the index is more than 0
  5476. // must be retrieved, otherwise it's gonna be the first item.
  5477. const node = bEnd < bLength ? bStart ? get(b[bStart - 1], -0).nextSibling : get(b[bEnd - bStart], 0) : before;
  5478. while (bStart < bEnd) insertBefore(get(b[bStart++], 1), node);
  5479. } // remove head or tail: fast path
  5480. else if (bEnd === bStart) {
  5481. while (aStart < aEnd) {
  5482. // remove the node only if it's unknown or not live
  5483. if (!map || !map.has(a[aStart])) removeChild(get(a[aStart], -1));
  5484. aStart++;
  5485. }
  5486. } // same node: fast path
  5487. else if (a[aStart] === b[bStart]) {
  5488. aStart++;
  5489. bStart++;
  5490. } // same tail: fast path
  5491. else if (a[aEnd - 1] === b[bEnd - 1]) {
  5492. aEnd--;
  5493. bEnd--;
  5494. } // The once here single last swap "fast path" has been removed in v1.1.0
  5495. // https://github.com/WebReflection/udomdiff/blob/single-final-swap/esm/index.js#L69-L85
  5496. // reverse swap: also fast path
  5497. else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {
  5498. // this is a "shrink" operation that could happen in these cases:
  5499. // [1, 2, 3, 4, 5]
  5500. // [1, 4, 3, 2, 5]
  5501. // or asymmetric too
  5502. // [1, 2, 3, 4, 5]
  5503. // [1, 2, 3, 5, 6, 4]
  5504. const node = get(a[--aEnd], -1).nextSibling;
  5505. insertBefore(get(b[bStart++], 1), get(a[aStart++], -1).nextSibling);
  5506. insertBefore(get(b[--bEnd], 1), node); // mark the future index as identical (yeah, it's dirty, but cheap 👍)
  5507. // The main reason to do this, is that when a[aEnd] will be reached,
  5508. // the loop will likely be on the fast path, as identical to b[bEnd].
  5509. // In the best case scenario, the next loop will skip the tail,
  5510. // but in the worst one, this node will be considered as already
  5511. // processed, bailing out pretty quickly from the map index check
  5512. a[aEnd] = b[bEnd];
  5513. } // map based fallback, "slow" path
  5514. else {
  5515. // the map requires an O(bEnd - bStart) operation once
  5516. // to store all future nodes indexes for later purposes.
  5517. // In the worst case scenario, this is a full O(N) cost,
  5518. // and such scenario happens at least when all nodes are different,
  5519. // but also if both first and last items of the lists are different
  5520. if (!map) {
  5521. map = new Map();
  5522. let i = bStart;
  5523. while (i < bEnd) map.set(b[i], i++);
  5524. } // if it's a future node, hence it needs some handling
  5525. if (map.has(a[aStart])) {
  5526. // grab the index of such node, 'cause it might have been processed
  5527. const index = map.get(a[aStart]); // if it's not already processed, look on demand for the next LCS
  5528. if (bStart < index && index < bEnd) {
  5529. let i = aStart; // counts the amount of nodes that are the same in the future
  5530. let sequence = 1;
  5531. while (++i < aEnd && i < bEnd && map.get(a[i]) === index + sequence) sequence++; // effort decision here: if the sequence is longer than replaces
  5532. // needed to reach such sequence, which would brings again this loop
  5533. // to the fast path, prepend the difference before a sequence,
  5534. // and move only the future list index forward, so that aStart
  5535. // and bStart will be aligned again, hence on the fast path.
  5536. // An example considering aStart and bStart are both 0:
  5537. // a: [1, 2, 3, 4]
  5538. // b: [7, 1, 2, 3, 6]
  5539. // this would place 7 before 1 and, from that time on, 1, 2, and 3
  5540. // will be processed at zero cost
  5541. if (sequence > index - bStart) {
  5542. const node = get(a[aStart], 0);
  5543. while (bStart < index) insertBefore(get(b[bStart++], 1), node);
  5544. } // if the effort wasn't good enough, fallback to a replace,
  5545. // moving both source and target indexes forward, hoping that some
  5546. // similar node will be found later on, to go back to the fast path
  5547. else {
  5548. replaceChild(get(b[bStart++], 1), get(a[aStart++], -1));
  5549. }
  5550. } // otherwise move the source forward, 'cause there's nothing to do
  5551. else aStart++;
  5552. } // this node has no meaning in the future list, so it's more than safe
  5553. // to remove it, and check the next live node out instead, meaning
  5554. // that only the live list index should be forwarded
  5555. else removeChild(get(a[aStart++], -1));
  5556. }
  5557. }
  5558. return b;
  5559. });
  5560. const UNMOUNT_SCOPE = Symbol('unmount');
  5561. const EachBinding = {
  5562. // dynamic binding properties
  5563. // childrenMap: null,
  5564. // node: null,
  5565. // root: null,
  5566. // condition: null,
  5567. // evaluate: null,
  5568. // template: null,
  5569. // isTemplateTag: false,
  5570. nodes: [],
  5571. // getKey: null,
  5572. // indexName: null,
  5573. // itemName: null,
  5574. // afterPlaceholder: null,
  5575. // placeholder: null,
  5576. // API methods
  5577. mount(scope, parentScope) {
  5578. return this.update(scope, parentScope);
  5579. },
  5580. update(scope, parentScope) {
  5581. const {
  5582. placeholder,
  5583. nodes,
  5584. childrenMap
  5585. } = this;
  5586. const collection = scope === UNMOUNT_SCOPE ? null : this.evaluate(scope);
  5587. const items = collection ? Array.from(collection) : []; // prepare the diffing
  5588. const {
  5589. newChildrenMap,
  5590. batches,
  5591. futureNodes
  5592. } = createPatch(items, scope, parentScope, this); // patch the DOM only if there are new nodes
  5593. udomdiff(nodes, futureNodes, patch(Array.from(childrenMap.values()), parentScope), placeholder); // trigger the mounts and the updates
  5594. batches.forEach(fn => fn()); // update the children map
  5595. this.childrenMap = newChildrenMap;
  5596. this.nodes = futureNodes; // make sure that the loop edge nodes are marked
  5597. markEdgeNodes(this.nodes);
  5598. return this;
  5599. },
  5600. unmount(scope, parentScope) {
  5601. this.update(UNMOUNT_SCOPE, parentScope);
  5602. return this;
  5603. }
  5604. };
  5605. /**
  5606. * Patch the DOM while diffing
  5607. * @param {any[]} redundant - list of all the children (template, nodes, context) added via each
  5608. * @param {*} parentScope - scope of the parent template
  5609. * @returns {Function} patch function used by domdiff
  5610. */
  5611. function patch(redundant, parentScope) {
  5612. return (item, info) => {
  5613. if (info < 0) {
  5614. // get the last element added to the childrenMap saved previously
  5615. const element = redundant[redundant.length - 1];
  5616. if (element) {
  5617. // get the nodes and the template in stored in the last child of the childrenMap
  5618. const {
  5619. template,
  5620. nodes,
  5621. context
  5622. } = element; // remove the last node (notice <template> tags might have more children nodes)
  5623. nodes.pop(); // notice that we pass null as last argument because
  5624. // the root node and its children will be removed by domdiff
  5625. if (!nodes.length) {
  5626. // we have cleared all the children nodes and we can unmount this template
  5627. redundant.pop();
  5628. template.unmount(context, parentScope, null);
  5629. }
  5630. }
  5631. }
  5632. return item;
  5633. };
  5634. }
  5635. /**
  5636. * Check whether a template must be filtered from a loop
  5637. * @param {Function} condition - filter function
  5638. * @param {Object} context - argument passed to the filter function
  5639. * @returns {boolean} true if this item should be skipped
  5640. */
  5641. function mustFilterItem(condition, context) {
  5642. return condition ? !condition(context) : false;
  5643. }
  5644. /**
  5645. * Extend the scope of the looped template
  5646. * @param {Object} scope - current template scope
  5647. * @param {Object} options - options
  5648. * @param {string} options.itemName - key to identify the looped item in the new context
  5649. * @param {string} options.indexName - key to identify the index of the looped item
  5650. * @param {number} options.index - current index
  5651. * @param {*} options.item - collection item looped
  5652. * @returns {Object} enhanced scope object
  5653. */
  5654. function extendScope(scope, _ref) {
  5655. let {
  5656. itemName,
  5657. indexName,
  5658. index,
  5659. item
  5660. } = _ref;
  5661. defineProperty(scope, itemName, item);
  5662. if (indexName) defineProperty(scope, indexName, index);
  5663. return scope;
  5664. }
  5665. /**
  5666. * Mark the first and last nodes in order to ignore them in case we need to retrieve the <template> fragment nodes
  5667. * @param {Array[]} nodes - each binding nodes list
  5668. * @returns {undefined} void function
  5669. */
  5670. function markEdgeNodes(nodes) {
  5671. const first = nodes[0];
  5672. const last = nodes[nodes.length - 1];
  5673. if (first) first[HEAD_SYMBOL] = true;
  5674. if (last) last[TAIL_SYMBOL] = true;
  5675. }
  5676. /**
  5677. * Loop the current template items
  5678. * @param {Array} items - expression collection value
  5679. * @param {*} scope - template scope
  5680. * @param {*} parentScope - scope of the parent template
  5681. * @param {EachBinding} binding - each binding object instance
  5682. * @returns {Object} data
  5683. * @returns {Map} data.newChildrenMap - a Map containing the new children template structure
  5684. * @returns {Array} data.batches - array containing the template lifecycle functions to trigger
  5685. * @returns {Array} data.futureNodes - array containing the nodes we need to diff
  5686. */
  5687. function createPatch(items, scope, parentScope, binding) {
  5688. const {
  5689. condition,
  5690. template,
  5691. childrenMap,
  5692. itemName,
  5693. getKey,
  5694. indexName,
  5695. root,
  5696. isTemplateTag
  5697. } = binding;
  5698. const newChildrenMap = new Map();
  5699. const batches = [];
  5700. const futureNodes = [];
  5701. items.forEach((item, index) => {
  5702. const context = extendScope(Object.create(scope), {
  5703. itemName,
  5704. indexName,
  5705. index,
  5706. item
  5707. });
  5708. const key = getKey ? getKey(context) : index;
  5709. const oldItem = childrenMap.get(key);
  5710. const nodes = [];
  5711. if (mustFilterItem(condition, context)) {
  5712. return;
  5713. }
  5714. const mustMount = !oldItem;
  5715. const componentTemplate = oldItem ? oldItem.template : template.clone();
  5716. const el = componentTemplate.el || root.cloneNode();
  5717. const meta = isTemplateTag && mustMount ? createTemplateMeta(componentTemplate) : componentTemplate.meta;
  5718. if (mustMount) {
  5719. batches.push(() => componentTemplate.mount(el, context, parentScope, meta));
  5720. } else {
  5721. batches.push(() => componentTemplate.update(context, parentScope));
  5722. } // create the collection of nodes to update or to add
  5723. // in case of template tags we need to add all its children nodes
  5724. if (isTemplateTag) {
  5725. nodes.push(...(mustMount ? meta.children : getFragmentChildren(meta)));
  5726. } else {
  5727. nodes.push(el);
  5728. } // delete the old item from the children map
  5729. childrenMap.delete(key);
  5730. futureNodes.push(...nodes); // update the children map
  5731. newChildrenMap.set(key, {
  5732. nodes,
  5733. template: componentTemplate,
  5734. context,
  5735. index
  5736. });
  5737. });
  5738. return {
  5739. newChildrenMap,
  5740. batches,
  5741. futureNodes
  5742. };
  5743. }
  5744. function create$6(node, _ref2) {
  5745. let {
  5746. evaluate,
  5747. condition,
  5748. itemName,
  5749. indexName,
  5750. getKey,
  5751. template
  5752. } = _ref2;
  5753. const placeholder = document.createTextNode('');
  5754. const root = node.cloneNode();
  5755. insertBefore(placeholder, node);
  5756. removeChild(node);
  5757. return Object.assign({}, EachBinding, {
  5758. childrenMap: new Map(),
  5759. node,
  5760. root,
  5761. condition,
  5762. evaluate,
  5763. isTemplateTag: isTemplate(root),
  5764. template: template.createDOM(node),
  5765. getKey,
  5766. indexName,
  5767. itemName,
  5768. placeholder
  5769. });
  5770. }
  5771. /**
  5772. * Binding responsible for the `if` directive
  5773. */
  5774. const IfBinding = {
  5775. // dynamic binding properties
  5776. // node: null,
  5777. // evaluate: null,
  5778. // isTemplateTag: false,
  5779. // placeholder: null,
  5780. // template: null,
  5781. // API methods
  5782. mount(scope, parentScope) {
  5783. return this.update(scope, parentScope);
  5784. },
  5785. update(scope, parentScope) {
  5786. const value = !!this.evaluate(scope);
  5787. const mustMount = !this.value && value;
  5788. const mustUnmount = this.value && !value;
  5789. const mount = () => {
  5790. const pristine = this.node.cloneNode();
  5791. insertBefore(pristine, this.placeholder);
  5792. this.template = this.template.clone();
  5793. this.template.mount(pristine, scope, parentScope);
  5794. };
  5795. switch (true) {
  5796. case mustMount:
  5797. mount();
  5798. break;
  5799. case mustUnmount:
  5800. this.unmount(scope);
  5801. break;
  5802. default:
  5803. if (value) this.template.update(scope, parentScope);
  5804. }
  5805. this.value = value;
  5806. return this;
  5807. },
  5808. unmount(scope, parentScope) {
  5809. this.template.unmount(scope, parentScope, true);
  5810. return this;
  5811. }
  5812. };
  5813. function create$5(node, _ref) {
  5814. let {
  5815. evaluate,
  5816. template
  5817. } = _ref;
  5818. const placeholder = document.createTextNode('');
  5819. insertBefore(placeholder, node);
  5820. removeChild(node);
  5821. return Object.assign({}, IfBinding, {
  5822. node,
  5823. evaluate,
  5824. placeholder,
  5825. template: template.createDOM(node)
  5826. });
  5827. }
  5828. /**
  5829. * Throw an error with a descriptive message
  5830. * @param { string } message - error message
  5831. * @returns { undefined } hoppla.. at this point the program should stop working
  5832. */
  5833. function panic(message) {
  5834. throw new Error(message);
  5835. }
  5836. /**
  5837. * Returns the memoized (cached) function.
  5838. * // borrowed from https://www.30secondsofcode.org/js/s/memoize
  5839. * @param {Function} fn - function to memoize
  5840. * @returns {Function} memoize function
  5841. */
  5842. function memoize(fn) {
  5843. const cache = new Map();
  5844. const cached = val => {
  5845. return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);
  5846. };
  5847. cached.cache = cache;
  5848. return cached;
  5849. }
  5850. /**
  5851. * Evaluate a list of attribute expressions
  5852. * @param {Array} attributes - attribute expressions generated by the riot compiler
  5853. * @returns {Object} key value pairs with the result of the computation
  5854. */
  5855. function evaluateAttributeExpressions(attributes) {
  5856. return attributes.reduce((acc, attribute) => {
  5857. const {
  5858. value,
  5859. type
  5860. } = attribute;
  5861. switch (true) {
  5862. // spread attribute
  5863. case !attribute.name && type === ATTRIBUTE:
  5864. return Object.assign({}, acc, value);
  5865. // value attribute
  5866. case type === VALUE:
  5867. acc.value = attribute.value;
  5868. break;
  5869. // normal attributes
  5870. default:
  5871. acc[dashToCamelCase(attribute.name)] = attribute.value;
  5872. }
  5873. return acc;
  5874. }, {});
  5875. }
  5876. const ElementProto = typeof Element === 'undefined' ? {} : Element.prototype;
  5877. const isNativeHtmlProperty = memoize(name => ElementProto.hasOwnProperty(name)); // eslint-disable-line
  5878. /**
  5879. * Add all the attributes provided
  5880. * @param {HTMLElement} node - target node
  5881. * @param {Object} attributes - object containing the attributes names and values
  5882. * @returns {undefined} sorry it's a void function :(
  5883. */
  5884. function setAllAttributes(node, attributes) {
  5885. Object.entries(attributes).forEach(_ref => {
  5886. let [name, value] = _ref;
  5887. return attributeExpression(node, {
  5888. name
  5889. }, value);
  5890. });
  5891. }
  5892. /**
  5893. * Remove all the attributes provided
  5894. * @param {HTMLElement} node - target node
  5895. * @param {Object} newAttributes - object containing all the new attribute names
  5896. * @param {Object} oldAttributes - object containing all the old attribute names
  5897. * @returns {undefined} sorry it's a void function :(
  5898. */
  5899. function removeAllAttributes(node, newAttributes, oldAttributes) {
  5900. const newKeys = newAttributes ? Object.keys(newAttributes) : [];
  5901. Object.keys(oldAttributes).filter(name => !newKeys.includes(name)).forEach(attribute => node.removeAttribute(attribute));
  5902. }
  5903. /**
  5904. * Check whether the attribute value can be rendered
  5905. * @param {*} value - expression value
  5906. * @returns {boolean} true if we can render this attribute value
  5907. */
  5908. function canRenderAttribute(value) {
  5909. return value === true || ['string', 'number'].includes(typeof value);
  5910. }
  5911. /**
  5912. * Check whether the attribute should be removed
  5913. * @param {*} value - expression value
  5914. * @returns {boolean} boolean - true if the attribute can be removed}
  5915. */
  5916. function shouldRemoveAttribute(value) {
  5917. return !value && value !== 0;
  5918. }
  5919. /**
  5920. * This methods handles the DOM attributes updates
  5921. * @param {HTMLElement} node - target node
  5922. * @param {Object} expression - expression object
  5923. * @param {string} expression.name - attribute name
  5924. * @param {*} value - new expression value
  5925. * @param {*} oldValue - the old expression cached value
  5926. * @returns {undefined}
  5927. */
  5928. function attributeExpression(node, _ref2, value, oldValue) {
  5929. let {
  5930. name
  5931. } = _ref2;
  5932. // is it a spread operator? {...attributes}
  5933. if (!name) {
  5934. if (oldValue) {
  5935. // remove all the old attributes
  5936. removeAllAttributes(node, value, oldValue);
  5937. } // is the value still truthy?
  5938. if (value) {
  5939. setAllAttributes(node, value);
  5940. }
  5941. return;
  5942. } // handle boolean attributes
  5943. if (!isNativeHtmlProperty(name) && (isBoolean(value) || isObject(value) || isFunction(value))) {
  5944. node[name] = value;
  5945. }
  5946. if (shouldRemoveAttribute(value)) {
  5947. node.removeAttribute(name);
  5948. } else if (canRenderAttribute(value)) {
  5949. node.setAttribute(name, normalizeValue(name, value));
  5950. }
  5951. }
  5952. /**
  5953. * Get the value as string
  5954. * @param {string} name - attribute name
  5955. * @param {*} value - user input value
  5956. * @returns {string} input value as string
  5957. */
  5958. function normalizeValue(name, value) {
  5959. // be sure that expressions like selected={ true } will be always rendered as selected='selected'
  5960. return value === true ? name : value;
  5961. }
  5962. const RE_EVENTS_PREFIX = /^on/;
  5963. 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
  5964. const EventListener = {
  5965. handleEvent(event) {
  5966. this[event.type](event);
  5967. }
  5968. };
  5969. const ListenersWeakMap = new WeakMap();
  5970. const createListener = node => {
  5971. const listener = Object.create(EventListener);
  5972. ListenersWeakMap.set(node, listener);
  5973. return listener;
  5974. };
  5975. /**
  5976. * Set a new event listener
  5977. * @param {HTMLElement} node - target node
  5978. * @param {Object} expression - expression object
  5979. * @param {string} expression.name - event name
  5980. * @param {*} value - new expression value
  5981. * @returns {value} the callback just received
  5982. */
  5983. function eventExpression(node, _ref, value) {
  5984. let {
  5985. name
  5986. } = _ref;
  5987. const normalizedEventName = name.replace(RE_EVENTS_PREFIX, '');
  5988. const eventListener = ListenersWeakMap.get(node) || createListener(node);
  5989. const [callback, options] = getCallbackAndOptions(value);
  5990. const handler = eventListener[normalizedEventName];
  5991. const mustRemoveEvent = handler && !callback;
  5992. const mustAddEvent = callback && !handler;
  5993. if (mustRemoveEvent) {
  5994. node.removeEventListener(normalizedEventName, eventListener);
  5995. }
  5996. if (mustAddEvent) {
  5997. node.addEventListener(normalizedEventName, eventListener, options);
  5998. }
  5999. eventListener[normalizedEventName] = callback;
  6000. }
  6001. /**
  6002. * Normalize the user value in order to render a empty string in case of falsy values
  6003. * @param {*} value - user input value
  6004. * @returns {string} hopefully a string
  6005. */
  6006. function normalizeStringValue(value) {
  6007. return isNil(value) ? '' : value;
  6008. }
  6009. /**
  6010. * Get the the target text node to update or create one from of a comment node
  6011. * @param {HTMLElement} node - any html element containing childNodes
  6012. * @param {number} childNodeIndex - index of the text node in the childNodes list
  6013. * @returns {Text} the text node to update
  6014. */
  6015. const getTextNode = (node, childNodeIndex) => {
  6016. const target = node.childNodes[childNodeIndex];
  6017. if (target.nodeType === Node.COMMENT_NODE) {
  6018. const textNode = document.createTextNode('');
  6019. node.replaceChild(textNode, target);
  6020. return textNode;
  6021. }
  6022. return target;
  6023. };
  6024. /**
  6025. * This methods handles a simple text expression update
  6026. * @param {HTMLElement} node - target node
  6027. * @param {Object} data - expression object
  6028. * @param {*} value - new expression value
  6029. * @returns {undefined}
  6030. */
  6031. function textExpression(node, data, value) {
  6032. node.data = normalizeStringValue(value);
  6033. }
  6034. /**
  6035. * This methods handles the input fileds value updates
  6036. * @param {HTMLElement} node - target node
  6037. * @param {Object} expression - expression object
  6038. * @param {*} value - new expression value
  6039. * @returns {undefined}
  6040. */
  6041. function valueExpression(node, expression, value) {
  6042. node.value = normalizeStringValue(value);
  6043. }
  6044. var expressions = {
  6045. [ATTRIBUTE]: attributeExpression,
  6046. [EVENT]: eventExpression,
  6047. [TEXT]: textExpression,
  6048. [VALUE]: valueExpression
  6049. };
  6050. const Expression = {
  6051. // Static props
  6052. // node: null,
  6053. // value: null,
  6054. // API methods
  6055. /**
  6056. * Mount the expression evaluating its initial value
  6057. * @param {*} scope - argument passed to the expression to evaluate its current values
  6058. * @returns {Expression} self
  6059. */
  6060. mount(scope) {
  6061. // hopefully a pure function
  6062. this.value = this.evaluate(scope); // IO() DOM updates
  6063. apply(this, this.value);
  6064. return this;
  6065. },
  6066. /**
  6067. * Update the expression if its value changed
  6068. * @param {*} scope - argument passed to the expression to evaluate its current values
  6069. * @returns {Expression} self
  6070. */
  6071. update(scope) {
  6072. // pure function
  6073. const value = this.evaluate(scope);
  6074. if (this.value !== value) {
  6075. // IO() DOM updates
  6076. apply(this, value);
  6077. this.value = value;
  6078. }
  6079. return this;
  6080. },
  6081. /**
  6082. * Expression teardown method
  6083. * @returns {Expression} self
  6084. */
  6085. unmount() {
  6086. // unmount only the event handling expressions
  6087. if (this.type === EVENT) apply(this, null);
  6088. return this;
  6089. }
  6090. };
  6091. /**
  6092. * IO() function to handle the DOM updates
  6093. * @param {Expression} expression - expression object
  6094. * @param {*} value - current expression value
  6095. * @returns {undefined}
  6096. */
  6097. function apply(expression, value) {
  6098. return expressions[expression.type](expression.node, expression, value, expression.value);
  6099. }
  6100. function create$4(node, data) {
  6101. return Object.assign({}, Expression, data, {
  6102. node: data.type === TEXT ? getTextNode(node, data.childNodeIndex) : node
  6103. });
  6104. }
  6105. /**
  6106. * Create a flat object having as keys a list of methods that if dispatched will propagate
  6107. * on the whole collection
  6108. * @param {Array} collection - collection to iterate
  6109. * @param {Array<string>} methods - methods to execute on each item of the collection
  6110. * @param {*} context - context returned by the new methods created
  6111. * @returns {Object} a new object to simplify the the nested methods dispatching
  6112. */
  6113. function flattenCollectionMethods(collection, methods, context) {
  6114. return methods.reduce((acc, method) => {
  6115. return Object.assign({}, acc, {
  6116. [method]: scope => {
  6117. return collection.map(item => item[method](scope)) && context;
  6118. }
  6119. });
  6120. }, {});
  6121. }
  6122. function create$3(node, _ref) {
  6123. let {
  6124. expressions
  6125. } = _ref;
  6126. return Object.assign({}, flattenCollectionMethods(expressions.map(expression => create$4(node, expression)), ['mount', 'update', 'unmount']));
  6127. }
  6128. function extendParentScope(attributes, scope, parentScope) {
  6129. if (!attributes || !attributes.length) return parentScope;
  6130. const expressions = attributes.map(attr => Object.assign({}, attr, {
  6131. value: attr.evaluate(scope)
  6132. }));
  6133. return Object.assign(Object.create(parentScope || null), evaluateAttributeExpressions(expressions));
  6134. } // this function is only meant to fix an edge case
  6135. // https://github.com/riot/riot/issues/2842
  6136. const getRealParent = (scope, parentScope) => scope[PARENT_KEY_SYMBOL] || parentScope;
  6137. const SlotBinding = {
  6138. // dynamic binding properties
  6139. // node: null,
  6140. // name: null,
  6141. attributes: [],
  6142. // template: null,
  6143. getTemplateScope(scope, parentScope) {
  6144. return extendParentScope(this.attributes, scope, parentScope);
  6145. },
  6146. // API methods
  6147. mount(scope, parentScope) {
  6148. const templateData = scope.slots ? scope.slots.find(_ref => {
  6149. let {
  6150. id
  6151. } = _ref;
  6152. return id === this.name;
  6153. }) : false;
  6154. const {
  6155. parentNode
  6156. } = this.node;
  6157. const realParent = getRealParent(scope, parentScope);
  6158. this.template = templateData && create(templateData.html, templateData.bindings).createDOM(parentNode);
  6159. if (this.template) {
  6160. cleanNode(this.node);
  6161. this.template.mount(this.node, this.getTemplateScope(scope, realParent), realParent);
  6162. this.template.children = Array.from(this.node.childNodes);
  6163. }
  6164. moveSlotInnerContent(this.node);
  6165. removeChild(this.node);
  6166. return this;
  6167. },
  6168. update(scope, parentScope) {
  6169. if (this.template) {
  6170. const realParent = getRealParent(scope, parentScope);
  6171. this.template.update(this.getTemplateScope(scope, realParent), realParent);
  6172. }
  6173. return this;
  6174. },
  6175. unmount(scope, parentScope, mustRemoveRoot) {
  6176. if (this.template) {
  6177. this.template.unmount(this.getTemplateScope(scope, parentScope), null, mustRemoveRoot);
  6178. }
  6179. return this;
  6180. }
  6181. };
  6182. /**
  6183. * Move the inner content of the slots outside of them
  6184. * @param {HTMLElement} slot - slot node
  6185. * @returns {undefined} it's a void method ¯\_()_/¯
  6186. */
  6187. function moveSlotInnerContent(slot) {
  6188. const child = slot && slot.firstChild;
  6189. if (!child) return;
  6190. insertBefore(child, slot);
  6191. moveSlotInnerContent(slot);
  6192. }
  6193. /**
  6194. * Create a single slot binding
  6195. * @param {HTMLElement} node - slot node
  6196. * @param {string} name - slot id
  6197. * @param {AttributeExpressionData[]} attributes - slot attributes
  6198. * @returns {Object} Slot binding object
  6199. */
  6200. function createSlot(node, _ref2) {
  6201. let {
  6202. name,
  6203. attributes
  6204. } = _ref2;
  6205. return Object.assign({}, SlotBinding, {
  6206. attributes,
  6207. node,
  6208. name
  6209. });
  6210. }
  6211. /**
  6212. * Create a new tag object if it was registered before, otherwise fallback to the simple
  6213. * template chunk
  6214. * @param {Function} component - component factory function
  6215. * @param {Array<Object>} slots - array containing the slots markup
  6216. * @param {Array} attributes - dynamic attributes that will be received by the tag element
  6217. * @returns {TagImplementation|TemplateChunk} a tag implementation or a template chunk as fallback
  6218. */
  6219. function getTag(component, slots, attributes) {
  6220. if (slots === void 0) {
  6221. slots = [];
  6222. }
  6223. if (attributes === void 0) {
  6224. attributes = [];
  6225. }
  6226. // if this tag was registered before we will return its implementation
  6227. if (component) {
  6228. return component({
  6229. slots,
  6230. attributes
  6231. });
  6232. } // otherwise we return a template chunk
  6233. return create(slotsToMarkup(slots), [...slotBindings(slots), {
  6234. // the attributes should be registered as binding
  6235. // if we fallback to a normal template chunk
  6236. expressions: attributes.map(attr => {
  6237. return Object.assign({
  6238. type: ATTRIBUTE
  6239. }, attr);
  6240. })
  6241. }]);
  6242. }
  6243. /**
  6244. * Merge all the slots bindings into a single array
  6245. * @param {Array<Object>} slots - slots collection
  6246. * @returns {Array<Bindings>} flatten bindings array
  6247. */
  6248. function slotBindings(slots) {
  6249. return slots.reduce((acc, _ref) => {
  6250. let {
  6251. bindings
  6252. } = _ref;
  6253. return acc.concat(bindings);
  6254. }, []);
  6255. }
  6256. /**
  6257. * Merge all the slots together in a single markup string
  6258. * @param {Array<Object>} slots - slots collection
  6259. * @returns {string} markup of all the slots in a single string
  6260. */
  6261. function slotsToMarkup(slots) {
  6262. return slots.reduce((acc, slot) => {
  6263. return acc + slot.html;
  6264. }, '');
  6265. }
  6266. const TagBinding = {
  6267. // dynamic binding properties
  6268. // node: null,
  6269. // evaluate: null,
  6270. // name: null,
  6271. // slots: null,
  6272. // tag: null,
  6273. // attributes: null,
  6274. // getComponent: null,
  6275. mount(scope) {
  6276. return this.update(scope);
  6277. },
  6278. update(scope, parentScope) {
  6279. const name = this.evaluate(scope); // simple update
  6280. if (name && name === this.name) {
  6281. this.tag.update(scope);
  6282. } else {
  6283. // unmount the old tag if it exists
  6284. this.unmount(scope, parentScope, true); // mount the new tag
  6285. this.name = name;
  6286. this.tag = getTag(this.getComponent(name), this.slots, this.attributes);
  6287. this.tag.mount(this.node, scope);
  6288. }
  6289. return this;
  6290. },
  6291. unmount(scope, parentScope, keepRootTag) {
  6292. if (this.tag) {
  6293. // keep the root tag
  6294. this.tag.unmount(keepRootTag);
  6295. }
  6296. return this;
  6297. }
  6298. };
  6299. function create$2(node, _ref2) {
  6300. let {
  6301. evaluate,
  6302. getComponent,
  6303. slots,
  6304. attributes
  6305. } = _ref2;
  6306. return Object.assign({}, TagBinding, {
  6307. node,
  6308. evaluate,
  6309. slots,
  6310. attributes,
  6311. getComponent
  6312. });
  6313. }
  6314. var bindings = {
  6315. [IF]: create$5,
  6316. [SIMPLE]: create$3,
  6317. [EACH]: create$6,
  6318. [TAG]: create$2,
  6319. [SLOT]: createSlot
  6320. };
  6321. /**
  6322. * Text expressions in a template tag will get childNodeIndex value normalized
  6323. * depending on the position of the <template> tag offset
  6324. * @param {Expression[]} expressions - riot expressions array
  6325. * @param {number} textExpressionsOffset - offset of the <template> tag
  6326. * @returns {Expression[]} expressions containing the text expressions normalized
  6327. */
  6328. function fixTextExpressionsOffset(expressions, textExpressionsOffset) {
  6329. return expressions.map(e => e.type === TEXT ? Object.assign({}, e, {
  6330. childNodeIndex: e.childNodeIndex + textExpressionsOffset
  6331. }) : e);
  6332. }
  6333. /**
  6334. * Bind a new expression object to a DOM node
  6335. * @param {HTMLElement} root - DOM node where to bind the expression
  6336. * @param {TagBindingData} binding - binding data
  6337. * @param {number|null} templateTagOffset - if it's defined we need to fix the text expressions childNodeIndex offset
  6338. * @returns {Binding} Binding object
  6339. */
  6340. function create$1(root, binding, templateTagOffset) {
  6341. const {
  6342. selector,
  6343. type,
  6344. redundantAttribute,
  6345. expressions
  6346. } = binding; // find the node to apply the bindings
  6347. const node = selector ? root.querySelector(selector) : root; // remove eventually additional attributes created only to select this node
  6348. if (redundantAttribute) node.removeAttribute(redundantAttribute);
  6349. const bindingExpressions = expressions || []; // init the binding
  6350. return (bindings[type] || bindings[SIMPLE])(node, Object.assign({}, binding, {
  6351. expressions: templateTagOffset && !selector ? fixTextExpressionsOffset(bindingExpressions, templateTagOffset) : bindingExpressions
  6352. }));
  6353. }
  6354. function createHTMLTree(html, root) {
  6355. const template = isTemplate(root) ? root : document.createElement('template');
  6356. template.innerHTML = html;
  6357. return template.content;
  6358. } // for svg nodes we need a bit more work
  6359. function createSVGTree(html, container) {
  6360. // create the SVGNode
  6361. const svgNode = container.ownerDocument.importNode(new window.DOMParser().parseFromString(`<svg xmlns="http://www.w3.org/2000/svg">${html}</svg>`, 'application/xml').documentElement, true);
  6362. return svgNode;
  6363. }
  6364. /**
  6365. * Create the DOM that will be injected
  6366. * @param {Object} root - DOM node to find out the context where the fragment will be created
  6367. * @param {string} html - DOM to create as string
  6368. * @returns {HTMLDocumentFragment|HTMLElement} a new html fragment
  6369. */
  6370. function createDOMTree(root, html) {
  6371. if (isSvg(root)) return createSVGTree(html, root);
  6372. return createHTMLTree(html, root);
  6373. }
  6374. /**
  6375. * Inject the DOM tree into a target node
  6376. * @param {HTMLElement} el - target element
  6377. * @param {DocumentFragment|SVGElement} dom - dom tree to inject
  6378. * @returns {undefined}
  6379. */
  6380. function injectDOM(el, dom) {
  6381. switch (true) {
  6382. case isSvg(el):
  6383. moveChildren(dom, el);
  6384. break;
  6385. case isTemplate(el):
  6386. el.parentNode.replaceChild(dom, el);
  6387. break;
  6388. default:
  6389. el.appendChild(dom);
  6390. }
  6391. }
  6392. /**
  6393. * Create the Template DOM skeleton
  6394. * @param {HTMLElement} el - root node where the DOM will be injected
  6395. * @param {string|HTMLElement} html - HTML markup or HTMLElement that will be injected into the root node
  6396. * @returns {?DocumentFragment} fragment that will be injected into the root node
  6397. */
  6398. function createTemplateDOM(el, html) {
  6399. return html && (typeof html === 'string' ? createDOMTree(el, html) : html);
  6400. }
  6401. /**
  6402. * Get the offset of the <template> tag
  6403. * @param {HTMLElement} parentNode - template tag parent node
  6404. * @param {HTMLElement} el - the template tag we want to render
  6405. * @param {Object} meta - meta properties needed to handle the <template> tags in loops
  6406. * @returns {number} offset of the <template> tag calculated from its siblings DOM nodes
  6407. */
  6408. function getTemplateTagOffset(parentNode, el, meta) {
  6409. const siblings = Array.from(parentNode.childNodes);
  6410. return Math.max(siblings.indexOf(el), siblings.indexOf(meta.head) + 1, 0);
  6411. }
  6412. /**
  6413. * Template Chunk model
  6414. * @type {Object}
  6415. */
  6416. const TemplateChunk = Object.freeze({
  6417. // Static props
  6418. // bindings: null,
  6419. // bindingsData: null,
  6420. // html: null,
  6421. // isTemplateTag: false,
  6422. // fragment: null,
  6423. // children: null,
  6424. // dom: null,
  6425. // el: null,
  6426. /**
  6427. * Create the template DOM structure that will be cloned on each mount
  6428. * @param {HTMLElement} el - the root node
  6429. * @returns {TemplateChunk} self
  6430. */
  6431. createDOM(el) {
  6432. // make sure that the DOM gets created before cloning the template
  6433. this.dom = this.dom || createTemplateDOM(el, this.html) || document.createDocumentFragment();
  6434. return this;
  6435. },
  6436. // API methods
  6437. /**
  6438. * Attach the template to a DOM node
  6439. * @param {HTMLElement} el - target DOM node
  6440. * @param {*} scope - template data
  6441. * @param {*} parentScope - scope of the parent template tag
  6442. * @param {Object} meta - meta properties needed to handle the <template> tags in loops
  6443. * @returns {TemplateChunk} self
  6444. */
  6445. mount(el, scope, parentScope, meta) {
  6446. if (meta === void 0) {
  6447. meta = {};
  6448. }
  6449. if (!el) throw new Error('Please provide DOM node to mount properly your template');
  6450. if (this.el) this.unmount(scope); // <template> tags require a bit more work
  6451. // the template fragment might be already created via meta outside of this call
  6452. const {
  6453. fragment,
  6454. children,
  6455. avoidDOMInjection
  6456. } = meta; // <template> bindings of course can not have a root element
  6457. // so we check the parent node to set the query selector bindings
  6458. const {
  6459. parentNode
  6460. } = children ? children[0] : el;
  6461. const isTemplateTag = isTemplate(el);
  6462. const templateTagOffset = isTemplateTag ? getTemplateTagOffset(parentNode, el, meta) : null; // create the DOM if it wasn't created before
  6463. this.createDOM(el); // create the DOM of this template cloning the original DOM structure stored in this instance
  6464. // notice that if a documentFragment was passed (via meta) we will use it instead
  6465. const cloneNode = fragment || this.dom.cloneNode(true); // store root node
  6466. // notice that for template tags the root note will be the parent tag
  6467. this.el = isTemplateTag ? parentNode : el; // create the children array only for the <template> fragments
  6468. this.children = isTemplateTag ? children || Array.from(cloneNode.childNodes) : null; // inject the DOM into the el only if a fragment is available
  6469. if (!avoidDOMInjection && cloneNode) injectDOM(el, cloneNode); // create the bindings
  6470. this.bindings = this.bindingsData.map(binding => create$1(this.el, binding, templateTagOffset));
  6471. this.bindings.forEach(b => b.mount(scope, parentScope)); // store the template meta properties
  6472. this.meta = meta;
  6473. return this;
  6474. },
  6475. /**
  6476. * Update the template with fresh data
  6477. * @param {*} scope - template data
  6478. * @param {*} parentScope - scope of the parent template tag
  6479. * @returns {TemplateChunk} self
  6480. */
  6481. update(scope, parentScope) {
  6482. this.bindings.forEach(b => b.update(scope, parentScope));
  6483. return this;
  6484. },
  6485. /**
  6486. * Remove the template from the node where it was initially mounted
  6487. * @param {*} scope - template data
  6488. * @param {*} parentScope - scope of the parent template tag
  6489. * @param {boolean|null} mustRemoveRoot - if true remove the root element,
  6490. * if false or undefined clean the root tag content, if null don't touch the DOM
  6491. * @returns {TemplateChunk} self
  6492. */
  6493. unmount(scope, parentScope, mustRemoveRoot) {
  6494. if (mustRemoveRoot === void 0) {
  6495. mustRemoveRoot = false;
  6496. }
  6497. const el = this.el;
  6498. if (!el) {
  6499. return this;
  6500. }
  6501. this.bindings.forEach(b => b.unmount(scope, parentScope, mustRemoveRoot));
  6502. switch (true) {
  6503. // pure components should handle the DOM unmount updates by themselves
  6504. // for mustRemoveRoot === null don't touch the DOM
  6505. case el[IS_PURE_SYMBOL] || mustRemoveRoot === null:
  6506. break;
  6507. // if children are declared, clear them
  6508. // applicable for <template> and <slot/> bindings
  6509. case Array.isArray(this.children):
  6510. clearChildren(this.children);
  6511. break;
  6512. // clean the node children only
  6513. case !mustRemoveRoot:
  6514. cleanNode(el);
  6515. break;
  6516. // remove the root node only if the mustRemoveRoot is truly
  6517. case !!mustRemoveRoot:
  6518. removeChild(el);
  6519. break;
  6520. }
  6521. this.el = null;
  6522. return this;
  6523. },
  6524. /**
  6525. * Clone the template chunk
  6526. * @returns {TemplateChunk} a clone of this object resetting the this.el property
  6527. */
  6528. clone() {
  6529. return Object.assign({}, this, {
  6530. meta: {},
  6531. el: null
  6532. });
  6533. }
  6534. });
  6535. /**
  6536. * Create a template chunk wiring also the bindings
  6537. * @param {string|HTMLElement} html - template string
  6538. * @param {BindingData[]} bindings - bindings collection
  6539. * @returns {TemplateChunk} a new TemplateChunk copy
  6540. */
  6541. function create(html, bindings) {
  6542. if (bindings === void 0) {
  6543. bindings = [];
  6544. }
  6545. return Object.assign({}, TemplateChunk, {
  6546. html,
  6547. bindingsData: bindings
  6548. });
  6549. }
  6550. /**
  6551. * Method used to bind expressions to a DOM node
  6552. * @param {string|HTMLElement} html - your static template html structure
  6553. * @param {Array} bindings - list of the expressions to bind to update the markup
  6554. * @returns {TemplateChunk} a new TemplateChunk object having the `update`,`mount`, `unmount` and `clone` methods
  6555. *
  6556. * @example
  6557. *
  6558. * riotDOMBindings
  6559. * .template(
  6560. * `<div expr0><!----></div><div><p expr1><!----><section expr2></section></p>`,
  6561. * [
  6562. * {
  6563. * selector: '[expr0]',
  6564. * redundantAttribute: 'expr0',
  6565. * expressions: [
  6566. * {
  6567. * type: expressionTypes.TEXT,
  6568. * childNodeIndex: 0,
  6569. * evaluate(scope) {
  6570. * return scope.time;
  6571. * },
  6572. * },
  6573. * ],
  6574. * },
  6575. * {
  6576. * selector: '[expr1]',
  6577. * redundantAttribute: 'expr1',
  6578. * expressions: [
  6579. * {
  6580. * type: expressionTypes.TEXT,
  6581. * childNodeIndex: 0,
  6582. * evaluate(scope) {
  6583. * return scope.name;
  6584. * },
  6585. * },
  6586. * {
  6587. * type: 'attribute',
  6588. * name: 'style',
  6589. * evaluate(scope) {
  6590. * return scope.style;
  6591. * },
  6592. * },
  6593. * ],
  6594. * },
  6595. * {
  6596. * selector: '[expr2]',
  6597. * redundantAttribute: 'expr2',
  6598. * type: bindingTypes.IF,
  6599. * evaluate(scope) {
  6600. * return scope.isVisible;
  6601. * },
  6602. * template: riotDOMBindings.template('hello there'),
  6603. * },
  6604. * ]
  6605. * )
  6606. */
  6607. var DOMBindings = /*#__PURE__*/Object.freeze({
  6608. __proto__: null,
  6609. template: create,
  6610. createBinding: create$1,
  6611. createExpression: create$4,
  6612. bindingTypes: bindingTypes,
  6613. expressionTypes: expressionTypes
  6614. });
  6615. function noop() {
  6616. return this;
  6617. }
  6618. /**
  6619. * Autobind the methods of a source object to itself
  6620. * @param {Object} source - probably a riot tag instance
  6621. * @param {Array<string>} methods - list of the methods to autobind
  6622. * @returns {Object} the original object received
  6623. */
  6624. function autobindMethods(source, methods) {
  6625. methods.forEach(method => {
  6626. source[method] = source[method].bind(source);
  6627. });
  6628. return source;
  6629. }
  6630. /**
  6631. * Call the first argument received only if it's a function otherwise return it as it is
  6632. * @param {*} source - anything
  6633. * @returns {*} anything
  6634. */
  6635. function callOrAssign(source) {
  6636. return isFunction(source) ? source.prototype && source.prototype.constructor ? new source() : source() : source;
  6637. }
  6638. /**
  6639. * Converts any DOM node/s to a loopable array
  6640. * @param { HTMLElement|NodeList } els - single html element or a node list
  6641. * @returns { Array } always a loopable object
  6642. */
  6643. function domToArray(els) {
  6644. // can this object be already looped?
  6645. if (!Array.isArray(els)) {
  6646. // is it a node list?
  6647. 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
  6648. // it will be returned as "array" with one single entry
  6649. return [els];
  6650. } // this object could be looped out of the box
  6651. return els;
  6652. }
  6653. /**
  6654. * Simple helper to find DOM nodes returning them as array like loopable object
  6655. * @param { string|DOMNodeList } selector - either the query or the DOM nodes to arraify
  6656. * @param { HTMLElement } ctx - context defining where the query will search for the DOM nodes
  6657. * @returns { Array } DOM nodes found as array
  6658. */
  6659. function $(selector, ctx) {
  6660. return domToArray(typeof selector === 'string' ? (ctx || document).querySelectorAll(selector) : selector);
  6661. }
  6662. /**
  6663. * Normalize the return values, in case of a single value we avoid to return an array
  6664. * @param { Array } values - list of values we want to return
  6665. * @returns { Array|string|boolean } either the whole list of values or the single one found
  6666. * @private
  6667. */
  6668. const normalize = values => values.length === 1 ? values[0] : values;
  6669. /**
  6670. * Parse all the nodes received to get/remove/check their attributes
  6671. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  6672. * @param { string|Array } name - name or list of attributes
  6673. * @param { string } method - method that will be used to parse the attributes
  6674. * @returns { Array|string } result of the parsing in a list or a single value
  6675. * @private
  6676. */
  6677. function parseNodes(els, name, method) {
  6678. const names = typeof name === 'string' ? [name] : name;
  6679. return normalize(domToArray(els).map(el => {
  6680. return normalize(names.map(n => el[method](n)));
  6681. }));
  6682. }
  6683. /**
  6684. * Set any attribute on a single or a list of DOM nodes
  6685. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  6686. * @param { string|Object } name - either the name of the attribute to set
  6687. * or a list of properties as object key - value
  6688. * @param { string } value - the new value of the attribute (optional)
  6689. * @returns { HTMLElement|NodeList|Array } the original array of elements passed to this function
  6690. *
  6691. * @example
  6692. *
  6693. * import { set } from 'bianco.attr'
  6694. *
  6695. * const img = document.createElement('img')
  6696. *
  6697. * set(img, 'width', 100)
  6698. *
  6699. * // or also
  6700. * set(img, {
  6701. * width: 300,
  6702. * height: 300
  6703. * })
  6704. *
  6705. */
  6706. function set(els, name, value) {
  6707. const attrs = typeof name === 'object' ? name : {
  6708. [name]: value
  6709. };
  6710. const props = Object.keys(attrs);
  6711. domToArray(els).forEach(el => {
  6712. props.forEach(prop => el.setAttribute(prop, attrs[prop]));
  6713. });
  6714. return els;
  6715. }
  6716. /**
  6717. * Get any attribute from a single or a list of DOM nodes
  6718. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  6719. * @param { string|Array } name - name or list of attributes to get
  6720. * @returns { Array|string } list of the attributes found
  6721. *
  6722. * @example
  6723. *
  6724. * import { get } from 'bianco.attr'
  6725. *
  6726. * const img = document.createElement('img')
  6727. *
  6728. * get(img, 'width') // => '200'
  6729. *
  6730. * // or also
  6731. * get(img, ['width', 'height']) // => ['200', '300']
  6732. *
  6733. * // or also
  6734. * get([img1, img2], ['width', 'height']) // => [['200', '300'], ['500', '200']]
  6735. */
  6736. function get(els, name) {
  6737. return parseNodes(els, name, 'getAttribute');
  6738. }
  6739. const CSS_BY_NAME = new Map();
  6740. const STYLE_NODE_SELECTOR = 'style[riot]'; // memoized curried function
  6741. const getStyleNode = (style => {
  6742. return () => {
  6743. // lazy evaluation:
  6744. // if this function was already called before
  6745. // we return its cached result
  6746. if (style) return style; // create a new style element or use an existing one
  6747. // and cache it internally
  6748. style = $(STYLE_NODE_SELECTOR)[0] || document.createElement('style');
  6749. set(style, 'type', 'text/css');
  6750. /* istanbul ignore next */
  6751. if (!style.parentNode) document.head.appendChild(style);
  6752. return style;
  6753. };
  6754. })();
  6755. /**
  6756. * Object that will be used to inject and manage the css of every tag instance
  6757. */
  6758. var cssManager = {
  6759. CSS_BY_NAME,
  6760. /**
  6761. * Save a tag style to be later injected into DOM
  6762. * @param { string } name - if it's passed we will map the css to a tagname
  6763. * @param { string } css - css string
  6764. * @returns {Object} self
  6765. */
  6766. add(name, css) {
  6767. if (!CSS_BY_NAME.has(name)) {
  6768. CSS_BY_NAME.set(name, css);
  6769. this.inject();
  6770. }
  6771. return this;
  6772. },
  6773. /**
  6774. * Inject all previously saved tag styles into DOM
  6775. * innerHTML seems slow: http://jsperf.com/riot-insert-style
  6776. * @returns {Object} self
  6777. */
  6778. inject() {
  6779. getStyleNode().innerHTML = [...CSS_BY_NAME.values()].join('\n');
  6780. return this;
  6781. },
  6782. /**
  6783. * Remove a tag style from the DOM
  6784. * @param {string} name a registered tagname
  6785. * @returns {Object} self
  6786. */
  6787. remove(name) {
  6788. if (CSS_BY_NAME.has(name)) {
  6789. CSS_BY_NAME.delete(name);
  6790. this.inject();
  6791. }
  6792. return this;
  6793. }
  6794. };
  6795. /**
  6796. * Function to curry any javascript method
  6797. * @param {Function} fn - the target function we want to curry
  6798. * @param {...[args]} acc - initial arguments
  6799. * @returns {Function|*} it will return a function until the target function
  6800. * will receive all of its arguments
  6801. */
  6802. function curry(fn) {
  6803. for (var _len = arguments.length, acc = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  6804. acc[_key - 1] = arguments[_key];
  6805. }
  6806. return function () {
  6807. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  6808. args[_key2] = arguments[_key2];
  6809. }
  6810. args = [...acc, ...args];
  6811. return args.length < fn.length ? curry(fn, ...args) : fn(...args);
  6812. };
  6813. }
  6814. /**
  6815. * Get the tag name of any DOM node
  6816. * @param {HTMLElement} element - DOM node we want to inspect
  6817. * @returns {string} name to identify this dom node in riot
  6818. */
  6819. function getName(element) {
  6820. return get(element, IS_DIRECTIVE) || element.tagName.toLowerCase();
  6821. }
  6822. const COMPONENT_CORE_HELPERS = Object.freeze({
  6823. // component helpers
  6824. $(selector) {
  6825. return $(selector, this.root)[0];
  6826. },
  6827. $$(selector) {
  6828. return $(selector, this.root);
  6829. }
  6830. });
  6831. const PURE_COMPONENT_API = Object.freeze({
  6832. [MOUNT_METHOD_KEY]: noop,
  6833. [UPDATE_METHOD_KEY]: noop,
  6834. [UNMOUNT_METHOD_KEY]: noop
  6835. });
  6836. const COMPONENT_LIFECYCLE_METHODS = Object.freeze({
  6837. [SHOULD_UPDATE_KEY]: noop,
  6838. [ON_BEFORE_MOUNT_KEY]: noop,
  6839. [ON_MOUNTED_KEY]: noop,
  6840. [ON_BEFORE_UPDATE_KEY]: noop,
  6841. [ON_UPDATED_KEY]: noop,
  6842. [ON_BEFORE_UNMOUNT_KEY]: noop,
  6843. [ON_UNMOUNTED_KEY]: noop
  6844. });
  6845. const MOCKED_TEMPLATE_INTERFACE = Object.assign({}, PURE_COMPONENT_API, {
  6846. clone: noop,
  6847. createDOM: noop
  6848. });
  6849. /**
  6850. * Performance optimization for the recursive components
  6851. * @param {RiotComponentWrapper} componentWrapper - riot compiler generated object
  6852. * @returns {Object} component like interface
  6853. */
  6854. const memoizedCreateComponent = memoize(createComponent);
  6855. /**
  6856. * Evaluate the component properties either from its real attributes or from its initial user properties
  6857. * @param {HTMLElement} element - component root
  6858. * @param {Object} initialProps - initial props
  6859. * @returns {Object} component props key value pairs
  6860. */
  6861. function evaluateInitialProps(element, initialProps) {
  6862. if (initialProps === void 0) {
  6863. initialProps = {};
  6864. }
  6865. return Object.assign({}, DOMattributesToObject(element), callOrAssign(initialProps));
  6866. }
  6867. /**
  6868. * Bind a DOM node to its component object
  6869. * @param {HTMLElement} node - html node mounted
  6870. * @param {Object} component - Riot.js component object
  6871. * @returns {Object} the component object received as second argument
  6872. */
  6873. const bindDOMNodeToComponentObject = (node, component) => node[DOM_COMPONENT_INSTANCE_PROPERTY$1] = component;
  6874. /**
  6875. * Wrap the Riot.js core API methods using a mapping function
  6876. * @param {Function} mapFunction - lifting function
  6877. * @returns {Object} an object having the { mount, update, unmount } functions
  6878. */
  6879. function createCoreAPIMethods(mapFunction) {
  6880. return [MOUNT_METHOD_KEY, UPDATE_METHOD_KEY, UNMOUNT_METHOD_KEY].reduce((acc, method) => {
  6881. acc[method] = mapFunction(method);
  6882. return acc;
  6883. }, {});
  6884. }
  6885. /**
  6886. * Factory function to create the component templates only once
  6887. * @param {Function} template - component template creation function
  6888. * @param {RiotComponentWrapper} componentWrapper - riot compiler generated object
  6889. * @returns {TemplateChunk} template chunk object
  6890. */
  6891. function componentTemplateFactory(template, componentWrapper) {
  6892. const components = createSubcomponents(componentWrapper.exports ? componentWrapper.exports.components : {});
  6893. return template(create, expressionTypes, bindingTypes, name => {
  6894. // improve support for recursive components
  6895. if (name === componentWrapper.name) return memoizedCreateComponent(componentWrapper); // return the registered components
  6896. return components[name] || COMPONENTS_IMPLEMENTATION_MAP$1.get(name);
  6897. });
  6898. }
  6899. /**
  6900. * Create a pure component
  6901. * @param {Function} pureFactoryFunction - pure component factory function
  6902. * @param {Array} options.slots - component slots
  6903. * @param {Array} options.attributes - component attributes
  6904. * @param {Array} options.template - template factory function
  6905. * @param {Array} options.template - template factory function
  6906. * @param {any} options.props - initial component properties
  6907. * @returns {Object} pure component object
  6908. */
  6909. function createPureComponent(pureFactoryFunction, _ref) {
  6910. let {
  6911. slots,
  6912. attributes,
  6913. props,
  6914. css,
  6915. template
  6916. } = _ref;
  6917. if (template) panic('Pure components can not have html');
  6918. if (css) panic('Pure components do not have css');
  6919. const component = defineDefaults(pureFactoryFunction({
  6920. slots,
  6921. attributes,
  6922. props
  6923. }), PURE_COMPONENT_API);
  6924. return createCoreAPIMethods(method => function () {
  6925. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  6926. args[_key] = arguments[_key];
  6927. }
  6928. // intercept the mount calls to bind the DOM node to the pure object created
  6929. // see also https://github.com/riot/riot/issues/2806
  6930. if (method === MOUNT_METHOD_KEY) {
  6931. const [el] = args; // mark this node as pure element
  6932. el[IS_PURE_SYMBOL] = true;
  6933. bindDOMNodeToComponentObject(el, component);
  6934. }
  6935. component[method](...args);
  6936. return component;
  6937. });
  6938. }
  6939. /**
  6940. * Create the component interface needed for the @riotjs/dom-bindings tag bindings
  6941. * @param {RiotComponentWrapper} componentWrapper - riot compiler generated object
  6942. * @param {string} componentWrapper.css - component css
  6943. * @param {Function} componentWrapper.template - function that will return the dom-bindings template function
  6944. * @param {Object} componentWrapper.exports - component interface
  6945. * @param {string} componentWrapper.name - component name
  6946. * @returns {Object} component like interface
  6947. */
  6948. function createComponent(componentWrapper) {
  6949. const {
  6950. css,
  6951. template,
  6952. exports,
  6953. name
  6954. } = componentWrapper;
  6955. const templateFn = template ? componentTemplateFactory(template, componentWrapper) : MOCKED_TEMPLATE_INTERFACE;
  6956. return _ref2 => {
  6957. let {
  6958. slots,
  6959. attributes,
  6960. props
  6961. } = _ref2;
  6962. // pure components rendering will be managed by the end user
  6963. if (exports && exports[IS_PURE_SYMBOL]) return createPureComponent(exports, {
  6964. slots,
  6965. attributes,
  6966. props,
  6967. css,
  6968. template
  6969. });
  6970. const componentAPI = callOrAssign(exports) || {};
  6971. const component = defineComponent({
  6972. css,
  6973. template: templateFn,
  6974. componentAPI,
  6975. name
  6976. })({
  6977. slots,
  6978. attributes,
  6979. props
  6980. }); // notice that for the components create via tag binding
  6981. // we need to invert the mount (state/parentScope) arguments
  6982. // the template bindings will only forward the parentScope updates
  6983. // and never deal with the component state
  6984. return {
  6985. mount(element, parentScope, state) {
  6986. return component.mount(element, state, parentScope);
  6987. },
  6988. update(parentScope, state) {
  6989. return component.update(state, parentScope);
  6990. },
  6991. unmount(preserveRoot) {
  6992. return component.unmount(preserveRoot);
  6993. }
  6994. };
  6995. };
  6996. }
  6997. /**
  6998. * Component definition function
  6999. * @param {Object} implementation - the componen implementation will be generated via compiler
  7000. * @param {Object} component - the component initial properties
  7001. * @returns {Object} a new component implementation object
  7002. */
  7003. function defineComponent(_ref3) {
  7004. let {
  7005. css,
  7006. template,
  7007. componentAPI,
  7008. name
  7009. } = _ref3;
  7010. // add the component css into the DOM
  7011. if (css && name) cssManager.add(name, css);
  7012. return curry(enhanceComponentAPI)(defineProperties( // set the component defaults without overriding the original component API
  7013. defineDefaults(componentAPI, Object.assign({}, COMPONENT_LIFECYCLE_METHODS, {
  7014. [PROPS_KEY]: {},
  7015. [STATE_KEY]: {}
  7016. })), Object.assign({
  7017. // defined during the component creation
  7018. [SLOTS_KEY]: null,
  7019. [ROOT_KEY]: null
  7020. }, COMPONENT_CORE_HELPERS, {
  7021. name,
  7022. css,
  7023. template
  7024. })));
  7025. }
  7026. /**
  7027. * Create the bindings to update the component attributes
  7028. * @param {HTMLElement} node - node where we will bind the expressions
  7029. * @param {Array} attributes - list of attribute bindings
  7030. * @returns {TemplateChunk} - template bindings object
  7031. */
  7032. function createAttributeBindings(node, attributes) {
  7033. if (attributes === void 0) {
  7034. attributes = [];
  7035. }
  7036. const expressions = attributes.map(a => create$4(node, a));
  7037. const binding = {};
  7038. return Object.assign(binding, Object.assign({
  7039. expressions
  7040. }, createCoreAPIMethods(method => scope => {
  7041. expressions.forEach(e => e[method](scope));
  7042. return binding;
  7043. })));
  7044. }
  7045. /**
  7046. * Create the subcomponents that can be included inside a tag in runtime
  7047. * @param {Object} components - components imported in runtime
  7048. * @returns {Object} all the components transformed into Riot.Component factory functions
  7049. */
  7050. function createSubcomponents(components) {
  7051. if (components === void 0) {
  7052. components = {};
  7053. }
  7054. return Object.entries(callOrAssign(components)).reduce((acc, _ref4) => {
  7055. let [key, value] = _ref4;
  7056. acc[camelToDashCase(key)] = createComponent(value);
  7057. return acc;
  7058. }, {});
  7059. }
  7060. /**
  7061. * Run the component instance through all the plugins set by the user
  7062. * @param {Object} component - component instance
  7063. * @returns {Object} the component enhanced by the plugins
  7064. */
  7065. function runPlugins(component) {
  7066. return [...PLUGINS_SET$1].reduce((c, fn) => fn(c) || c, component);
  7067. }
  7068. /**
  7069. * Compute the component current state merging it with its previous state
  7070. * @param {Object} oldState - previous state object
  7071. * @param {Object} newState - new state givent to the `update` call
  7072. * @returns {Object} new object state
  7073. */
  7074. function computeState(oldState, newState) {
  7075. return Object.assign({}, oldState, callOrAssign(newState));
  7076. }
  7077. /**
  7078. * Add eventually the "is" attribute to link this DOM node to its css
  7079. * @param {HTMLElement} element - target root node
  7080. * @param {string} name - name of the component mounted
  7081. * @returns {undefined} it's a void function
  7082. */
  7083. function addCssHook(element, name) {
  7084. if (getName(element) !== name) {
  7085. set(element, IS_DIRECTIVE, name);
  7086. }
  7087. }
  7088. /**
  7089. * Component creation factory function that will enhance the user provided API
  7090. * @param {Object} component - a component implementation previously defined
  7091. * @param {Array} options.slots - component slots generated via riot compiler
  7092. * @param {Array} options.attributes - attribute expressions generated via riot compiler
  7093. * @returns {Riot.Component} a riot component instance
  7094. */
  7095. function enhanceComponentAPI(component, _ref5) {
  7096. let {
  7097. slots,
  7098. attributes,
  7099. props
  7100. } = _ref5;
  7101. return autobindMethods(runPlugins(defineProperties(isObject(component) ? Object.create(component) : component, {
  7102. mount(element, state, parentScope) {
  7103. if (state === void 0) {
  7104. state = {};
  7105. }
  7106. this[PARENT_KEY_SYMBOL] = parentScope;
  7107. this[ATTRIBUTES_KEY_SYMBOL] = createAttributeBindings(element, attributes).mount(parentScope);
  7108. defineProperty(this, PROPS_KEY, Object.freeze(Object.assign({}, evaluateInitialProps(element, props), evaluateAttributeExpressions(this[ATTRIBUTES_KEY_SYMBOL].expressions))));
  7109. this[STATE_KEY] = computeState(this[STATE_KEY], state);
  7110. this[TEMPLATE_KEY_SYMBOL] = this.template.createDOM(element).clone(); // link this object to the DOM node
  7111. bindDOMNodeToComponentObject(element, this); // add eventually the 'is' attribute
  7112. component.name && addCssHook(element, component.name); // define the root element
  7113. defineProperty(this, ROOT_KEY, element); // define the slots array
  7114. defineProperty(this, SLOTS_KEY, slots); // before mount lifecycle event
  7115. this[ON_BEFORE_MOUNT_KEY](this[PROPS_KEY], this[STATE_KEY]); // mount the template
  7116. this[TEMPLATE_KEY_SYMBOL].mount(element, this, parentScope);
  7117. this[ON_MOUNTED_KEY](this[PROPS_KEY], this[STATE_KEY]);
  7118. return this;
  7119. },
  7120. update(state, parentScope) {
  7121. if (state === void 0) {
  7122. state = {};
  7123. }
  7124. if (parentScope) {
  7125. this[PARENT_KEY_SYMBOL] = parentScope;
  7126. this[ATTRIBUTES_KEY_SYMBOL].update(parentScope);
  7127. }
  7128. const newProps = evaluateAttributeExpressions(this[ATTRIBUTES_KEY_SYMBOL].expressions);
  7129. if (this[SHOULD_UPDATE_KEY](newProps, this[PROPS_KEY]) === false) return;
  7130. defineProperty(this, PROPS_KEY, Object.freeze(Object.assign({}, this[PROPS_KEY], newProps)));
  7131. this[STATE_KEY] = computeState(this[STATE_KEY], state);
  7132. this[ON_BEFORE_UPDATE_KEY](this[PROPS_KEY], this[STATE_KEY]); // avoiding recursive updates
  7133. // see also https://github.com/riot/riot/issues/2895
  7134. if (!this[IS_COMPONENT_UPDATING]) {
  7135. this[IS_COMPONENT_UPDATING] = true;
  7136. this[TEMPLATE_KEY_SYMBOL].update(this, this[PARENT_KEY_SYMBOL]);
  7137. }
  7138. this[ON_UPDATED_KEY](this[PROPS_KEY], this[STATE_KEY]);
  7139. this[IS_COMPONENT_UPDATING] = false;
  7140. return this;
  7141. },
  7142. unmount(preserveRoot) {
  7143. this[ON_BEFORE_UNMOUNT_KEY](this[PROPS_KEY], this[STATE_KEY]);
  7144. this[ATTRIBUTES_KEY_SYMBOL].unmount(); // if the preserveRoot is null the template html will be left untouched
  7145. // in that case the DOM cleanup will happen differently from a parent node
  7146. this[TEMPLATE_KEY_SYMBOL].unmount(this, this[PARENT_KEY_SYMBOL], preserveRoot === null ? null : !preserveRoot);
  7147. this[ON_UNMOUNTED_KEY](this[PROPS_KEY], this[STATE_KEY]);
  7148. return this;
  7149. }
  7150. })), Object.keys(component).filter(prop => isFunction(component[prop])));
  7151. }
  7152. /**
  7153. * Component initialization function starting from a DOM node
  7154. * @param {HTMLElement} element - element to upgrade
  7155. * @param {Object} initialProps - initial component properties
  7156. * @param {string} componentName - component id
  7157. * @returns {Object} a new component instance bound to a DOM node
  7158. */
  7159. function mountComponent(element, initialProps, componentName) {
  7160. const name = componentName || getName(element);
  7161. if (!COMPONENTS_IMPLEMENTATION_MAP$1.has(name)) panic(`The component named "${name}" was never registered`);
  7162. const component = COMPONENTS_IMPLEMENTATION_MAP$1.get(name)({
  7163. props: initialProps
  7164. });
  7165. return component.mount(element);
  7166. }
  7167. /**
  7168. * Similar to compose but performs from left-to-right function composition.<br/>
  7169. * {@link https://30secondsofcode.org/function#composeright see also}
  7170. * @param {...[function]} fns) - list of unary function
  7171. * @returns {*} result of the computation
  7172. */
  7173. /**
  7174. * Performs right-to-left function composition.<br/>
  7175. * Use Array.prototype.reduce() to perform right-to-left function composition.<br/>
  7176. * The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.<br/>
  7177. * {@link https://30secondsofcode.org/function#compose original source code}
  7178. * @param {...[function]} fns) - list of unary function
  7179. * @returns {*} result of the computation
  7180. */
  7181. function compose() {
  7182. for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  7183. fns[_key2] = arguments[_key2];
  7184. }
  7185. return fns.reduce((f, g) => function () {
  7186. return f(g(...arguments));
  7187. });
  7188. }
  7189. const {
  7190. DOM_COMPONENT_INSTANCE_PROPERTY,
  7191. COMPONENTS_IMPLEMENTATION_MAP,
  7192. PLUGINS_SET
  7193. } = globals;
  7194. /**
  7195. * Riot public api
  7196. */
  7197. /**
  7198. * Register a custom tag by name
  7199. * @param {string} name - component name
  7200. * @param {Object} implementation - tag implementation
  7201. * @returns {Map} map containing all the components implementations
  7202. */
  7203. function register(name, _ref) {
  7204. let {
  7205. css,
  7206. template,
  7207. exports
  7208. } = _ref;
  7209. if (COMPONENTS_IMPLEMENTATION_MAP.has(name)) panic(`The component "${name}" was already registered`);
  7210. COMPONENTS_IMPLEMENTATION_MAP.set(name, createComponent({
  7211. name,
  7212. css,
  7213. template,
  7214. exports
  7215. }));
  7216. return COMPONENTS_IMPLEMENTATION_MAP;
  7217. }
  7218. /**
  7219. * Unregister a riot web component
  7220. * @param {string} name - component name
  7221. * @returns {Map} map containing all the components implementations
  7222. */
  7223. function unregister(name) {
  7224. if (!COMPONENTS_IMPLEMENTATION_MAP.has(name)) panic(`The component "${name}" was never registered`);
  7225. COMPONENTS_IMPLEMENTATION_MAP.delete(name);
  7226. cssManager.remove(name);
  7227. return COMPONENTS_IMPLEMENTATION_MAP;
  7228. }
  7229. /**
  7230. * Mounting function that will work only for the components that were globally registered
  7231. * @param {string|HTMLElement} selector - query for the selection or a DOM element
  7232. * @param {Object} initialProps - the initial component properties
  7233. * @param {string} name - optional component name
  7234. * @returns {Array} list of riot components
  7235. */
  7236. function mount(selector, initialProps, name) {
  7237. return $(selector).map(element => mountComponent(element, initialProps, name));
  7238. }
  7239. /**
  7240. * Sweet unmounting helper function for the DOM node mounted manually by the user
  7241. * @param {string|HTMLElement} selector - query for the selection or a DOM element
  7242. * @param {boolean|null} keepRootElement - if true keep the root element
  7243. * @returns {Array} list of nodes unmounted
  7244. */
  7245. function unmount(selector, keepRootElement) {
  7246. return $(selector).map(element => {
  7247. if (element[DOM_COMPONENT_INSTANCE_PROPERTY]) {
  7248. element[DOM_COMPONENT_INSTANCE_PROPERTY].unmount(keepRootElement);
  7249. }
  7250. return element;
  7251. });
  7252. }
  7253. /**
  7254. * Define a riot plugin
  7255. * @param {Function} plugin - function that will receive all the components created
  7256. * @returns {Set} the set containing all the plugins installed
  7257. */
  7258. function install(plugin) {
  7259. if (!isFunction(plugin)) panic('Plugins must be of type function');
  7260. if (PLUGINS_SET.has(plugin)) panic('This plugin was already installed');
  7261. PLUGINS_SET.add(plugin);
  7262. return PLUGINS_SET;
  7263. }
  7264. /**
  7265. * Uninstall a riot plugin
  7266. * @param {Function} plugin - plugin previously installed
  7267. * @returns {Set} the set containing all the plugins installed
  7268. */
  7269. function uninstall(plugin) {
  7270. if (!PLUGINS_SET.has(plugin)) panic('This plugin was never installed');
  7271. PLUGINS_SET.delete(plugin);
  7272. return PLUGINS_SET;
  7273. }
  7274. /**
  7275. * Helper method to create component without relying on the registered ones
  7276. * @param {Object} implementation - component implementation
  7277. * @returns {Function} function that will allow you to mount a riot component on a DOM node
  7278. */
  7279. function component(implementation) {
  7280. return function (el, props, _temp) {
  7281. let {
  7282. slots,
  7283. attributes,
  7284. parentScope
  7285. } = _temp === void 0 ? {} : _temp;
  7286. return compose(c => c.mount(el, parentScope), c => c({
  7287. props,
  7288. slots,
  7289. attributes
  7290. }), createComponent)(implementation);
  7291. };
  7292. }
  7293. /**
  7294. * Lift a riot component Interface into a pure riot object
  7295. * @param {Function} func - RiotPureComponent factory function
  7296. * @returns {Function} the lifted original function received as argument
  7297. */
  7298. function pure(func) {
  7299. if (!isFunction(func)) panic('riot.pure accepts only arguments of type "function"');
  7300. func[IS_PURE_SYMBOL] = true;
  7301. return func;
  7302. }
  7303. /**
  7304. * no-op function needed to add the proper types to your component via typescript
  7305. * @param {Function|Object} component - component default export
  7306. * @returns {Function|Object} returns exactly what it has received
  7307. */
  7308. const withTypes = component => component;
  7309. /** @type {string} current riot version */
  7310. const version = 'v6.0.1'; // expose some internal stuff that might be used from external tools
  7311. const __ = {
  7312. cssManager,
  7313. DOMBindings,
  7314. createComponent,
  7315. defineComponent,
  7316. globals
  7317. };
  7318. /***/ }),
  7319. /***/ "./node_modules/validate.js/validate.js":
  7320. /*!**********************************************!*\
  7321. !*** ./node_modules/validate.js/validate.js ***!
  7322. \**********************************************/
  7323. /***/ (function(module, exports, __webpack_require__) {
  7324. /* module decorator */ module = __webpack_require__.nmd(module);
  7325. /*!
  7326. * validate.js 0.13.1
  7327. *
  7328. * (c) 2013-2019 Nicklas Ansman, 2013 Wrapp
  7329. * Validate.js may be freely distributed under the MIT license.
  7330. * For all details and documentation:
  7331. * http://validatejs.org/
  7332. */
  7333. (function(exports, module, define) {
  7334. "use strict";
  7335. // The main function that calls the validators specified by the constraints.
  7336. // The options are the following:
  7337. // - format (string) - An option that controls how the returned value is formatted
  7338. // * flat - Returns a flat array of just the error messages
  7339. // * grouped - Returns the messages grouped by attribute (default)
  7340. // * detailed - Returns an array of the raw validation data
  7341. // - fullMessages (boolean) - If `true` (default) the attribute name is prepended to the error.
  7342. //
  7343. // Please note that the options are also passed to each validator.
  7344. var validate = function(attributes, constraints, options) {
  7345. options = v.extend({}, v.options, options);
  7346. var results = v.runValidations(attributes, constraints, options)
  7347. , attr
  7348. , validator;
  7349. if (results.some(function(r) { return v.isPromise(r.error); })) {
  7350. throw new Error("Use validate.async if you want support for promises");
  7351. }
  7352. return validate.processValidationResults(results, options);
  7353. };
  7354. var v = validate;
  7355. // Copies over attributes from one or more sources to a single destination.
  7356. // Very much similar to underscore's extend.
  7357. // The first argument is the target object and the remaining arguments will be
  7358. // used as sources.
  7359. v.extend = function(obj) {
  7360. [].slice.call(arguments, 1).forEach(function(source) {
  7361. for (var attr in source) {
  7362. obj[attr] = source[attr];
  7363. }
  7364. });
  7365. return obj;
  7366. };
  7367. v.extend(validate, {
  7368. // This is the version of the library as a semver.
  7369. // The toString function will allow it to be coerced into a string
  7370. version: {
  7371. major: 0,
  7372. minor: 13,
  7373. patch: 1,
  7374. metadata: null,
  7375. toString: function() {
  7376. var version = v.format("%{major}.%{minor}.%{patch}", v.version);
  7377. if (!v.isEmpty(v.version.metadata)) {
  7378. version += "+" + v.version.metadata;
  7379. }
  7380. return version;
  7381. }
  7382. },
  7383. // Below is the dependencies that are used in validate.js
  7384. // The constructor of the Promise implementation.
  7385. // If you are using Q.js, RSVP or any other A+ compatible implementation
  7386. // override this attribute to be the constructor of that promise.
  7387. // Since jQuery promises aren't A+ compatible they won't work.
  7388. Promise: typeof Promise !== "undefined" ? Promise : /* istanbul ignore next */ null,
  7389. EMPTY_STRING_REGEXP: /^\s*$/,
  7390. // Runs the validators specified by the constraints object.
  7391. // Will return an array of the format:
  7392. // [{attribute: "<attribute name>", error: "<validation result>"}, ...]
  7393. runValidations: function(attributes, constraints, options) {
  7394. var results = []
  7395. , attr
  7396. , validatorName
  7397. , value
  7398. , validators
  7399. , validator
  7400. , validatorOptions
  7401. , error;
  7402. if (v.isDomElement(attributes) || v.isJqueryElement(attributes)) {
  7403. attributes = v.collectFormValues(attributes);
  7404. }
  7405. // Loops through each constraints, finds the correct validator and run it.
  7406. for (attr in constraints) {
  7407. value = v.getDeepObjectValue(attributes, attr);
  7408. // This allows the constraints for an attribute to be a function.
  7409. // The function will be called with the value, attribute name, the complete dict of
  7410. // attributes as well as the options and constraints passed in.
  7411. // This is useful when you want to have different
  7412. // validations depending on the attribute value.
  7413. validators = v.result(constraints[attr], value, attributes, attr, options, constraints);
  7414. for (validatorName in validators) {
  7415. validator = v.validators[validatorName];
  7416. if (!validator) {
  7417. error = v.format("Unknown validator %{name}", {name: validatorName});
  7418. throw new Error(error);
  7419. }
  7420. validatorOptions = validators[validatorName];
  7421. // This allows the options to be a function. The function will be
  7422. // called with the value, attribute name, the complete dict of
  7423. // attributes as well as the options and constraints passed in.
  7424. // This is useful when you want to have different
  7425. // validations depending on the attribute value.
  7426. validatorOptions = v.result(validatorOptions, value, attributes, attr, options, constraints);
  7427. if (!validatorOptions) {
  7428. continue;
  7429. }
  7430. results.push({
  7431. attribute: attr,
  7432. value: value,
  7433. validator: validatorName,
  7434. globalOptions: options,
  7435. attributes: attributes,
  7436. options: validatorOptions,
  7437. error: validator.call(validator,
  7438. value,
  7439. validatorOptions,
  7440. attr,
  7441. attributes,
  7442. options)
  7443. });
  7444. }
  7445. }
  7446. return results;
  7447. },
  7448. // Takes the output from runValidations and converts it to the correct
  7449. // output format.
  7450. processValidationResults: function(errors, options) {
  7451. errors = v.pruneEmptyErrors(errors, options);
  7452. errors = v.expandMultipleErrors(errors, options);
  7453. errors = v.convertErrorMessages(errors, options);
  7454. var format = options.format || "grouped";
  7455. if (typeof v.formatters[format] === 'function') {
  7456. errors = v.formatters[format](errors);
  7457. } else {
  7458. throw new Error(v.format("Unknown format %{format}", options));
  7459. }
  7460. return v.isEmpty(errors) ? undefined : errors;
  7461. },
  7462. // Runs the validations with support for promises.
  7463. // This function will return a promise that is settled when all the
  7464. // validation promises have been completed.
  7465. // It can be called even if no validations returned a promise.
  7466. async: function(attributes, constraints, options) {
  7467. options = v.extend({}, v.async.options, options);
  7468. var WrapErrors = options.wrapErrors || function(errors) {
  7469. return errors;
  7470. };
  7471. // Removes unknown attributes
  7472. if (options.cleanAttributes !== false) {
  7473. attributes = v.cleanAttributes(attributes, constraints);
  7474. }
  7475. var results = v.runValidations(attributes, constraints, options);
  7476. return new v.Promise(function(resolve, reject) {
  7477. v.waitForResults(results).then(function() {
  7478. var errors = v.processValidationResults(results, options);
  7479. if (errors) {
  7480. reject(new WrapErrors(errors, options, attributes, constraints));
  7481. } else {
  7482. resolve(attributes);
  7483. }
  7484. }, function(err) {
  7485. reject(err);
  7486. });
  7487. });
  7488. },
  7489. single: function(value, constraints, options) {
  7490. options = v.extend({}, v.single.options, options, {
  7491. format: "flat",
  7492. fullMessages: false
  7493. });
  7494. return v({single: value}, {single: constraints}, options);
  7495. },
  7496. // Returns a promise that is resolved when all promises in the results array
  7497. // are settled. The promise returned from this function is always resolved,
  7498. // never rejected.
  7499. // This function modifies the input argument, it replaces the promises
  7500. // with the value returned from the promise.
  7501. waitForResults: function(results) {
  7502. // Create a sequence of all the results starting with a resolved promise.
  7503. return results.reduce(function(memo, result) {
  7504. // If this result isn't a promise skip it in the sequence.
  7505. if (!v.isPromise(result.error)) {
  7506. return memo;
  7507. }
  7508. return memo.then(function() {
  7509. return result.error.then(function(error) {
  7510. result.error = error || null;
  7511. });
  7512. });
  7513. }, new v.Promise(function(r) { r(); })); // A resolved promise
  7514. },
  7515. // If the given argument is a call: function the and: function return the value
  7516. // otherwise just return the value. Additional arguments will be passed as
  7517. // arguments to the function.
  7518. // Example:
  7519. // ```
  7520. // result('foo') // 'foo'
  7521. // result(Math.max, 1, 2) // 2
  7522. // ```
  7523. result: function(value) {
  7524. var args = [].slice.call(arguments, 1);
  7525. if (typeof value === 'function') {
  7526. value = value.apply(null, args);
  7527. }
  7528. return value;
  7529. },
  7530. // Checks if the value is a number. This function does not consider NaN a
  7531. // number like many other `isNumber` functions do.
  7532. isNumber: function(value) {
  7533. return typeof value === 'number' && !isNaN(value);
  7534. },
  7535. // Returns false if the object is not a function
  7536. isFunction: function(value) {
  7537. return typeof value === 'function';
  7538. },
  7539. // A simple check to verify that the value is an integer. Uses `isNumber`
  7540. // and a simple modulo check.
  7541. isInteger: function(value) {
  7542. return v.isNumber(value) && value % 1 === 0;
  7543. },
  7544. // Checks if the value is a boolean
  7545. isBoolean: function(value) {
  7546. return typeof value === 'boolean';
  7547. },
  7548. // Uses the `Object` function to check if the given argument is an object.
  7549. isObject: function(obj) {
  7550. return obj === Object(obj);
  7551. },
  7552. // Simply checks if the object is an instance of a date
  7553. isDate: function(obj) {
  7554. return obj instanceof Date;
  7555. },
  7556. // Returns false if the object is `null` of `undefined`
  7557. isDefined: function(obj) {
  7558. return obj !== null && obj !== undefined;
  7559. },
  7560. // Checks if the given argument is a promise. Anything with a `then`
  7561. // function is considered a promise.
  7562. isPromise: function(p) {
  7563. return !!p && v.isFunction(p.then);
  7564. },
  7565. isJqueryElement: function(o) {
  7566. return o && v.isString(o.jquery);
  7567. },
  7568. isDomElement: function(o) {
  7569. if (!o) {
  7570. return false;
  7571. }
  7572. if (!o.querySelectorAll || !o.querySelector) {
  7573. return false;
  7574. }
  7575. if (v.isObject(document) && o === document) {
  7576. return true;
  7577. }
  7578. // http://stackoverflow.com/a/384380/699304
  7579. /* istanbul ignore else */
  7580. if (typeof HTMLElement === "object") {
  7581. return o instanceof HTMLElement;
  7582. } else {
  7583. return o &&
  7584. typeof o === "object" &&
  7585. o !== null &&
  7586. o.nodeType === 1 &&
  7587. typeof o.nodeName === "string";
  7588. }
  7589. },
  7590. isEmpty: function(value) {
  7591. var attr;
  7592. // Null and undefined are empty
  7593. if (!v.isDefined(value)) {
  7594. return true;
  7595. }
  7596. // functions are non empty
  7597. if (v.isFunction(value)) {
  7598. return false;
  7599. }
  7600. // Whitespace only strings are empty
  7601. if (v.isString(value)) {
  7602. return v.EMPTY_STRING_REGEXP.test(value);
  7603. }
  7604. // For arrays we use the length property
  7605. if (v.isArray(value)) {
  7606. return value.length === 0;
  7607. }
  7608. // Dates have no attributes but aren't empty
  7609. if (v.isDate(value)) {
  7610. return false;
  7611. }
  7612. // If we find at least one property we consider it non empty
  7613. if (v.isObject(value)) {
  7614. for (attr in value) {
  7615. return false;
  7616. }
  7617. return true;
  7618. }
  7619. return false;
  7620. },
  7621. // Formats the specified strings with the given values like so:
  7622. // ```
  7623. // format("Foo: %{foo}", {foo: "bar"}) // "Foo bar"
  7624. // ```
  7625. // If you want to write %{...} without having it replaced simply
  7626. // prefix it with % like this `Foo: %%{foo}` and it will be returned
  7627. // as `"Foo: %{foo}"`
  7628. format: v.extend(function(str, vals) {
  7629. if (!v.isString(str)) {
  7630. return str;
  7631. }
  7632. return str.replace(v.format.FORMAT_REGEXP, function(m0, m1, m2) {
  7633. if (m1 === '%') {
  7634. return "%{" + m2 + "}";
  7635. } else {
  7636. return String(vals[m2]);
  7637. }
  7638. });
  7639. }, {
  7640. // Finds %{key} style patterns in the given string
  7641. FORMAT_REGEXP: /(%?)%\{([^\}]+)\}/g
  7642. }),
  7643. // "Prettifies" the given string.
  7644. // Prettifying means replacing [.\_-] with spaces as well as splitting
  7645. // camel case words.
  7646. prettify: function(str) {
  7647. if (v.isNumber(str)) {
  7648. // If there are more than 2 decimals round it to two
  7649. if ((str * 100) % 1 === 0) {
  7650. return "" + str;
  7651. } else {
  7652. return parseFloat(Math.round(str * 100) / 100).toFixed(2);
  7653. }
  7654. }
  7655. if (v.isArray(str)) {
  7656. return str.map(function(s) { return v.prettify(s); }).join(", ");
  7657. }
  7658. if (v.isObject(str)) {
  7659. if (!v.isDefined(str.toString)) {
  7660. return JSON.stringify(str);
  7661. }
  7662. return str.toString();
  7663. }
  7664. // Ensure the string is actually a string
  7665. str = "" + str;
  7666. return str
  7667. // Splits keys separated by periods
  7668. .replace(/([^\s])\.([^\s])/g, '$1 $2')
  7669. // Removes backslashes
  7670. .replace(/\\+/g, '')
  7671. // Replaces - and - with space
  7672. .replace(/[_-]/g, ' ')
  7673. // Splits camel cased words
  7674. .replace(/([a-z])([A-Z])/g, function(m0, m1, m2) {
  7675. return "" + m1 + " " + m2.toLowerCase();
  7676. })
  7677. .toLowerCase();
  7678. },
  7679. stringifyValue: function(value, options) {
  7680. var prettify = options && options.prettify || v.prettify;
  7681. return prettify(value);
  7682. },
  7683. isString: function(value) {
  7684. return typeof value === 'string';
  7685. },
  7686. isArray: function(value) {
  7687. return {}.toString.call(value) === '[object Array]';
  7688. },
  7689. // Checks if the object is a hash, which is equivalent to an object that
  7690. // is neither an array nor a function.
  7691. isHash: function(value) {
  7692. return v.isObject(value) && !v.isArray(value) && !v.isFunction(value);
  7693. },
  7694. contains: function(obj, value) {
  7695. if (!v.isDefined(obj)) {
  7696. return false;
  7697. }
  7698. if (v.isArray(obj)) {
  7699. return obj.indexOf(value) !== -1;
  7700. }
  7701. return value in obj;
  7702. },
  7703. unique: function(array) {
  7704. if (!v.isArray(array)) {
  7705. return array;
  7706. }
  7707. return array.filter(function(el, index, array) {
  7708. return array.indexOf(el) == index;
  7709. });
  7710. },
  7711. forEachKeyInKeypath: function(object, keypath, callback) {
  7712. if (!v.isString(keypath)) {
  7713. return undefined;
  7714. }
  7715. var key = ""
  7716. , i
  7717. , escape = false;
  7718. for (i = 0; i < keypath.length; ++i) {
  7719. switch (keypath[i]) {
  7720. case '.':
  7721. if (escape) {
  7722. escape = false;
  7723. key += '.';
  7724. } else {
  7725. object = callback(object, key, false);
  7726. key = "";
  7727. }
  7728. break;
  7729. case '\\':
  7730. if (escape) {
  7731. escape = false;
  7732. key += '\\';
  7733. } else {
  7734. escape = true;
  7735. }
  7736. break;
  7737. default:
  7738. escape = false;
  7739. key += keypath[i];
  7740. break;
  7741. }
  7742. }
  7743. return callback(object, key, true);
  7744. },
  7745. getDeepObjectValue: function(obj, keypath) {
  7746. if (!v.isObject(obj)) {
  7747. return undefined;
  7748. }
  7749. return v.forEachKeyInKeypath(obj, keypath, function(obj, key) {
  7750. if (v.isObject(obj)) {
  7751. return obj[key];
  7752. }
  7753. });
  7754. },
  7755. // This returns an object with all the values of the form.
  7756. // It uses the input name as key and the value as value
  7757. // So for example this:
  7758. // <input type="text" name="email" value="foo@bar.com" />
  7759. // would return:
  7760. // {email: "foo@bar.com"}
  7761. collectFormValues: function(form, options) {
  7762. var values = {}
  7763. , i
  7764. , j
  7765. , input
  7766. , inputs
  7767. , option
  7768. , value;
  7769. if (v.isJqueryElement(form)) {
  7770. form = form[0];
  7771. }
  7772. if (!form) {
  7773. return values;
  7774. }
  7775. options = options || {};
  7776. inputs = form.querySelectorAll("input[name], textarea[name]");
  7777. for (i = 0; i < inputs.length; ++i) {
  7778. input = inputs.item(i);
  7779. if (v.isDefined(input.getAttribute("data-ignored"))) {
  7780. continue;
  7781. }
  7782. var name = input.name.replace(/\./g, "\\\\.");
  7783. value = v.sanitizeFormValue(input.value, options);
  7784. if (input.type === "number") {
  7785. value = value ? +value : null;
  7786. } else if (input.type === "checkbox") {
  7787. if (input.attributes.value) {
  7788. if (!input.checked) {
  7789. value = values[name] || null;
  7790. }
  7791. } else {
  7792. value = input.checked;
  7793. }
  7794. } else if (input.type === "radio") {
  7795. if (!input.checked) {
  7796. value = values[name] || null;
  7797. }
  7798. }
  7799. values[name] = value;
  7800. }
  7801. inputs = form.querySelectorAll("select[name]");
  7802. for (i = 0; i < inputs.length; ++i) {
  7803. input = inputs.item(i);
  7804. if (v.isDefined(input.getAttribute("data-ignored"))) {
  7805. continue;
  7806. }
  7807. if (input.multiple) {
  7808. value = [];
  7809. for (j in input.options) {
  7810. option = input.options[j];
  7811. if (option && option.selected) {
  7812. value.push(v.sanitizeFormValue(option.value, options));
  7813. }
  7814. }
  7815. } else {
  7816. var _val = typeof input.options[input.selectedIndex] !== 'undefined' ? input.options[input.selectedIndex].value : /* istanbul ignore next */ '';
  7817. value = v.sanitizeFormValue(_val, options);
  7818. }
  7819. values[input.name] = value;
  7820. }
  7821. return values;
  7822. },
  7823. sanitizeFormValue: function(value, options) {
  7824. if (options.trim && v.isString(value)) {
  7825. value = value.trim();
  7826. }
  7827. if (options.nullify !== false && value === "") {
  7828. return null;
  7829. }
  7830. return value;
  7831. },
  7832. capitalize: function(str) {
  7833. if (!v.isString(str)) {
  7834. return str;
  7835. }
  7836. return str[0].toUpperCase() + str.slice(1);
  7837. },
  7838. // Remove all errors who's error attribute is empty (null or undefined)
  7839. pruneEmptyErrors: function(errors) {
  7840. return errors.filter(function(error) {
  7841. return !v.isEmpty(error.error);
  7842. });
  7843. },
  7844. // In
  7845. // [{error: ["err1", "err2"], ...}]
  7846. // Out
  7847. // [{error: "err1", ...}, {error: "err2", ...}]
  7848. //
  7849. // All attributes in an error with multiple messages are duplicated
  7850. // when expanding the errors.
  7851. expandMultipleErrors: function(errors) {
  7852. var ret = [];
  7853. errors.forEach(function(error) {
  7854. // Removes errors without a message
  7855. if (v.isArray(error.error)) {
  7856. error.error.forEach(function(msg) {
  7857. ret.push(v.extend({}, error, {error: msg}));
  7858. });
  7859. } else {
  7860. ret.push(error);
  7861. }
  7862. });
  7863. return ret;
  7864. },
  7865. // Converts the error mesages by prepending the attribute name unless the
  7866. // message is prefixed by ^
  7867. convertErrorMessages: function(errors, options) {
  7868. options = options || {};
  7869. var ret = []
  7870. , prettify = options.prettify || v.prettify;
  7871. errors.forEach(function(errorInfo) {
  7872. var error = v.result(errorInfo.error,
  7873. errorInfo.value,
  7874. errorInfo.attribute,
  7875. errorInfo.options,
  7876. errorInfo.attributes,
  7877. errorInfo.globalOptions);
  7878. if (!v.isString(error)) {
  7879. ret.push(errorInfo);
  7880. return;
  7881. }
  7882. if (error[0] === '^') {
  7883. error = error.slice(1);
  7884. } else if (options.fullMessages !== false) {
  7885. error = v.capitalize(prettify(errorInfo.attribute)) + " " + error;
  7886. }
  7887. error = error.replace(/\\\^/g, "^");
  7888. error = v.format(error, {
  7889. value: v.stringifyValue(errorInfo.value, options)
  7890. });
  7891. ret.push(v.extend({}, errorInfo, {error: error}));
  7892. });
  7893. return ret;
  7894. },
  7895. // In:
  7896. // [{attribute: "<attributeName>", ...}]
  7897. // Out:
  7898. // {"<attributeName>": [{attribute: "<attributeName>", ...}]}
  7899. groupErrorsByAttribute: function(errors) {
  7900. var ret = {};
  7901. errors.forEach(function(error) {
  7902. var list = ret[error.attribute];
  7903. if (list) {
  7904. list.push(error);
  7905. } else {
  7906. ret[error.attribute] = [error];
  7907. }
  7908. });
  7909. return ret;
  7910. },
  7911. // In:
  7912. // [{error: "<message 1>", ...}, {error: "<message 2>", ...}]
  7913. // Out:
  7914. // ["<message 1>", "<message 2>"]
  7915. flattenErrorsToArray: function(errors) {
  7916. return errors
  7917. .map(function(error) { return error.error; })
  7918. .filter(function(value, index, self) {
  7919. return self.indexOf(value) === index;
  7920. });
  7921. },
  7922. cleanAttributes: function(attributes, whitelist) {
  7923. function whitelistCreator(obj, key, last) {
  7924. if (v.isObject(obj[key])) {
  7925. return obj[key];
  7926. }
  7927. return (obj[key] = last ? true : {});
  7928. }
  7929. function buildObjectWhitelist(whitelist) {
  7930. var ow = {}
  7931. , lastObject
  7932. , attr;
  7933. for (attr in whitelist) {
  7934. if (!whitelist[attr]) {
  7935. continue;
  7936. }
  7937. v.forEachKeyInKeypath(ow, attr, whitelistCreator);
  7938. }
  7939. return ow;
  7940. }
  7941. function cleanRecursive(attributes, whitelist) {
  7942. if (!v.isObject(attributes)) {
  7943. return attributes;
  7944. }
  7945. var ret = v.extend({}, attributes)
  7946. , w
  7947. , attribute;
  7948. for (attribute in attributes) {
  7949. w = whitelist[attribute];
  7950. if (v.isObject(w)) {
  7951. ret[attribute] = cleanRecursive(ret[attribute], w);
  7952. } else if (!w) {
  7953. delete ret[attribute];
  7954. }
  7955. }
  7956. return ret;
  7957. }
  7958. if (!v.isObject(whitelist) || !v.isObject(attributes)) {
  7959. return {};
  7960. }
  7961. whitelist = buildObjectWhitelist(whitelist);
  7962. return cleanRecursive(attributes, whitelist);
  7963. },
  7964. exposeModule: function(validate, root, exports, module, define) {
  7965. if (exports) {
  7966. if (module && module.exports) {
  7967. exports = module.exports = validate;
  7968. }
  7969. exports.validate = validate;
  7970. } else {
  7971. root.validate = validate;
  7972. if (validate.isFunction(define) && define.amd) {
  7973. define([], function () { return validate; });
  7974. }
  7975. }
  7976. },
  7977. warn: function(msg) {
  7978. if (typeof console !== "undefined" && console.warn) {
  7979. console.warn("[validate.js] " + msg);
  7980. }
  7981. },
  7982. error: function(msg) {
  7983. if (typeof console !== "undefined" && console.error) {
  7984. console.error("[validate.js] " + msg);
  7985. }
  7986. }
  7987. });
  7988. validate.validators = {
  7989. // Presence validates that the value isn't empty
  7990. presence: function(value, options) {
  7991. options = v.extend({}, this.options, options);
  7992. if (options.allowEmpty !== false ? !v.isDefined(value) : v.isEmpty(value)) {
  7993. return options.message || this.message || "can't be blank";
  7994. }
  7995. },
  7996. length: function(value, options, attribute) {
  7997. // Empty values are allowed
  7998. if (!v.isDefined(value)) {
  7999. return;
  8000. }
  8001. options = v.extend({}, this.options, options);
  8002. var is = options.is
  8003. , maximum = options.maximum
  8004. , minimum = options.minimum
  8005. , tokenizer = options.tokenizer || function(val) { return val; }
  8006. , err
  8007. , errors = [];
  8008. value = tokenizer(value);
  8009. var length = value.length;
  8010. if(!v.isNumber(length)) {
  8011. return options.message || this.notValid || "has an incorrect length";
  8012. }
  8013. // Is checks
  8014. if (v.isNumber(is) && length !== is) {
  8015. err = options.wrongLength ||
  8016. this.wrongLength ||
  8017. "is the wrong length (should be %{count} characters)";
  8018. errors.push(v.format(err, {count: is}));
  8019. }
  8020. if (v.isNumber(minimum) && length < minimum) {
  8021. err = options.tooShort ||
  8022. this.tooShort ||
  8023. "is too short (minimum is %{count} characters)";
  8024. errors.push(v.format(err, {count: minimum}));
  8025. }
  8026. if (v.isNumber(maximum) && length > maximum) {
  8027. err = options.tooLong ||
  8028. this.tooLong ||
  8029. "is too long (maximum is %{count} characters)";
  8030. errors.push(v.format(err, {count: maximum}));
  8031. }
  8032. if (errors.length > 0) {
  8033. return options.message || errors;
  8034. }
  8035. },
  8036. numericality: function(value, options, attribute, attributes, globalOptions) {
  8037. // Empty values are fine
  8038. if (!v.isDefined(value)) {
  8039. return;
  8040. }
  8041. options = v.extend({}, this.options, options);
  8042. var errors = []
  8043. , name
  8044. , count
  8045. , checks = {
  8046. greaterThan: function(v, c) { return v > c; },
  8047. greaterThanOrEqualTo: function(v, c) { return v >= c; },
  8048. equalTo: function(v, c) { return v === c; },
  8049. lessThan: function(v, c) { return v < c; },
  8050. lessThanOrEqualTo: function(v, c) { return v <= c; },
  8051. divisibleBy: function(v, c) { return v % c === 0; }
  8052. }
  8053. , prettify = options.prettify ||
  8054. (globalOptions && globalOptions.prettify) ||
  8055. v.prettify;
  8056. // Strict will check that it is a valid looking number
  8057. if (v.isString(value) && options.strict) {
  8058. var pattern = "^-?(0|[1-9]\\d*)";
  8059. if (!options.onlyInteger) {
  8060. pattern += "(\\.\\d+)?";
  8061. }
  8062. pattern += "$";
  8063. if (!(new RegExp(pattern).test(value))) {
  8064. return options.message ||
  8065. options.notValid ||
  8066. this.notValid ||
  8067. this.message ||
  8068. "must be a valid number";
  8069. }
  8070. }
  8071. // Coerce the value to a number unless we're being strict.
  8072. if (options.noStrings !== true && v.isString(value) && !v.isEmpty(value)) {
  8073. value = +value;
  8074. }
  8075. // If it's not a number we shouldn't continue since it will compare it.
  8076. if (!v.isNumber(value)) {
  8077. return options.message ||
  8078. options.notValid ||
  8079. this.notValid ||
  8080. this.message ||
  8081. "is not a number";
  8082. }
  8083. // Same logic as above, sort of. Don't bother with comparisons if this
  8084. // doesn't pass.
  8085. if (options.onlyInteger && !v.isInteger(value)) {
  8086. return options.message ||
  8087. options.notInteger ||
  8088. this.notInteger ||
  8089. this.message ||
  8090. "must be an integer";
  8091. }
  8092. for (name in checks) {
  8093. count = options[name];
  8094. if (v.isNumber(count) && !checks[name](value, count)) {
  8095. // This picks the default message if specified
  8096. // For example the greaterThan check uses the message from
  8097. // this.notGreaterThan so we capitalize the name and prepend "not"
  8098. var key = "not" + v.capitalize(name);
  8099. var msg = options[key] ||
  8100. this[key] ||
  8101. this.message ||
  8102. "must be %{type} %{count}";
  8103. errors.push(v.format(msg, {
  8104. count: count,
  8105. type: prettify(name)
  8106. }));
  8107. }
  8108. }
  8109. if (options.odd && value % 2 !== 1) {
  8110. errors.push(options.notOdd ||
  8111. this.notOdd ||
  8112. this.message ||
  8113. "must be odd");
  8114. }
  8115. if (options.even && value % 2 !== 0) {
  8116. errors.push(options.notEven ||
  8117. this.notEven ||
  8118. this.message ||
  8119. "must be even");
  8120. }
  8121. if (errors.length) {
  8122. return options.message || errors;
  8123. }
  8124. },
  8125. datetime: v.extend(function(value, options) {
  8126. if (!v.isFunction(this.parse) || !v.isFunction(this.format)) {
  8127. throw new Error("Both the parse and format functions needs to be set to use the datetime/date validator");
  8128. }
  8129. // Empty values are fine
  8130. if (!v.isDefined(value)) {
  8131. return;
  8132. }
  8133. options = v.extend({}, this.options, options);
  8134. var err
  8135. , errors = []
  8136. , earliest = options.earliest ? this.parse(options.earliest, options) : NaN
  8137. , latest = options.latest ? this.parse(options.latest, options) : NaN;
  8138. value = this.parse(value, options);
  8139. // 86400000 is the number of milliseconds in a day, this is used to remove
  8140. // the time from the date
  8141. if (isNaN(value) || options.dateOnly && value % 86400000 !== 0) {
  8142. err = options.notValid ||
  8143. options.message ||
  8144. this.notValid ||
  8145. "must be a valid date";
  8146. return v.format(err, {value: arguments[0]});
  8147. }
  8148. if (!isNaN(earliest) && value < earliest) {
  8149. err = options.tooEarly ||
  8150. options.message ||
  8151. this.tooEarly ||
  8152. "must be no earlier than %{date}";
  8153. err = v.format(err, {
  8154. value: this.format(value, options),
  8155. date: this.format(earliest, options)
  8156. });
  8157. errors.push(err);
  8158. }
  8159. if (!isNaN(latest) && value > latest) {
  8160. err = options.tooLate ||
  8161. options.message ||
  8162. this.tooLate ||
  8163. "must be no later than %{date}";
  8164. err = v.format(err, {
  8165. date: this.format(latest, options),
  8166. value: this.format(value, options)
  8167. });
  8168. errors.push(err);
  8169. }
  8170. if (errors.length) {
  8171. return v.unique(errors);
  8172. }
  8173. }, {
  8174. parse: null,
  8175. format: null
  8176. }),
  8177. date: function(value, options) {
  8178. options = v.extend({}, options, {dateOnly: true});
  8179. return v.validators.datetime.call(v.validators.datetime, value, options);
  8180. },
  8181. format: function(value, options) {
  8182. if (v.isString(options) || (options instanceof RegExp)) {
  8183. options = {pattern: options};
  8184. }
  8185. options = v.extend({}, this.options, options);
  8186. var message = options.message || this.message || "is invalid"
  8187. , pattern = options.pattern
  8188. , match;
  8189. // Empty values are allowed
  8190. if (!v.isDefined(value)) {
  8191. return;
  8192. }
  8193. if (!v.isString(value)) {
  8194. return message;
  8195. }
  8196. if (v.isString(pattern)) {
  8197. pattern = new RegExp(options.pattern, options.flags);
  8198. }
  8199. match = pattern.exec(value);
  8200. if (!match || match[0].length != value.length) {
  8201. return message;
  8202. }
  8203. },
  8204. inclusion: function(value, options) {
  8205. // Empty values are fine
  8206. if (!v.isDefined(value)) {
  8207. return;
  8208. }
  8209. if (v.isArray(options)) {
  8210. options = {within: options};
  8211. }
  8212. options = v.extend({}, this.options, options);
  8213. if (v.contains(options.within, value)) {
  8214. return;
  8215. }
  8216. var message = options.message ||
  8217. this.message ||
  8218. "^%{value} is not included in the list";
  8219. return v.format(message, {value: value});
  8220. },
  8221. exclusion: function(value, options) {
  8222. // Empty values are fine
  8223. if (!v.isDefined(value)) {
  8224. return;
  8225. }
  8226. if (v.isArray(options)) {
  8227. options = {within: options};
  8228. }
  8229. options = v.extend({}, this.options, options);
  8230. if (!v.contains(options.within, value)) {
  8231. return;
  8232. }
  8233. var message = options.message || this.message || "^%{value} is restricted";
  8234. if (v.isString(options.within[value])) {
  8235. value = options.within[value];
  8236. }
  8237. return v.format(message, {value: value});
  8238. },
  8239. email: v.extend(function(value, options) {
  8240. options = v.extend({}, this.options, options);
  8241. var message = options.message || this.message || "is not a valid email";
  8242. // Empty values are fine
  8243. if (!v.isDefined(value)) {
  8244. return;
  8245. }
  8246. if (!v.isString(value)) {
  8247. return message;
  8248. }
  8249. if (!this.PATTERN.exec(value)) {
  8250. return message;
  8251. }
  8252. }, {
  8253. 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
  8254. }),
  8255. equality: function(value, options, attribute, attributes, globalOptions) {
  8256. if (!v.isDefined(value)) {
  8257. return;
  8258. }
  8259. if (v.isString(options)) {
  8260. options = {attribute: options};
  8261. }
  8262. options = v.extend({}, this.options, options);
  8263. var message = options.message ||
  8264. this.message ||
  8265. "is not equal to %{attribute}";
  8266. if (v.isEmpty(options.attribute) || !v.isString(options.attribute)) {
  8267. throw new Error("The attribute must be a non empty string");
  8268. }
  8269. var otherValue = v.getDeepObjectValue(attributes, options.attribute)
  8270. , comparator = options.comparator || function(v1, v2) {
  8271. return v1 === v2;
  8272. }
  8273. , prettify = options.prettify ||
  8274. (globalOptions && globalOptions.prettify) ||
  8275. v.prettify;
  8276. if (!comparator(value, otherValue, options, attribute, attributes)) {
  8277. return v.format(message, {attribute: prettify(options.attribute)});
  8278. }
  8279. },
  8280. // A URL validator that is used to validate URLs with the ability to
  8281. // restrict schemes and some domains.
  8282. url: function(value, options) {
  8283. if (!v.isDefined(value)) {
  8284. return;
  8285. }
  8286. options = v.extend({}, this.options, options);
  8287. var message = options.message || this.message || "is not a valid url"
  8288. , schemes = options.schemes || this.schemes || ['http', 'https']
  8289. , allowLocal = options.allowLocal || this.allowLocal || false
  8290. , allowDataUrl = options.allowDataUrl || this.allowDataUrl || false;
  8291. if (!v.isString(value)) {
  8292. return message;
  8293. }
  8294. // https://gist.github.com/dperini/729294
  8295. var regex =
  8296. "^" +
  8297. // protocol identifier
  8298. "(?:(?:" + schemes.join("|") + ")://)" +
  8299. // user:pass authentication
  8300. "(?:\\S+(?::\\S*)?@)?" +
  8301. "(?:";
  8302. var tld = "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))";
  8303. if (allowLocal) {
  8304. tld += "?";
  8305. } else {
  8306. regex +=
  8307. // IP address exclusion
  8308. // private & local networks
  8309. "(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
  8310. "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
  8311. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})";
  8312. }
  8313. regex +=
  8314. // IP address dotted notation octets
  8315. // excludes loopback network 0.0.0.0
  8316. // excludes reserved space >= 224.0.0.0
  8317. // excludes network & broacast addresses
  8318. // (first & last IP address of each class)
  8319. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  8320. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  8321. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  8322. "|" +
  8323. // host name
  8324. "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
  8325. // domain name
  8326. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
  8327. tld +
  8328. ")" +
  8329. // port number
  8330. "(?::\\d{2,5})?" +
  8331. // resource path
  8332. "(?:[/?#]\\S*)?" +
  8333. "$";
  8334. if (allowDataUrl) {
  8335. // RFC 2397
  8336. var mediaType = "\\w+\\/[-+.\\w]+(?:;[\\w=]+)*";
  8337. var urlchar = "[A-Za-z0-9-_.!~\\*'();\\/?:@&=+$,%]*";
  8338. var dataurl = "data:(?:"+mediaType+")?(?:;base64)?,"+urlchar;
  8339. regex = "(?:"+regex+")|(?:^"+dataurl+"$)";
  8340. }
  8341. var PATTERN = new RegExp(regex, 'i');
  8342. if (!PATTERN.exec(value)) {
  8343. return message;
  8344. }
  8345. },
  8346. type: v.extend(function(value, originalOptions, attribute, attributes, globalOptions) {
  8347. if (v.isString(originalOptions)) {
  8348. originalOptions = {type: originalOptions};
  8349. }
  8350. if (!v.isDefined(value)) {
  8351. return;
  8352. }
  8353. var options = v.extend({}, this.options, originalOptions);
  8354. var type = options.type;
  8355. if (!v.isDefined(type)) {
  8356. throw new Error("No type was specified");
  8357. }
  8358. var check;
  8359. if (v.isFunction(type)) {
  8360. check = type;
  8361. } else {
  8362. check = this.types[type];
  8363. }
  8364. if (!v.isFunction(check)) {
  8365. throw new Error("validate.validators.type.types." + type + " must be a function.");
  8366. }
  8367. if (!check(value, options, attribute, attributes, globalOptions)) {
  8368. var message = originalOptions.message ||
  8369. this.messages[type] ||
  8370. this.message ||
  8371. options.message ||
  8372. (v.isFunction(type) ? "must be of the correct type" : "must be of type %{type}");
  8373. if (v.isFunction(message)) {
  8374. message = message(value, originalOptions, attribute, attributes, globalOptions);
  8375. }
  8376. return v.format(message, {attribute: v.prettify(attribute), type: type});
  8377. }
  8378. }, {
  8379. types: {
  8380. object: function(value) {
  8381. return v.isObject(value) && !v.isArray(value);
  8382. },
  8383. array: v.isArray,
  8384. integer: v.isInteger,
  8385. number: v.isNumber,
  8386. string: v.isString,
  8387. date: v.isDate,
  8388. boolean: v.isBoolean
  8389. },
  8390. messages: {}
  8391. })
  8392. };
  8393. validate.formatters = {
  8394. detailed: function(errors) {return errors;},
  8395. flat: v.flattenErrorsToArray,
  8396. grouped: function(errors) {
  8397. var attr;
  8398. errors = v.groupErrorsByAttribute(errors);
  8399. for (attr in errors) {
  8400. errors[attr] = v.flattenErrorsToArray(errors[attr]);
  8401. }
  8402. return errors;
  8403. },
  8404. constraint: function(errors) {
  8405. var attr;
  8406. errors = v.groupErrorsByAttribute(errors);
  8407. for (attr in errors) {
  8408. errors[attr] = errors[attr].map(function(result) {
  8409. return result.validator;
  8410. }).sort();
  8411. }
  8412. return errors;
  8413. }
  8414. };
  8415. validate.exposeModule(validate, this, exports, module, __webpack_require__.amdD);
  8416. }).call(this,
  8417. true ? /* istanbul ignore next */ exports : 0,
  8418. true ? /* istanbul ignore next */ module : 0,
  8419. __webpack_require__.amdD);
  8420. /***/ })
  8421. /******/ });
  8422. /************************************************************************/
  8423. /******/ // The module cache
  8424. /******/ var __webpack_module_cache__ = {};
  8425. /******/
  8426. /******/ // The require function
  8427. /******/ function __webpack_require__(moduleId) {
  8428. /******/ // Check if module is in cache
  8429. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  8430. /******/ if (cachedModule !== undefined) {
  8431. /******/ return cachedModule.exports;
  8432. /******/ }
  8433. /******/ // Create a new module (and put it into the cache)
  8434. /******/ var module = __webpack_module_cache__[moduleId] = {
  8435. /******/ id: moduleId,
  8436. /******/ loaded: false,
  8437. /******/ exports: {}
  8438. /******/ };
  8439. /******/
  8440. /******/ // Execute the module function
  8441. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  8442. /******/
  8443. /******/ // Flag the module as loaded
  8444. /******/ module.loaded = true;
  8445. /******/
  8446. /******/ // Return the exports of the module
  8447. /******/ return module.exports;
  8448. /******/ }
  8449. /******/
  8450. /************************************************************************/
  8451. /******/ /* webpack/runtime/amd define */
  8452. /******/ (() => {
  8453. /******/ __webpack_require__.amdD = function () {
  8454. /******/ throw new Error('define cannot be used indirect');
  8455. /******/ };
  8456. /******/ })();
  8457. /******/
  8458. /******/ /* webpack/runtime/compat get default export */
  8459. /******/ (() => {
  8460. /******/ // getDefaultExport function for compatibility with non-harmony modules
  8461. /******/ __webpack_require__.n = (module) => {
  8462. /******/ var getter = module && module.__esModule ?
  8463. /******/ () => (module['default']) :
  8464. /******/ () => (module);
  8465. /******/ __webpack_require__.d(getter, { a: getter });
  8466. /******/ return getter;
  8467. /******/ };
  8468. /******/ })();
  8469. /******/
  8470. /******/ /* webpack/runtime/define property getters */
  8471. /******/ (() => {
  8472. /******/ // define getter functions for harmony exports
  8473. /******/ __webpack_require__.d = (exports, definition) => {
  8474. /******/ for(var key in definition) {
  8475. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  8476. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  8477. /******/ }
  8478. /******/ }
  8479. /******/ };
  8480. /******/ })();
  8481. /******/
  8482. /******/ /* webpack/runtime/global */
  8483. /******/ (() => {
  8484. /******/ __webpack_require__.g = (function() {
  8485. /******/ if (typeof globalThis === 'object') return globalThis;
  8486. /******/ try {
  8487. /******/ return this || new Function('return this')();
  8488. /******/ } catch (e) {
  8489. /******/ if (typeof window === 'object') return window;
  8490. /******/ }
  8491. /******/ })();
  8492. /******/ })();
  8493. /******/
  8494. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  8495. /******/ (() => {
  8496. /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
  8497. /******/ })();
  8498. /******/
  8499. /******/ /* webpack/runtime/make namespace object */
  8500. /******/ (() => {
  8501. /******/ // define __esModule on exports
  8502. /******/ __webpack_require__.r = (exports) => {
  8503. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  8504. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  8505. /******/ }
  8506. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  8507. /******/ };
  8508. /******/ })();
  8509. /******/
  8510. /******/ /* webpack/runtime/node module decorator */
  8511. /******/ (() => {
  8512. /******/ __webpack_require__.nmd = (module) => {
  8513. /******/ module.paths = [];
  8514. /******/ if (!module.children) module.children = [];
  8515. /******/ return module;
  8516. /******/ };
  8517. /******/ })();
  8518. /******/
  8519. /************************************************************************/
  8520. var __webpack_exports__ = {};
  8521. // This entry need to be wrapped in an IIFE because it need to be in strict mode.
  8522. (() => {
  8523. "use strict";
  8524. /*!*******************************!*\
  8525. !*** ./resources/js/users.js ***!
  8526. \*******************************/
  8527. __webpack_require__.r(__webpack_exports__);
  8528. /* harmony import */ var riot__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! riot */ "./node_modules/riot/riot.esm.js");
  8529. /* harmony import */ var _components_users_riot__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components/users.riot */ "./resources/js/components/users.riot");
  8530. /* harmony import */ var _components_users_form_riot__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./components/users/form.riot */ "./resources/js/components/users/form.riot");
  8531. /* harmony import */ var _components_sidebar_button_riot__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./components/sidebar-button.riot */ "./resources/js/components/sidebar-button.riot");
  8532. // register components for buckets
  8533. riot__WEBPACK_IMPORTED_MODULE_3__.register('app-users', _components_users_riot__WEBPACK_IMPORTED_MODULE_0__.default);
  8534. riot__WEBPACK_IMPORTED_MODULE_3__.mount('app-users');
  8535. riot__WEBPACK_IMPORTED_MODULE_3__.register('app-users-form', _components_users_form_riot__WEBPACK_IMPORTED_MODULE_1__.default);
  8536. riot__WEBPACK_IMPORTED_MODULE_3__.mount('app-users-form');
  8537. riot__WEBPACK_IMPORTED_MODULE_3__.register('app-sidebar-button', _components_sidebar_button_riot__WEBPACK_IMPORTED_MODULE_2__.default);
  8538. riot__WEBPACK_IMPORTED_MODULE_3__.mount('app-sidebar-button');
  8539. })();
  8540. /******/ })()
  8541. ;