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.

2712 lines
83 KiB

  1. /******/ (function(modules) { // webpackBootstrap
  2. /******/ // The module cache
  3. /******/ var installedModules = {};
  4. /******/
  5. /******/ // The require function
  6. /******/ function __webpack_require__(moduleId) {
  7. /******/
  8. /******/ // Check if module is in cache
  9. /******/ if(installedModules[moduleId]) {
  10. /******/ return installedModules[moduleId].exports;
  11. /******/ }
  12. /******/ // Create a new module (and put it into the cache)
  13. /******/ var module = installedModules[moduleId] = {
  14. /******/ i: moduleId,
  15. /******/ l: false,
  16. /******/ exports: {}
  17. /******/ };
  18. /******/
  19. /******/ // Execute the module function
  20. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  21. /******/
  22. /******/ // Flag the module as loaded
  23. /******/ module.l = true;
  24. /******/
  25. /******/ // Return the exports of the module
  26. /******/ return module.exports;
  27. /******/ }
  28. /******/
  29. /******/
  30. /******/ // expose the modules object (__webpack_modules__)
  31. /******/ __webpack_require__.m = modules;
  32. /******/
  33. /******/ // expose the module cache
  34. /******/ __webpack_require__.c = installedModules;
  35. /******/
  36. /******/ // define getter function for harmony exports
  37. /******/ __webpack_require__.d = function(exports, name, getter) {
  38. /******/ if(!__webpack_require__.o(exports, name)) {
  39. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  40. /******/ }
  41. /******/ };
  42. /******/
  43. /******/ // define __esModule on exports
  44. /******/ __webpack_require__.r = function(exports) {
  45. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  46. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  47. /******/ }
  48. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  49. /******/ };
  50. /******/
  51. /******/ // create a fake namespace object
  52. /******/ // mode & 1: value is a module id, require it
  53. /******/ // mode & 2: merge all properties of value into the ns
  54. /******/ // mode & 4: return value when already ns object
  55. /******/ // mode & 8|1: behave like require
  56. /******/ __webpack_require__.t = function(value, mode) {
  57. /******/ if(mode & 1) value = __webpack_require__(value);
  58. /******/ if(mode & 8) return value;
  59. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  60. /******/ var ns = Object.create(null);
  61. /******/ __webpack_require__.r(ns);
  62. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  63. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  64. /******/ return ns;
  65. /******/ };
  66. /******/
  67. /******/ // getDefaultExport function for compatibility with non-harmony modules
  68. /******/ __webpack_require__.n = function(module) {
  69. /******/ var getter = module && module.__esModule ?
  70. /******/ function getDefault() { return module['default']; } :
  71. /******/ function getModuleExports() { return module; };
  72. /******/ __webpack_require__.d(getter, 'a', getter);
  73. /******/ return getter;
  74. /******/ };
  75. /******/
  76. /******/ // Object.prototype.hasOwnProperty.call
  77. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  78. /******/
  79. /******/ // __webpack_public_path__
  80. /******/ __webpack_require__.p = "/";
  81. /******/
  82. /******/
  83. /******/ // Load entry module and return exports
  84. /******/ return __webpack_require__(__webpack_require__.s = 0);
  85. /******/ })
  86. /************************************************************************/
  87. /******/ ({
  88. /***/ "./demo-386.js":
  89. /*!*********************!*\
  90. !*** ./demo-386.js ***!
  91. \*********************/
  92. /*! no exports provided */
  93. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  94. "use strict";
  95. __webpack_require__.r(__webpack_exports__);
  96. /* harmony import */ var riot__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! riot */ "./node_modules/riot/riot.esm.js");
  97. /* harmony import */ var _src_TinyOnePage_riot__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./src/TinyOnePage.riot */ "./src/TinyOnePage.riot");
  98. riot__WEBPACK_IMPORTED_MODULE_0__["register"]('tiny-one-page', _src_TinyOnePage_riot__WEBPACK_IMPORTED_MODULE_1__["default"]); // adding component with animate object
  99. riot__WEBPACK_IMPORTED_MODULE_0__["mount"]('tiny-one-page');
  100. /***/ }),
  101. /***/ "./demo-386.scss":
  102. /*!***********************!*\
  103. !*** ./demo-386.scss ***!
  104. \***********************/
  105. /*! no static exports found */
  106. /***/ (function(module, exports) {
  107. // removed by extract-text-webpack-plugin
  108. /***/ }),
  109. /***/ "./node_modules/riot/riot.esm.js":
  110. /*!***************************************!*\
  111. !*** ./node_modules/riot/riot.esm.js ***!
  112. \***************************************/
  113. /*! exports provided: __, component, install, mount, register, uninstall, unmount, unregister, version */
  114. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  115. "use strict";
  116. __webpack_require__.r(__webpack_exports__);
  117. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__", function() { return __; });
  118. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "component", function() { return component; });
  119. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "install", function() { return install; });
  120. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mount", function() { return mount; });
  121. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "register", function() { return register; });
  122. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "uninstall", function() { return uninstall; });
  123. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unmount", function() { return unmount; });
  124. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unregister", function() { return unregister; });
  125. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; });
  126. /* Riot v4.5.0, @license MIT */
  127. const COMPONENTS_IMPLEMENTATION_MAP = new Map(),
  128. DOM_COMPONENT_INSTANCE_PROPERTY = Symbol('riot-component'),
  129. PLUGINS_SET = new Set(),
  130. IS_DIRECTIVE = 'is',
  131. VALUE_ATTRIBUTE = 'value',
  132. ATTRIBUTES_KEY_SYMBOL = Symbol('attributes'),
  133. TEMPLATE_KEY_SYMBOL = Symbol('template');
  134. var globals = /*#__PURE__*/Object.freeze({
  135. COMPONENTS_IMPLEMENTATION_MAP: COMPONENTS_IMPLEMENTATION_MAP,
  136. DOM_COMPONENT_INSTANCE_PROPERTY: DOM_COMPONENT_INSTANCE_PROPERTY,
  137. PLUGINS_SET: PLUGINS_SET,
  138. IS_DIRECTIVE: IS_DIRECTIVE,
  139. VALUE_ATTRIBUTE: VALUE_ATTRIBUTE,
  140. ATTRIBUTES_KEY_SYMBOL: ATTRIBUTES_KEY_SYMBOL,
  141. TEMPLATE_KEY_SYMBOL: TEMPLATE_KEY_SYMBOL
  142. });
  143. /**
  144. * Remove the child nodes from any DOM node
  145. * @param {HTMLElement} node - target node
  146. * @returns {undefined}
  147. */
  148. function cleanNode(node) {
  149. clearChildren(node.childNodes);
  150. }
  151. /**
  152. * Clear multiple children in a node
  153. * @param {HTMLElement[]} children - direct children nodes
  154. * @returns {undefined}
  155. */
  156. function clearChildren(children) {
  157. Array.from(children).forEach(n => n.parentNode && n.parentNode.removeChild(n));
  158. }
  159. const EACH = 0;
  160. const IF = 1;
  161. const SIMPLE = 2;
  162. const TAG = 3;
  163. const SLOT = 4;
  164. var bindingTypes = {
  165. EACH,
  166. IF,
  167. SIMPLE,
  168. TAG,
  169. SLOT
  170. };
  171. /**
  172. * Create the template meta object in case of <template> fragments
  173. * @param {TemplateChunk} componentTemplate - template chunk object
  174. * @returns {Object} the meta property that will be passed to the mount function of the TemplateChunk
  175. */
  176. function createTemplateMeta(componentTemplate) {
  177. const fragment = componentTemplate.dom.cloneNode(true);
  178. return {
  179. avoidDOMInjection: true,
  180. fragment,
  181. children: Array.from(fragment.childNodes)
  182. };
  183. }
  184. /* get rid of the @ungap/essential-map polyfill */
  185. const {
  186. indexOf: iOF
  187. } = [];
  188. const append = (get, parent, children, start, end, before) => {
  189. const isSelect = 'selectedIndex' in parent;
  190. let noSelection = isSelect;
  191. while (start < end) {
  192. const child = get(children[start], 1);
  193. parent.insertBefore(child, before);
  194. if (isSelect && noSelection && child.selected) {
  195. noSelection = !noSelection;
  196. let {
  197. selectedIndex
  198. } = parent;
  199. parent.selectedIndex = selectedIndex < 0 ? start : iOF.call(parent.querySelectorAll('option'), child);
  200. }
  201. start++;
  202. }
  203. };
  204. const eqeq = (a, b) => a == b;
  205. const identity = O => O;
  206. const indexOf = (moreNodes, moreStart, moreEnd, lessNodes, lessStart, lessEnd, compare) => {
  207. const length = lessEnd - lessStart;
  208. /* istanbul ignore if */
  209. if (length < 1) return -1;
  210. while (moreEnd - moreStart >= length) {
  211. let m = moreStart;
  212. let l = lessStart;
  213. while (m < moreEnd && l < lessEnd && compare(moreNodes[m], lessNodes[l])) {
  214. m++;
  215. l++;
  216. }
  217. if (l === lessEnd) return moreStart;
  218. moreStart = m + 1;
  219. }
  220. return -1;
  221. };
  222. const isReversed = (futureNodes, futureEnd, currentNodes, currentStart, currentEnd, compare) => {
  223. while (currentStart < currentEnd && compare(currentNodes[currentStart], futureNodes[futureEnd - 1])) {
  224. currentStart++;
  225. futureEnd--;
  226. }
  227. return futureEnd === 0;
  228. };
  229. const next = (get, list, i, length, before) => i < length ? get(list[i], 0) : 0 < i ? get(list[i - 1], -0).nextSibling : before;
  230. const remove = (get, parent, children, start, end) => {
  231. if (end - start < 2) parent.removeChild(get(children[start], -1));else {
  232. const range = parent.ownerDocument.createRange();
  233. range.setStartBefore(get(children[start], -1));
  234. range.setEndAfter(get(children[end - 1], -1));
  235. range.deleteContents();
  236. }
  237. }; // - - - - - - - - - - - - - - - - - - -
  238. // diff related constants and utilities
  239. // - - - - - - - - - - - - - - - - - - -
  240. const DELETION = -1;
  241. const INSERTION = 1;
  242. const SKIP = 0;
  243. const SKIP_OND = 50;
  244. const HS = (futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges) => {
  245. let k = 0;
  246. /* istanbul ignore next */
  247. let minLen = futureChanges < currentChanges ? futureChanges : currentChanges;
  248. const link = Array(minLen++);
  249. const tresh = Array(minLen);
  250. tresh[0] = -1;
  251. for (let i = 1; i < minLen; i++) tresh[i] = currentEnd;
  252. const keymap = new Map();
  253. for (let i = currentStart; i < currentEnd; i++) keymap.set(currentNodes[i], i);
  254. for (let i = futureStart; i < futureEnd; i++) {
  255. const idxInOld = keymap.get(futureNodes[i]);
  256. if (idxInOld != null) {
  257. k = findK(tresh, minLen, idxInOld);
  258. /* istanbul ignore else */
  259. if (-1 < k) {
  260. tresh[k] = idxInOld;
  261. link[k] = {
  262. newi: i,
  263. oldi: idxInOld,
  264. prev: link[k - 1]
  265. };
  266. }
  267. }
  268. }
  269. k = --minLen;
  270. --currentEnd;
  271. while (tresh[k] > currentEnd) --k;
  272. minLen = currentChanges + futureChanges - k;
  273. const diff = Array(minLen);
  274. let ptr = link[k];
  275. --futureEnd;
  276. while (ptr) {
  277. const {
  278. newi,
  279. oldi
  280. } = ptr;
  281. while (futureEnd > newi) {
  282. diff[--minLen] = INSERTION;
  283. --futureEnd;
  284. }
  285. while (currentEnd > oldi) {
  286. diff[--minLen] = DELETION;
  287. --currentEnd;
  288. }
  289. diff[--minLen] = SKIP;
  290. --futureEnd;
  291. --currentEnd;
  292. ptr = ptr.prev;
  293. }
  294. while (futureEnd >= futureStart) {
  295. diff[--minLen] = INSERTION;
  296. --futureEnd;
  297. }
  298. while (currentEnd >= currentStart) {
  299. diff[--minLen] = DELETION;
  300. --currentEnd;
  301. }
  302. return diff;
  303. }; // this is pretty much the same petit-dom code without the delete map part
  304. // https://github.com/yelouafi/petit-dom/blob/bd6f5c919b5ae5297be01612c524c40be45f14a7/src/vdom.js#L556-L561
  305. const OND = (futureNodes, futureStart, rows, currentNodes, currentStart, cols, compare) => {
  306. const length = rows + cols;
  307. const v = [];
  308. let d, k, r, c, pv, cv, pd;
  309. outer: for (d = 0; d <= length; d++) {
  310. /* istanbul ignore if */
  311. if (d > SKIP_OND) return null;
  312. pd = d - 1;
  313. /* istanbul ignore next */
  314. pv = d ? v[d - 1] : [0, 0];
  315. cv = v[d] = [];
  316. for (k = -d; k <= d; k += 2) {
  317. if (k === -d || k !== d && pv[pd + k - 1] < pv[pd + k + 1]) {
  318. c = pv[pd + k + 1];
  319. } else {
  320. c = pv[pd + k - 1] + 1;
  321. }
  322. r = c - k;
  323. while (c < cols && r < rows && compare(currentNodes[currentStart + c], futureNodes[futureStart + r])) {
  324. c++;
  325. r++;
  326. }
  327. if (c === cols && r === rows) {
  328. break outer;
  329. }
  330. cv[d + k] = c;
  331. }
  332. }
  333. const diff = Array(d / 2 + length / 2);
  334. let diffIdx = diff.length - 1;
  335. for (d = v.length - 1; d >= 0; d--) {
  336. while (c > 0 && r > 0 && compare(currentNodes[currentStart + c - 1], futureNodes[futureStart + r - 1])) {
  337. // diagonal edge = equality
  338. diff[diffIdx--] = SKIP;
  339. c--;
  340. r--;
  341. }
  342. if (!d) break;
  343. pd = d - 1;
  344. /* istanbul ignore next */
  345. pv = d ? v[d - 1] : [0, 0];
  346. k = c - r;
  347. if (k === -d || k !== d && pv[pd + k - 1] < pv[pd + k + 1]) {
  348. // vertical edge = insertion
  349. r--;
  350. diff[diffIdx--] = INSERTION;
  351. } else {
  352. // horizontal edge = deletion
  353. c--;
  354. diff[diffIdx--] = DELETION;
  355. }
  356. }
  357. return diff;
  358. };
  359. const applyDiff = (diff, get, parentNode, futureNodes, futureStart, currentNodes, currentStart, currentLength, before) => {
  360. const live = new Map();
  361. const length = diff.length;
  362. let currentIndex = currentStart;
  363. let i = 0;
  364. while (i < length) {
  365. switch (diff[i++]) {
  366. case SKIP:
  367. futureStart++;
  368. currentIndex++;
  369. break;
  370. case INSERTION:
  371. // TODO: bulk appends for sequential nodes
  372. live.set(futureNodes[futureStart], 1);
  373. append(get, parentNode, futureNodes, futureStart++, futureStart, currentIndex < currentLength ? get(currentNodes[currentIndex], 0) : before);
  374. break;
  375. case DELETION:
  376. currentIndex++;
  377. break;
  378. }
  379. }
  380. i = 0;
  381. while (i < length) {
  382. switch (diff[i++]) {
  383. case SKIP:
  384. currentStart++;
  385. break;
  386. case DELETION:
  387. // TODO: bulk removes for sequential nodes
  388. if (live.has(currentNodes[currentStart])) currentStart++;else remove(get, parentNode, currentNodes, currentStart++, currentStart);
  389. break;
  390. }
  391. }
  392. };
  393. const findK = (ktr, length, j) => {
  394. let lo = 1;
  395. let hi = length;
  396. while (lo < hi) {
  397. const mid = (lo + hi) / 2 >>> 0;
  398. if (j < ktr[mid]) hi = mid;else lo = mid + 1;
  399. }
  400. return lo;
  401. };
  402. const smartDiff = (get, parentNode, futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges, currentLength, compare, before) => {
  403. applyDiff(OND(futureNodes, futureStart, futureChanges, currentNodes, currentStart, currentChanges, compare) || HS(futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges), get, parentNode, futureNodes, futureStart, currentNodes, currentStart, currentLength, before);
  404. };
  405. /*! (c) 2018 Andrea Giammarchi (ISC) */
  406. const domdiff = (parentNode, // where changes happen
  407. currentNodes, // Array of current items/nodes
  408. futureNodes, // Array of future items/nodes
  409. options // optional object with one of the following properties
  410. // before: domNode
  411. // compare(generic, generic) => true if same generic
  412. // node(generic) => Node
  413. ) => {
  414. if (!options) options = {};
  415. const compare = options.compare || eqeq;
  416. const get = options.node || identity;
  417. const before = options.before == null ? null : get(options.before, 0);
  418. const currentLength = currentNodes.length;
  419. let currentEnd = currentLength;
  420. let currentStart = 0;
  421. let futureEnd = futureNodes.length;
  422. let futureStart = 0; // common prefix
  423. while (currentStart < currentEnd && futureStart < futureEnd && compare(currentNodes[currentStart], futureNodes[futureStart])) {
  424. currentStart++;
  425. futureStart++;
  426. } // common suffix
  427. while (currentStart < currentEnd && futureStart < futureEnd && compare(currentNodes[currentEnd - 1], futureNodes[futureEnd - 1])) {
  428. currentEnd--;
  429. futureEnd--;
  430. }
  431. const currentSame = currentStart === currentEnd;
  432. const futureSame = futureStart === futureEnd; // same list
  433. if (currentSame && futureSame) return futureNodes; // only stuff to add
  434. if (currentSame && futureStart < futureEnd) {
  435. append(get, parentNode, futureNodes, futureStart, futureEnd, next(get, currentNodes, currentStart, currentLength, before));
  436. return futureNodes;
  437. } // only stuff to remove
  438. if (futureSame && currentStart < currentEnd) {
  439. remove(get, parentNode, currentNodes, currentStart, currentEnd);
  440. return futureNodes;
  441. }
  442. const currentChanges = currentEnd - currentStart;
  443. const futureChanges = futureEnd - futureStart;
  444. let i = -1; // 2 simple indels: the shortest sequence is a subsequence of the longest
  445. if (currentChanges < futureChanges) {
  446. i = indexOf(futureNodes, futureStart, futureEnd, currentNodes, currentStart, currentEnd, compare); // inner diff
  447. if (-1 < i) {
  448. append(get, parentNode, futureNodes, futureStart, i, get(currentNodes[currentStart], 0));
  449. append(get, parentNode, futureNodes, i + currentChanges, futureEnd, next(get, currentNodes, currentEnd, currentLength, before));
  450. return futureNodes;
  451. }
  452. }
  453. /* istanbul ignore else */
  454. else if (futureChanges < currentChanges) {
  455. i = indexOf(currentNodes, currentStart, currentEnd, futureNodes, futureStart, futureEnd, compare); // outer diff
  456. if (-1 < i) {
  457. remove(get, parentNode, currentNodes, currentStart, i);
  458. remove(get, parentNode, currentNodes, i + futureChanges, currentEnd);
  459. return futureNodes;
  460. }
  461. } // common case with one replacement for many nodes
  462. // or many nodes replaced for a single one
  463. /* istanbul ignore else */
  464. if (currentChanges < 2 || futureChanges < 2) {
  465. append(get, parentNode, futureNodes, futureStart, futureEnd, get(currentNodes[currentStart], 0));
  466. remove(get, parentNode, currentNodes, currentStart, currentEnd);
  467. return futureNodes;
  468. } // the half match diff part has been skipped in petit-dom
  469. // https://github.com/yelouafi/petit-dom/blob/bd6f5c919b5ae5297be01612c524c40be45f14a7/src/vdom.js#L391-L397
  470. // accordingly, I think it's safe to skip in here too
  471. // if one day it'll come out like the speediest thing ever to do
  472. // then I might add it in here too
  473. // Extra: before going too fancy, what about reversed lists ?
  474. // This should bail out pretty quickly if that's not the case.
  475. if (currentChanges === futureChanges && isReversed(futureNodes, futureEnd, currentNodes, currentStart, currentEnd, compare)) {
  476. append(get, parentNode, futureNodes, futureStart, futureEnd, next(get, currentNodes, currentEnd, currentLength, before));
  477. return futureNodes;
  478. } // last resort through a smart diff
  479. smartDiff(get, parentNode, futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges, currentLength, compare, before);
  480. return futureNodes;
  481. };
  482. /**
  483. * Check if a value is null or undefined
  484. * @param {*} value - anything
  485. * @returns {boolean} true only for the 'undefined' and 'null' types
  486. */
  487. function isNil(value) {
  488. return value === null || value === undefined;
  489. }
  490. /**
  491. * Check if an element is a template tag
  492. * @param {HTMLElement} el - element to check
  493. * @returns {boolean} true if it's a <template>
  494. */
  495. function isTemplate(el) {
  496. return !isNil(el.content);
  497. }
  498. const EachBinding = Object.seal({
  499. // dynamic binding properties
  500. childrenMap: null,
  501. node: null,
  502. root: null,
  503. condition: null,
  504. evaluate: null,
  505. template: null,
  506. isTemplateTag: false,
  507. nodes: [],
  508. getKey: null,
  509. indexName: null,
  510. itemName: null,
  511. afterPlaceholder: null,
  512. placeholder: null,
  513. // API methods
  514. mount(scope, parentScope) {
  515. return this.update(scope, parentScope);
  516. },
  517. update(scope, parentScope) {
  518. const {
  519. placeholder
  520. } = this;
  521. const collection = this.evaluate(scope);
  522. const items = collection ? Array.from(collection) : [];
  523. const parent = placeholder.parentNode; // prepare the diffing
  524. const {
  525. newChildrenMap,
  526. batches,
  527. futureNodes
  528. } = createPatch(items, scope, parentScope, this); // patch the DOM only if there are new nodes
  529. if (futureNodes.length) {
  530. domdiff(parent, this.nodes, futureNodes, {
  531. before: placeholder,
  532. node: patch(Array.from(this.childrenMap.values()), parentScope)
  533. });
  534. } else {
  535. // remove all redundant templates
  536. unmountRedundant(this.childrenMap);
  537. } // trigger the mounts and the updates
  538. batches.forEach(fn => fn()); // update the children map
  539. this.childrenMap = newChildrenMap;
  540. this.nodes = futureNodes;
  541. return this;
  542. },
  543. unmount(scope, parentScope) {
  544. unmountRedundant(this.childrenMap, parentScope);
  545. this.childrenMap = new Map();
  546. this.nodes = [];
  547. return this;
  548. }
  549. });
  550. /**
  551. * Patch the DOM while diffing
  552. * @param {TemplateChunk[]} redundant - redundant tepmplate chunks
  553. * @param {*} parentScope - scope of the parent template
  554. * @returns {Function} patch function used by domdiff
  555. */
  556. function patch(redundant, parentScope) {
  557. return (item, info) => {
  558. if (info < 0) {
  559. const {
  560. template,
  561. context
  562. } = redundant.pop(); // notice that we pass null as last argument because
  563. // the root node and its children will be removed by domdiff
  564. template.unmount(context, parentScope, null);
  565. }
  566. return item;
  567. };
  568. }
  569. /**
  570. * Unmount the remaining template instances
  571. * @param {Map} childrenMap - map containing the children template to unmount
  572. * @param {*} parentScope - scope of the parent template
  573. * @returns {TemplateChunk[]} collection containing the template chunks unmounted
  574. */
  575. function unmountRedundant(childrenMap, parentScope) {
  576. return Array.from(childrenMap.values()).map((_ref) => {
  577. let {
  578. template,
  579. context
  580. } = _ref;
  581. return template.unmount(context, parentScope, true);
  582. });
  583. }
  584. /**
  585. * Check whether a template must be filtered from a loop
  586. * @param {Function} condition - filter function
  587. * @param {Object} context - argument passed to the filter function
  588. * @returns {boolean} true if this item should be skipped
  589. */
  590. function mustFilterItem(condition, context) {
  591. return condition ? Boolean(condition(context)) === false : false;
  592. }
  593. /**
  594. * Extend the scope of the looped template
  595. * @param {Object} scope - current template scope
  596. * @param {string} options.itemName - key to identify the looped item in the new context
  597. * @param {string} options.indexName - key to identify the index of the looped item
  598. * @param {number} options.index - current index
  599. * @param {*} options.item - collection item looped
  600. * @returns {Object} enhanced scope object
  601. */
  602. function extendScope(scope, _ref2) {
  603. let {
  604. itemName,
  605. indexName,
  606. index,
  607. item
  608. } = _ref2;
  609. scope[itemName] = item;
  610. if (indexName) scope[indexName] = index;
  611. return scope;
  612. }
  613. /**
  614. * Loop the current template items
  615. * @param {Array} items - expression collection value
  616. * @param {*} scope - template scope
  617. * @param {*} parentScope - scope of the parent template
  618. * @param {EeachBinding} binding - each binding object instance
  619. * @returns {Object} data
  620. * @returns {Map} data.newChildrenMap - a Map containing the new children template structure
  621. * @returns {Array} data.batches - array containing the template lifecycle functions to trigger
  622. * @returns {Array} data.futureNodes - array containing the nodes we need to diff
  623. */
  624. function createPatch(items, scope, parentScope, binding) {
  625. const {
  626. condition,
  627. template,
  628. childrenMap,
  629. itemName,
  630. getKey,
  631. indexName,
  632. root,
  633. isTemplateTag
  634. } = binding;
  635. const newChildrenMap = new Map();
  636. const batches = [];
  637. const futureNodes = [];
  638. items.forEach((item, index) => {
  639. const context = extendScope(Object.create(scope), {
  640. itemName,
  641. indexName,
  642. index,
  643. item
  644. });
  645. const key = getKey ? getKey(context) : index;
  646. const oldItem = childrenMap.get(key);
  647. if (mustFilterItem(condition, context)) {
  648. return;
  649. }
  650. const componentTemplate = oldItem ? oldItem.template : template.clone();
  651. const el = oldItem ? componentTemplate.el : root.cloneNode();
  652. const mustMount = !oldItem;
  653. const meta = isTemplateTag && mustMount ? createTemplateMeta(componentTemplate) : {};
  654. if (mustMount) {
  655. batches.push(() => componentTemplate.mount(el, context, parentScope, meta));
  656. } else {
  657. componentTemplate.update(context, parentScope);
  658. } // create the collection of nodes to update or to add
  659. // in case of template tags we need to add all its children nodes
  660. if (isTemplateTag) {
  661. futureNodes.push(...(meta.children || componentTemplate.children));
  662. } else {
  663. futureNodes.push(el);
  664. } // delete the old item from the children map
  665. childrenMap.delete(key); // update the children map
  666. newChildrenMap.set(key, {
  667. template: componentTemplate,
  668. context,
  669. index
  670. });
  671. });
  672. return {
  673. newChildrenMap,
  674. batches,
  675. futureNodes
  676. };
  677. }
  678. function create(node, _ref3) {
  679. let {
  680. evaluate,
  681. condition,
  682. itemName,
  683. indexName,
  684. getKey,
  685. template
  686. } = _ref3;
  687. const placeholder = document.createTextNode('');
  688. const parent = node.parentNode;
  689. const root = node.cloneNode();
  690. parent.insertBefore(placeholder, node);
  691. parent.removeChild(node);
  692. return Object.assign({}, EachBinding, {
  693. childrenMap: new Map(),
  694. node,
  695. root,
  696. condition,
  697. evaluate,
  698. isTemplateTag: isTemplate(root),
  699. template: template.createDOM(node),
  700. getKey,
  701. indexName,
  702. itemName,
  703. placeholder
  704. });
  705. }
  706. /**
  707. * Binding responsible for the `if` directive
  708. */
  709. const IfBinding = Object.seal({
  710. // dynamic binding properties
  711. node: null,
  712. evaluate: null,
  713. parent: null,
  714. isTemplateTag: false,
  715. placeholder: null,
  716. template: null,
  717. // API methods
  718. mount(scope, parentScope) {
  719. this.parent.insertBefore(this.placeholder, this.node);
  720. this.parent.removeChild(this.node);
  721. return this.update(scope, parentScope);
  722. },
  723. update(scope, parentScope) {
  724. const value = !!this.evaluate(scope);
  725. const mustMount = !this.value && value;
  726. const mustUnmount = this.value && !value;
  727. const mount = () => {
  728. const pristine = this.node.cloneNode();
  729. this.parent.insertBefore(pristine, this.placeholder);
  730. this.template = this.template.clone();
  731. this.template.mount(pristine, scope, parentScope);
  732. };
  733. switch (true) {
  734. case mustMount:
  735. mount();
  736. break;
  737. case mustUnmount:
  738. this.unmount(scope);
  739. break;
  740. default:
  741. if (value) this.template.update(scope, parentScope);
  742. }
  743. this.value = value;
  744. return this;
  745. },
  746. unmount(scope, parentScope) {
  747. this.template.unmount(scope, parentScope, true);
  748. return this;
  749. }
  750. });
  751. function create$1(node, _ref4) {
  752. let {
  753. evaluate,
  754. template
  755. } = _ref4;
  756. return Object.assign({}, IfBinding, {
  757. node,
  758. evaluate,
  759. parent: node.parentNode,
  760. placeholder: document.createTextNode(''),
  761. template: template.createDOM(node)
  762. });
  763. }
  764. const ATTRIBUTE = 0;
  765. const EVENT = 1;
  766. const TEXT = 2;
  767. const VALUE = 3;
  768. var expressionTypes = {
  769. ATTRIBUTE,
  770. EVENT,
  771. TEXT,
  772. VALUE
  773. };
  774. /**
  775. * Check if a value is a Boolean
  776. * @param {*} value - anything
  777. * @returns {boolean} true only for the value is a boolean
  778. */
  779. function isBoolean(value) {
  780. return typeof value === 'boolean';
  781. }
  782. /**
  783. * Check if a value is an Object
  784. * @param {*} value - anything
  785. * @returns {boolean} true only for the value is an object
  786. */
  787. function isObject(value) {
  788. return typeof value === 'object';
  789. }
  790. const REMOVE_ATTRIBUTE = 'removeAttribute';
  791. const SET_ATTIBUTE = 'setAttribute';
  792. /**
  793. * Add all the attributes provided
  794. * @param {HTMLElement} node - target node
  795. * @param {Object} attributes - object containing the attributes names and values
  796. * @returns {undefined} sorry it's a void function :(
  797. */
  798. function setAllAttributes(node, attributes) {
  799. Object.entries(attributes).forEach((_ref5) => {
  800. let [name, value] = _ref5;
  801. return attributeExpression(node, {
  802. name
  803. }, value);
  804. });
  805. }
  806. /**
  807. * Remove all the attributes provided
  808. * @param {HTMLElement} node - target node
  809. * @param {Object} attributes - object containing all the attribute names
  810. * @returns {undefined} sorry it's a void function :(
  811. */
  812. function removeAllAttributes(node, attributes) {
  813. Object.keys(attributes).forEach(attribute => node.removeAttribute(attribute));
  814. }
  815. /**
  816. * This methods handles the DOM attributes updates
  817. * @param {HTMLElement} node - target node
  818. * @param {Object} expression - expression object
  819. * @param {string} expression.name - attribute name
  820. * @param {*} value - new expression value
  821. * @param {*} oldValue - the old expression cached value
  822. * @returns {undefined}
  823. */
  824. function attributeExpression(node, _ref6, value, oldValue) {
  825. let {
  826. name
  827. } = _ref6;
  828. // is it a spread operator? {...attributes}
  829. if (!name) {
  830. // is the value still truthy?
  831. if (value) {
  832. setAllAttributes(node, value);
  833. } else if (oldValue) {
  834. // otherwise remove all the old attributes
  835. removeAllAttributes(node, oldValue);
  836. }
  837. return;
  838. } // handle boolean attributes
  839. if (isBoolean(value) || isObject(value)) {
  840. node[name] = value;
  841. }
  842. node[getMethod(value)](name, normalizeValue(name, value));
  843. }
  844. /**
  845. * Get the attribute modifier method
  846. * @param {*} value - if truthy we return `setAttribute` othewise `removeAttribute`
  847. * @returns {string} the node attribute modifier method name
  848. */
  849. function getMethod(value) {
  850. return isNil(value) || value === false || value === '' || isObject(value) ? REMOVE_ATTRIBUTE : SET_ATTIBUTE;
  851. }
  852. /**
  853. * Get the value as string
  854. * @param {string} name - attribute name
  855. * @param {*} value - user input value
  856. * @returns {string} input value as string
  857. */
  858. function normalizeValue(name, value) {
  859. // be sure that expressions like selected={ true } will be always rendered as selected='selected'
  860. if (value === true) return name;
  861. return value;
  862. }
  863. const RE_EVENTS_PREFIX = /^on/;
  864. /**
  865. * Set a new event listener
  866. * @param {HTMLElement} node - target node
  867. * @param {Object} expression - expression object
  868. * @param {string} expression.name - event name
  869. * @param {*} value - new expression value
  870. * @param {*} oldValue - old expression value
  871. * @returns {value} the callback just received
  872. */
  873. function eventExpression(node, _ref7, value, oldValue) {
  874. let {
  875. name
  876. } = _ref7;
  877. const normalizedEventName = name.replace(RE_EVENTS_PREFIX, '');
  878. if (oldValue) {
  879. node.removeEventListener(normalizedEventName, oldValue);
  880. }
  881. if (value) {
  882. node.addEventListener(normalizedEventName, value, false);
  883. }
  884. return value;
  885. }
  886. /**
  887. * This methods handles a simple text expression update
  888. * @param {HTMLElement} node - target node
  889. * @param {Object} expression - expression object
  890. * @param {number} expression.childNodeIndex - index to find the text node to update
  891. * @param {*} value - new expression value
  892. * @returns {undefined}
  893. */
  894. function textExpression(node, _ref8, value) {
  895. let {
  896. childNodeIndex
  897. } = _ref8;
  898. const target = node.childNodes[childNodeIndex];
  899. const val = normalizeValue$1(value); // replace the target if it's a placeholder comment
  900. if (target.nodeType === Node.COMMENT_NODE) {
  901. const textNode = document.createTextNode(val);
  902. node.replaceChild(textNode, target);
  903. } else {
  904. target.data = normalizeValue$1(val);
  905. }
  906. }
  907. /**
  908. * Normalize the user value in order to render a empty string in case of falsy values
  909. * @param {*} value - user input value
  910. * @returns {string} hopefully a string
  911. */
  912. function normalizeValue$1(value) {
  913. return isNil(value) ? '' : value;
  914. }
  915. /**
  916. * This methods handles the input fileds value updates
  917. * @param {HTMLElement} node - target node
  918. * @param {Object} expression - expression object
  919. * @param {*} value - new expression value
  920. * @returns {undefined}
  921. */
  922. function valueExpression(node, expression, value) {
  923. node.value = value;
  924. }
  925. var expressions = {
  926. [ATTRIBUTE]: attributeExpression,
  927. [EVENT]: eventExpression,
  928. [TEXT]: textExpression,
  929. [VALUE]: valueExpression
  930. };
  931. const Expression = Object.seal({
  932. // Static props
  933. node: null,
  934. value: null,
  935. // API methods
  936. /**
  937. * Mount the expression evaluating its initial value
  938. * @param {*} scope - argument passed to the expression to evaluate its current values
  939. * @returns {Expression} self
  940. */
  941. mount(scope) {
  942. // hopefully a pure function
  943. this.value = this.evaluate(scope); // IO() DOM updates
  944. apply(this, this.value);
  945. return this;
  946. },
  947. /**
  948. * Update the expression if its value changed
  949. * @param {*} scope - argument passed to the expression to evaluate its current values
  950. * @returns {Expression} self
  951. */
  952. update(scope) {
  953. // pure function
  954. const value = this.evaluate(scope);
  955. if (this.value !== value) {
  956. // IO() DOM updates
  957. apply(this, value);
  958. this.value = value;
  959. }
  960. return this;
  961. },
  962. /**
  963. * Expression teardown method
  964. * @returns {Expression} self
  965. */
  966. unmount() {
  967. // unmount only the event handling expressions
  968. if (this.type === EVENT) apply(this, null);
  969. return this;
  970. }
  971. });
  972. /**
  973. * IO() function to handle the DOM updates
  974. * @param {Expression} expression - expression object
  975. * @param {*} value - current expression value
  976. * @returns {undefined}
  977. */
  978. function apply(expression, value) {
  979. return expressions[expression.type](expression.node, expression, value, expression.value);
  980. }
  981. function create$2(node, data) {
  982. return Object.assign({}, Expression, {}, data, {
  983. node
  984. });
  985. }
  986. /**
  987. * Create a flat object having as keys a list of methods that if dispatched will propagate
  988. * on the whole collection
  989. * @param {Array} collection - collection to iterate
  990. * @param {Array<string>} methods - methods to execute on each item of the collection
  991. * @param {*} context - context returned by the new methods created
  992. * @returns {Object} a new object to simplify the the nested methods dispatching
  993. */
  994. function flattenCollectionMethods(collection, methods, context) {
  995. return methods.reduce((acc, method) => {
  996. return Object.assign({}, acc, {
  997. [method]: scope => {
  998. return collection.map(item => item[method](scope)) && context;
  999. }
  1000. });
  1001. }, {});
  1002. }
  1003. function create$3(node, _ref9) {
  1004. let {
  1005. expressions
  1006. } = _ref9;
  1007. return Object.assign({}, flattenCollectionMethods(expressions.map(expression => create$2(node, expression)), ['mount', 'update', 'unmount']));
  1008. }
  1009. const SlotBinding = Object.seal({
  1010. // dynamic binding properties
  1011. node: null,
  1012. name: null,
  1013. template: null,
  1014. // API methods
  1015. mount(scope, parentScope) {
  1016. const templateData = scope.slots ? scope.slots.find((_ref10) => {
  1017. let {
  1018. id
  1019. } = _ref10;
  1020. return id === this.name;
  1021. }) : false;
  1022. const {
  1023. parentNode
  1024. } = this.node;
  1025. this.template = templateData && create$6(templateData.html, templateData.bindings).createDOM(parentNode);
  1026. if (this.template) {
  1027. this.template.mount(this.node, parentScope);
  1028. moveSlotInnerContent(this.node);
  1029. }
  1030. parentNode.removeChild(this.node);
  1031. return this;
  1032. },
  1033. update(scope, parentScope) {
  1034. if (this.template && parentScope) {
  1035. this.template.update(parentScope);
  1036. }
  1037. return this;
  1038. },
  1039. unmount(scope, parentScope, mustRemoveRoot) {
  1040. if (this.template) {
  1041. this.template.unmount(parentScope, null, mustRemoveRoot);
  1042. }
  1043. return this;
  1044. }
  1045. });
  1046. /**
  1047. * Move the inner content of the slots outside of them
  1048. * @param {HTMLNode} slot - slot node
  1049. * @returns {undefined} it's a void function
  1050. */
  1051. function moveSlotInnerContent(slot) {
  1052. if (slot.firstChild) {
  1053. slot.parentNode.insertBefore(slot.firstChild, slot);
  1054. moveSlotInnerContent(slot);
  1055. }
  1056. }
  1057. /**
  1058. * Create a single slot binding
  1059. * @param {HTMLElement} node - slot node
  1060. * @param {string} options.name - slot id
  1061. * @returns {Object} Slot binding object
  1062. */
  1063. function createSlot(node, _ref11) {
  1064. let {
  1065. name
  1066. } = _ref11;
  1067. return Object.assign({}, SlotBinding, {
  1068. node,
  1069. name
  1070. });
  1071. }
  1072. /**
  1073. * Create a new tag object if it was registered before, otherwise fallback to the simple
  1074. * template chunk
  1075. * @param {Function} component - component factory function
  1076. * @param {Array<Object>} slots - array containing the slots markup
  1077. * @param {Array} attributes - dynamic attributes that will be received by the tag element
  1078. * @returns {TagImplementation|TemplateChunk} a tag implementation or a template chunk as fallback
  1079. */
  1080. function getTag(component, slots, attributes) {
  1081. if (slots === void 0) {
  1082. slots = [];
  1083. }
  1084. if (attributes === void 0) {
  1085. attributes = [];
  1086. }
  1087. // if this tag was registered before we will return its implementation
  1088. if (component) {
  1089. return component({
  1090. slots,
  1091. attributes
  1092. });
  1093. } // otherwise we return a template chunk
  1094. return create$6(slotsToMarkup(slots), [...slotBindings(slots), {
  1095. // the attributes should be registered as binding
  1096. // if we fallback to a normal template chunk
  1097. expressions: attributes.map(attr => {
  1098. return Object.assign({
  1099. type: ATTRIBUTE
  1100. }, attr);
  1101. })
  1102. }]);
  1103. }
  1104. /**
  1105. * Merge all the slots bindings into a single array
  1106. * @param {Array<Object>} slots - slots collection
  1107. * @returns {Array<Bindings>} flatten bindings array
  1108. */
  1109. function slotBindings(slots) {
  1110. return slots.reduce((acc, _ref12) => {
  1111. let {
  1112. bindings
  1113. } = _ref12;
  1114. return acc.concat(bindings);
  1115. }, []);
  1116. }
  1117. /**
  1118. * Merge all the slots together in a single markup string
  1119. * @param {Array<Object>} slots - slots collection
  1120. * @returns {string} markup of all the slots in a single string
  1121. */
  1122. function slotsToMarkup(slots) {
  1123. return slots.reduce((acc, slot) => {
  1124. return acc + slot.html;
  1125. }, '');
  1126. }
  1127. const TagBinding = Object.seal({
  1128. // dynamic binding properties
  1129. node: null,
  1130. evaluate: null,
  1131. name: null,
  1132. slots: null,
  1133. tag: null,
  1134. attributes: null,
  1135. getComponent: null,
  1136. mount(scope) {
  1137. return this.update(scope);
  1138. },
  1139. update(scope, parentScope) {
  1140. const name = this.evaluate(scope); // simple update
  1141. if (name === this.name) {
  1142. this.tag.update(scope);
  1143. } else {
  1144. // unmount the old tag if it exists
  1145. this.unmount(scope, parentScope, true); // mount the new tag
  1146. this.name = name;
  1147. this.tag = getTag(this.getComponent(name), this.slots, this.attributes);
  1148. this.tag.mount(this.node, scope);
  1149. }
  1150. return this;
  1151. },
  1152. unmount(scope, parentScope, keepRootTag) {
  1153. if (this.tag) {
  1154. // keep the root tag
  1155. this.tag.unmount(keepRootTag);
  1156. }
  1157. return this;
  1158. }
  1159. });
  1160. function create$4(node, _ref13) {
  1161. let {
  1162. evaluate,
  1163. getComponent,
  1164. slots,
  1165. attributes
  1166. } = _ref13;
  1167. return Object.assign({}, TagBinding, {
  1168. node,
  1169. evaluate,
  1170. slots,
  1171. attributes,
  1172. getComponent
  1173. });
  1174. }
  1175. var bindings = {
  1176. [IF]: create$1,
  1177. [SIMPLE]: create$3,
  1178. [EACH]: create,
  1179. [TAG]: create$4,
  1180. [SLOT]: createSlot
  1181. };
  1182. /**
  1183. * Bind a new expression object to a DOM node
  1184. * @param {HTMLElement} root - DOM node where to bind the expression
  1185. * @param {Object} binding - binding data
  1186. * @returns {Expression} Expression object
  1187. */
  1188. function create$5(root, binding) {
  1189. const {
  1190. selector,
  1191. type,
  1192. redundantAttribute,
  1193. expressions
  1194. } = binding; // find the node to apply the bindings
  1195. const node = selector ? root.querySelector(selector) : root; // remove eventually additional attributes created only to select this node
  1196. if (redundantAttribute) node.removeAttribute(redundantAttribute); // init the binding
  1197. return (bindings[type] || bindings[SIMPLE])(node, Object.assign({}, binding, {
  1198. expressions: expressions || []
  1199. }));
  1200. }
  1201. /**
  1202. * Check if an element is part of an svg
  1203. * @param {HTMLElement} el - element to check
  1204. * @returns {boolean} true if we are in an svg context
  1205. */
  1206. function isSvg(el) {
  1207. const owner = el.ownerSVGElement;
  1208. return !!owner || owner === null;
  1209. } // in this case a simple innerHTML is enough
  1210. function createHTMLTree(html, root) {
  1211. const template = isTemplate(root) ? root : document.createElement('template');
  1212. template.innerHTML = html;
  1213. return template.content;
  1214. } // for svg nodes we need a bit more work
  1215. function createSVGTree(html, container) {
  1216. // create the SVGNode
  1217. const svgNode = container.ownerDocument.importNode(new window.DOMParser().parseFromString(`<svg xmlns="http://www.w3.org/2000/svg">${html}</svg>`, 'application/xml').documentElement, true);
  1218. return svgNode;
  1219. }
  1220. /**
  1221. * Create the DOM that will be injected
  1222. * @param {Object} root - DOM node to find out the context where the fragment will be created
  1223. * @param {string} html - DOM to create as string
  1224. * @returns {HTMLDocumentFragment|HTMLElement} a new html fragment
  1225. */
  1226. function createDOMTree(root, html) {
  1227. if (isSvg(root)) return createSVGTree(html, root);
  1228. return createHTMLTree(html, root);
  1229. }
  1230. /**
  1231. * Move all the child nodes from a source tag to another
  1232. * @param {HTMLElement} source - source node
  1233. * @param {HTMLElement} target - target node
  1234. * @returns {undefined} it's a void method ¯\_()_/¯
  1235. */
  1236. // Ignore this helper because it's needed only for svg tags
  1237. /* istanbul ignore next */
  1238. function moveChildren(source, target) {
  1239. if (source.firstChild) {
  1240. target.appendChild(source.firstChild);
  1241. moveChildren(source, target);
  1242. }
  1243. }
  1244. /**
  1245. * Inject the DOM tree into a target node
  1246. * @param {HTMLElement} el - target element
  1247. * @param {HTMLFragment|SVGElement} dom - dom tree to inject
  1248. * @returns {undefined}
  1249. */
  1250. function injectDOM(el, dom) {
  1251. switch (true) {
  1252. case isSvg(el):
  1253. moveChildren(dom, el);
  1254. break;
  1255. case isTemplate(el):
  1256. el.parentNode.replaceChild(dom, el);
  1257. break;
  1258. default:
  1259. el.appendChild(dom);
  1260. }
  1261. }
  1262. /**
  1263. * Create the Template DOM skeleton
  1264. * @param {HTMLElement} el - root node where the DOM will be injected
  1265. * @param {string} html - markup that will be injected into the root node
  1266. * @returns {HTMLFragment} fragment that will be injected into the root node
  1267. */
  1268. function createTemplateDOM(el, html) {
  1269. return html && (typeof html === 'string' ? createDOMTree(el, html) : html);
  1270. }
  1271. /**
  1272. * Template Chunk model
  1273. * @type {Object}
  1274. */
  1275. const TemplateChunk = Object.freeze({
  1276. // Static props
  1277. bindings: null,
  1278. bindingsData: null,
  1279. html: null,
  1280. isTemplateTag: false,
  1281. fragment: null,
  1282. children: null,
  1283. dom: null,
  1284. el: null,
  1285. /**
  1286. * Create the template DOM structure that will be cloned on each mount
  1287. * @param {HTMLElement} el - the root node
  1288. * @returns {TemplateChunk} self
  1289. */
  1290. createDOM(el) {
  1291. // make sure that the DOM gets created before cloning the template
  1292. this.dom = this.dom || createTemplateDOM(el, this.html);
  1293. return this;
  1294. },
  1295. // API methods
  1296. /**
  1297. * Attach the template to a DOM node
  1298. * @param {HTMLElement} el - target DOM node
  1299. * @param {*} scope - template data
  1300. * @param {*} parentScope - scope of the parent template tag
  1301. * @param {Object} meta - meta properties needed to handle the <template> tags in loops
  1302. * @returns {TemplateChunk} self
  1303. */
  1304. mount(el, scope, parentScope, meta) {
  1305. if (meta === void 0) {
  1306. meta = {};
  1307. }
  1308. if (!el) throw new Error('Please provide DOM node to mount properly your template');
  1309. if (this.el) this.unmount(scope); // <template> tags require a bit more work
  1310. // the template fragment might be already created via meta outside of this call
  1311. const {
  1312. fragment,
  1313. children,
  1314. avoidDOMInjection
  1315. } = meta; // <template> bindings of course can not have a root element
  1316. // so we check the parent node to set the query selector bindings
  1317. const {
  1318. parentNode
  1319. } = children ? children[0] : el;
  1320. this.isTemplateTag = isTemplate(el); // create the DOM if it wasn't created before
  1321. this.createDOM(el);
  1322. if (this.dom) {
  1323. // create the new template dom fragment if it want already passed in via meta
  1324. this.fragment = fragment || this.dom.cloneNode(true);
  1325. } // store root node
  1326. // notice that for template tags the root note will be the parent tag
  1327. this.el = this.isTemplateTag ? parentNode : el; // create the children array only for the <template> fragments
  1328. this.children = this.isTemplateTag ? children || Array.from(this.fragment.childNodes) : null; // inject the DOM into the el only if a fragment is available
  1329. if (!avoidDOMInjection && this.fragment) injectDOM(el, this.fragment); // create the bindings
  1330. this.bindings = this.bindingsData.map(binding => create$5(this.el, binding));
  1331. this.bindings.forEach(b => b.mount(scope, parentScope));
  1332. return this;
  1333. },
  1334. /**
  1335. * Update the template with fresh data
  1336. * @param {*} scope - template data
  1337. * @param {*} parentScope - scope of the parent template tag
  1338. * @returns {TemplateChunk} self
  1339. */
  1340. update(scope, parentScope) {
  1341. this.bindings.forEach(b => b.update(scope, parentScope));
  1342. return this;
  1343. },
  1344. /**
  1345. * Remove the template from the node where it was initially mounted
  1346. * @param {*} scope - template data
  1347. * @param {*} parentScope - scope of the parent template tag
  1348. * @param {boolean|null} mustRemoveRoot - if true remove the root element,
  1349. * if false or undefined clean the root tag content, if null don't touch the DOM
  1350. * @returns {TemplateChunk} self
  1351. */
  1352. unmount(scope, parentScope, mustRemoveRoot) {
  1353. if (this.el) {
  1354. this.bindings.forEach(b => b.unmount(scope, parentScope, mustRemoveRoot));
  1355. switch (true) {
  1356. // <template> tags should be treated a bit differently
  1357. // we need to clear their children only if it's explicitly required by the caller
  1358. // via mustRemoveRoot !== null
  1359. case this.isTemplateTag === true && mustRemoveRoot !== null:
  1360. clearChildren(this.children);
  1361. break;
  1362. // remove the root node only if the mustRemoveRoot === true
  1363. case mustRemoveRoot === true && this.el.parentNode !== null:
  1364. this.el.parentNode.removeChild(this.el);
  1365. break;
  1366. // otherwise we clean the node children
  1367. case mustRemoveRoot !== null:
  1368. cleanNode(this.el);
  1369. break;
  1370. }
  1371. this.el = null;
  1372. }
  1373. return this;
  1374. },
  1375. /**
  1376. * Clone the template chunk
  1377. * @returns {TemplateChunk} a clone of this object resetting the this.el property
  1378. */
  1379. clone() {
  1380. return Object.assign({}, this, {
  1381. el: null
  1382. });
  1383. }
  1384. });
  1385. /**
  1386. * Create a template chunk wiring also the bindings
  1387. * @param {string|HTMLElement} html - template string
  1388. * @param {Array} bindings - bindings collection
  1389. * @returns {TemplateChunk} a new TemplateChunk copy
  1390. */
  1391. function create$6(html, bindings) {
  1392. if (bindings === void 0) {
  1393. bindings = [];
  1394. }
  1395. return Object.assign({}, TemplateChunk, {
  1396. html,
  1397. bindingsData: bindings
  1398. });
  1399. }
  1400. /**
  1401. * Quick type checking
  1402. * @param {*} element - anything
  1403. * @param {string} type - type definition
  1404. * @returns {boolean} true if the type corresponds
  1405. */
  1406. function checkType(element, type) {
  1407. return typeof element === type;
  1408. }
  1409. /**
  1410. * Check that will be passed if its argument is a function
  1411. * @param {*} value - value to check
  1412. * @returns {boolean} - true if the value is a function
  1413. */
  1414. function isFunction(value) {
  1415. return checkType(value, 'function');
  1416. }
  1417. /* eslint-disable fp/no-mutating-methods */
  1418. /**
  1419. * Throw an error
  1420. * @param {string} error - error message
  1421. * @returns {undefined} it's a IO void function
  1422. */
  1423. function panic(error) {
  1424. throw new Error(error);
  1425. }
  1426. /**
  1427. * Call the first argument received only if it's a function otherwise return it as it is
  1428. * @param {*} source - anything
  1429. * @returns {*} anything
  1430. */
  1431. function callOrAssign(source) {
  1432. return isFunction(source) ? source.prototype && source.prototype.constructor ? new source() : source() : source;
  1433. }
  1434. /**
  1435. * Convert a string from camel case to dash-case
  1436. * @param {string} string - probably a component tag name
  1437. * @returns {string} component name normalized
  1438. */
  1439. function camelToDashCase(string) {
  1440. return string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  1441. }
  1442. /**
  1443. * Convert a string containing dashes to camel case
  1444. * @param {string} string - input string
  1445. * @returns {string} my-string -> myString
  1446. */
  1447. function dashToCamelCase(string) {
  1448. return string.replace(/-(\w)/g, (_, c) => c.toUpperCase());
  1449. }
  1450. /**
  1451. * Define default properties if they don't exist on the source object
  1452. * @param {Object} source - object that will receive the default properties
  1453. * @param {Object} defaults - object containing additional optional keys
  1454. * @returns {Object} the original object received enhanced
  1455. */
  1456. function defineDefaults(source, defaults) {
  1457. Object.entries(defaults).forEach((_ref) => {
  1458. let [key, value] = _ref;
  1459. if (!source[key]) source[key] = value;
  1460. });
  1461. return source;
  1462. } // doese simply nothing
  1463. function noop() {
  1464. return this;
  1465. }
  1466. /**
  1467. * Autobind the methods of a source object to itself
  1468. * @param {Object} source - probably a riot tag instance
  1469. * @param {Array<string>} methods - list of the methods to autobind
  1470. * @returns {Object} the original object received
  1471. */
  1472. function autobindMethods(source, methods) {
  1473. methods.forEach(method => {
  1474. source[method] = source[method].bind(source);
  1475. });
  1476. return source;
  1477. }
  1478. /**
  1479. * Helper function to set an immutable property
  1480. * @param {Object} source - object where the new property will be set
  1481. * @param {string} key - object key where the new property will be stored
  1482. * @param {*} value - value of the new property
  1483. * @param {Object} options - set the propery overriding the default options
  1484. * @returns {Object} - the original object modified
  1485. */
  1486. function defineProperty(source, key, value, options) {
  1487. if (options === void 0) {
  1488. options = {};
  1489. }
  1490. Object.defineProperty(source, key, Object.assign({
  1491. value,
  1492. enumerable: false,
  1493. writable: false,
  1494. configurable: true
  1495. }, options));
  1496. return source;
  1497. }
  1498. /**
  1499. * Define multiple properties on a target object
  1500. * @param {Object} source - object where the new properties will be set
  1501. * @param {Object} properties - object containing as key pair the key + value properties
  1502. * @param {Object} options - set the propery overriding the default options
  1503. * @returns {Object} the original object modified
  1504. */
  1505. function defineProperties(source, properties, options) {
  1506. Object.entries(properties).forEach((_ref2) => {
  1507. let [key, value] = _ref2;
  1508. defineProperty(source, key, value, options);
  1509. });
  1510. return source;
  1511. }
  1512. /**
  1513. * Evaluate a list of attribute expressions
  1514. * @param {Array} attributes - attribute expressions generated by the riot compiler
  1515. * @returns {Object} key value pairs with the result of the computation
  1516. */
  1517. function evaluateAttributeExpressions(attributes) {
  1518. return attributes.reduce((acc, attribute) => {
  1519. const {
  1520. value,
  1521. type
  1522. } = attribute;
  1523. switch (true) {
  1524. // spread attribute
  1525. case !attribute.name && type === expressionTypes.ATTRIBUTE:
  1526. return Object.assign({}, acc, {}, value);
  1527. // value attribute
  1528. case type === expressionTypes.VALUE:
  1529. acc[VALUE_ATTRIBUTE] = attribute.value;
  1530. break;
  1531. // normal attributes
  1532. default:
  1533. acc[dashToCamelCase(attribute.name)] = attribute.value;
  1534. }
  1535. return acc;
  1536. }, {});
  1537. }
  1538. /**
  1539. * Converts any DOM node/s to a loopable array
  1540. * @param { HTMLElement|NodeList } els - single html element or a node list
  1541. * @returns { Array } always a loopable object
  1542. */
  1543. function domToArray(els) {
  1544. // can this object be already looped?
  1545. if (!Array.isArray(els)) {
  1546. // is it a node list?
  1547. 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
  1548. // it will be returned as "array" with one single entry
  1549. return [els];
  1550. } // this object could be looped out of the box
  1551. return els;
  1552. }
  1553. /**
  1554. * Normalize the return values, in case of a single value we avoid to return an array
  1555. * @param { Array } values - list of values we want to return
  1556. * @returns { Array|string|boolean } either the whole list of values or the single one found
  1557. * @private
  1558. */
  1559. const normalize = values => values.length === 1 ? values[0] : values;
  1560. /**
  1561. * Parse all the nodes received to get/remove/check their attributes
  1562. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  1563. * @param { string|Array } name - name or list of attributes
  1564. * @param { string } method - method that will be used to parse the attributes
  1565. * @returns { Array|string } result of the parsing in a list or a single value
  1566. * @private
  1567. */
  1568. function parseNodes(els, name, method) {
  1569. const names = typeof name === 'string' ? [name] : name;
  1570. return normalize(domToArray(els).map(el => {
  1571. return normalize(names.map(n => el[method](n)));
  1572. }));
  1573. }
  1574. /**
  1575. * Set any attribute on a single or a list of DOM nodes
  1576. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  1577. * @param { string|Object } name - either the name of the attribute to set
  1578. * or a list of properties as object key - value
  1579. * @param { string } value - the new value of the attribute (optional)
  1580. * @returns { HTMLElement|NodeList|Array } the original array of elements passed to this function
  1581. *
  1582. * @example
  1583. *
  1584. * import { set } from 'bianco.attr'
  1585. *
  1586. * const img = document.createElement('img')
  1587. *
  1588. * set(img, 'width', 100)
  1589. *
  1590. * // or also
  1591. * set(img, {
  1592. * width: 300,
  1593. * height: 300
  1594. * })
  1595. *
  1596. */
  1597. function set(els, name, value) {
  1598. const attrs = typeof name === 'object' ? name : {
  1599. [name]: value
  1600. };
  1601. const props = Object.keys(attrs);
  1602. domToArray(els).forEach(el => {
  1603. props.forEach(prop => el.setAttribute(prop, attrs[prop]));
  1604. });
  1605. return els;
  1606. }
  1607. /**
  1608. * Get any attribute from a single or a list of DOM nodes
  1609. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  1610. * @param { string|Array } name - name or list of attributes to get
  1611. * @returns { Array|string } list of the attributes found
  1612. *
  1613. * @example
  1614. *
  1615. * import { get } from 'bianco.attr'
  1616. *
  1617. * const img = document.createElement('img')
  1618. *
  1619. * get(img, 'width') // => '200'
  1620. *
  1621. * // or also
  1622. * get(img, ['width', 'height']) // => ['200', '300']
  1623. *
  1624. * // or also
  1625. * get([img1, img2], ['width', 'height']) // => [['200', '300'], ['500', '200']]
  1626. */
  1627. function get(els, name) {
  1628. return parseNodes(els, name, 'getAttribute');
  1629. }
  1630. /**
  1631. * Get all the element attributes as object
  1632. * @param {HTMLElement} element - DOM node we want to parse
  1633. * @returns {Object} all the attributes found as a key value pairs
  1634. */
  1635. function DOMattributesToObject(element) {
  1636. return Array.from(element.attributes).reduce((acc, attribute) => {
  1637. acc[dashToCamelCase(attribute.name)] = attribute.value;
  1638. return acc;
  1639. }, {});
  1640. }
  1641. /**
  1642. * Get the tag name of any DOM node
  1643. * @param {HTMLElement} element - DOM node we want to inspect
  1644. * @returns {string} name to identify this dom node in riot
  1645. */
  1646. function getName(element) {
  1647. return get(element, IS_DIRECTIVE) || element.tagName.toLowerCase();
  1648. }
  1649. /**
  1650. * Simple helper to find DOM nodes returning them as array like loopable object
  1651. * @param { string|DOMNodeList } selector - either the query or the DOM nodes to arraify
  1652. * @param { HTMLElement } ctx - context defining where the query will search for the DOM nodes
  1653. * @returns { Array } DOM nodes found as array
  1654. */
  1655. function $(selector, ctx) {
  1656. return domToArray(typeof selector === 'string' ? (ctx || document).querySelectorAll(selector) : selector);
  1657. }
  1658. const CSS_BY_NAME = new Map();
  1659. const STYLE_NODE_SELECTOR = 'style[riot]'; // memoized curried function
  1660. const getStyleNode = (style => {
  1661. return () => {
  1662. // lazy evaluation:
  1663. // if this function was already called before
  1664. // we return its cached result
  1665. if (style) return style; // create a new style element or use an existing one
  1666. // and cache it internally
  1667. style = $(STYLE_NODE_SELECTOR)[0] || document.createElement('style');
  1668. set(style, 'type', 'text/css');
  1669. /* istanbul ignore next */
  1670. if (!style.parentNode) document.head.appendChild(style);
  1671. return style;
  1672. };
  1673. })();
  1674. /**
  1675. * Object that will be used to inject and manage the css of every tag instance
  1676. */
  1677. var cssManager = {
  1678. CSS_BY_NAME,
  1679. /**
  1680. * Save a tag style to be later injected into DOM
  1681. * @param { string } name - if it's passed we will map the css to a tagname
  1682. * @param { string } css - css string
  1683. * @returns {Object} self
  1684. */
  1685. add(name, css) {
  1686. if (!CSS_BY_NAME.has(name)) {
  1687. CSS_BY_NAME.set(name, css);
  1688. this.inject();
  1689. }
  1690. return this;
  1691. },
  1692. /**
  1693. * Inject all previously saved tag styles into DOM
  1694. * innerHTML seems slow: http://jsperf.com/riot-insert-style
  1695. * @returns {Object} self
  1696. */
  1697. inject() {
  1698. getStyleNode().innerHTML = [...CSS_BY_NAME.values()].join('\n');
  1699. return this;
  1700. },
  1701. /**
  1702. * Remove a tag style from the DOM
  1703. * @param {string} name a registered tagname
  1704. * @returns {Object} self
  1705. */
  1706. remove(name) {
  1707. if (CSS_BY_NAME.has(name)) {
  1708. CSS_BY_NAME.delete(name);
  1709. this.inject();
  1710. }
  1711. return this;
  1712. }
  1713. };
  1714. /**
  1715. * Function to curry any javascript method
  1716. * @param {Function} fn - the target function we want to curry
  1717. * @param {...[args]} acc - initial arguments
  1718. * @returns {Function|*} it will return a function until the target function
  1719. * will receive all of its arguments
  1720. */
  1721. function curry(fn) {
  1722. for (var _len = arguments.length, acc = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  1723. acc[_key - 1] = arguments[_key];
  1724. }
  1725. return function () {
  1726. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  1727. args[_key2] = arguments[_key2];
  1728. }
  1729. args = [...acc, ...args];
  1730. return args.length < fn.length ? curry(fn, ...args) : fn(...args);
  1731. };
  1732. }
  1733. const COMPONENT_CORE_HELPERS = Object.freeze({
  1734. // component helpers
  1735. $(selector) {
  1736. return $(selector, this.root)[0];
  1737. },
  1738. $$(selector) {
  1739. return $(selector, this.root);
  1740. }
  1741. });
  1742. const COMPONENT_LIFECYCLE_METHODS = Object.freeze({
  1743. shouldUpdate: noop,
  1744. onBeforeMount: noop,
  1745. onMounted: noop,
  1746. onBeforeUpdate: noop,
  1747. onUpdated: noop,
  1748. onBeforeUnmount: noop,
  1749. onUnmounted: noop
  1750. });
  1751. const MOCKED_TEMPLATE_INTERFACE = {
  1752. update: noop,
  1753. mount: noop,
  1754. unmount: noop,
  1755. clone: noop,
  1756. createDOM: noop
  1757. /**
  1758. * Factory function to create the component templates only once
  1759. * @param {Function} template - component template creation function
  1760. * @param {Object} components - object containing the nested components
  1761. * @returns {TemplateChunk} template chunk object
  1762. */
  1763. };
  1764. function componentTemplateFactory(template, components) {
  1765. return template(create$6, expressionTypes, bindingTypes, name => {
  1766. return components[name] || COMPONENTS_IMPLEMENTATION_MAP.get(name);
  1767. });
  1768. }
  1769. /**
  1770. * Create the component interface needed for the @riotjs/dom-bindings tag bindings
  1771. * @param {string} options.css - component css
  1772. * @param {Function} options.template - functon that will return the dom-bindings template function
  1773. * @param {Object} options.exports - component interface
  1774. * @param {string} options.name - component name
  1775. * @returns {Object} component like interface
  1776. */
  1777. function createComponent(_ref) {
  1778. let {
  1779. css,
  1780. template,
  1781. exports,
  1782. name
  1783. } = _ref;
  1784. const templateFn = template ? componentTemplateFactory(template, exports ? createSubcomponents(exports.components) : {}) : MOCKED_TEMPLATE_INTERFACE;
  1785. return (_ref2) => {
  1786. let {
  1787. slots,
  1788. attributes,
  1789. props
  1790. } = _ref2;
  1791. const componentAPI = callOrAssign(exports) || {};
  1792. const component = defineComponent({
  1793. css,
  1794. template: templateFn,
  1795. componentAPI,
  1796. name
  1797. })({
  1798. slots,
  1799. attributes,
  1800. props
  1801. }); // notice that for the components create via tag binding
  1802. // we need to invert the mount (state/parentScope) arguments
  1803. // the template bindings will only forward the parentScope updates
  1804. // and never deal with the component state
  1805. return {
  1806. mount(element, parentScope, state) {
  1807. return component.mount(element, state, parentScope);
  1808. },
  1809. update(parentScope, state) {
  1810. return component.update(state, parentScope);
  1811. },
  1812. unmount(preserveRoot) {
  1813. return component.unmount(preserveRoot);
  1814. }
  1815. };
  1816. };
  1817. }
  1818. /**
  1819. * Component definition function
  1820. * @param {Object} implementation - the componen implementation will be generated via compiler
  1821. * @param {Object} component - the component initial properties
  1822. * @returns {Object} a new component implementation object
  1823. */
  1824. function defineComponent(_ref3) {
  1825. let {
  1826. css,
  1827. template,
  1828. componentAPI,
  1829. name
  1830. } = _ref3;
  1831. // add the component css into the DOM
  1832. if (css && name) cssManager.add(name, css);
  1833. return curry(enhanceComponentAPI)(defineProperties( // set the component defaults without overriding the original component API
  1834. defineDefaults(componentAPI, Object.assign({}, COMPONENT_LIFECYCLE_METHODS, {
  1835. state: {}
  1836. })), Object.assign({
  1837. // defined during the component creation
  1838. slots: null,
  1839. root: null
  1840. }, COMPONENT_CORE_HELPERS, {
  1841. name,
  1842. css,
  1843. template
  1844. })));
  1845. }
  1846. /**
  1847. * Evaluate the component properties either from its real attributes or from its attribute expressions
  1848. * @param {HTMLElement} element - component root
  1849. * @param {Array} attributeExpressions - attribute values generated via createAttributeBindings
  1850. * @returns {Object} attributes key value pairs
  1851. */
  1852. function evaluateProps(element, attributeExpressions) {
  1853. if (attributeExpressions === void 0) {
  1854. attributeExpressions = [];
  1855. }
  1856. return Object.assign({}, DOMattributesToObject(element), {}, evaluateAttributeExpressions(attributeExpressions));
  1857. }
  1858. /**
  1859. * Create the bindings to update the component attributes
  1860. * @param {HTMLElement} node - node where we will bind the expressions
  1861. * @param {Array} attributes - list of attribute bindings
  1862. * @returns {TemplateChunk} - template bindings object
  1863. */
  1864. function createAttributeBindings(node, attributes) {
  1865. if (attributes === void 0) {
  1866. attributes = [];
  1867. }
  1868. const expressions = attributes.map(a => create$2(node, a));
  1869. const binding = {};
  1870. const updateValues = method => scope => {
  1871. expressions.forEach(e => e[method](scope));
  1872. return binding;
  1873. };
  1874. return Object.assign(binding, {
  1875. expressions,
  1876. mount: updateValues('mount'),
  1877. update: updateValues('update'),
  1878. unmount: updateValues('unmount')
  1879. });
  1880. }
  1881. /**
  1882. * Create the subcomponents that can be included inside a tag in runtime
  1883. * @param {Object} components - components imported in runtime
  1884. * @returns {Object} all the components transformed into Riot.Component factory functions
  1885. */
  1886. function createSubcomponents(components) {
  1887. if (components === void 0) {
  1888. components = {};
  1889. }
  1890. return Object.entries(callOrAssign(components)).reduce((acc, _ref4) => {
  1891. let [key, value] = _ref4;
  1892. acc[camelToDashCase(key)] = createComponent(value);
  1893. return acc;
  1894. }, {});
  1895. }
  1896. /**
  1897. * Run the component instance through all the plugins set by the user
  1898. * @param {Object} component - component instance
  1899. * @returns {Object} the component enhanced by the plugins
  1900. */
  1901. function runPlugins(component) {
  1902. return [...PLUGINS_SET].reduce((c, fn) => fn(c) || c, component);
  1903. }
  1904. /**
  1905. * Compute the component current state merging it with its previous state
  1906. * @param {Object} oldState - previous state object
  1907. * @param {Object} newState - new state givent to the `update` call
  1908. * @returns {Object} new object state
  1909. */
  1910. function computeState(oldState, newState) {
  1911. return Object.assign({}, oldState, {}, callOrAssign(newState));
  1912. }
  1913. /**
  1914. * Add eventually the "is" attribute to link this DOM node to its css
  1915. * @param {HTMLElement} element - target root node
  1916. * @param {string} name - name of the component mounted
  1917. * @returns {undefined} it's a void function
  1918. */
  1919. function addCssHook(element, name) {
  1920. if (getName(element) !== name) {
  1921. set(element, 'is', name);
  1922. }
  1923. }
  1924. /**
  1925. * Component creation factory function that will enhance the user provided API
  1926. * @param {Object} component - a component implementation previously defined
  1927. * @param {Array} options.slots - component slots generated via riot compiler
  1928. * @param {Array} options.attributes - attribute expressions generated via riot compiler
  1929. * @returns {Riot.Component} a riot component instance
  1930. */
  1931. function enhanceComponentAPI(component, _ref5) {
  1932. let {
  1933. slots,
  1934. attributes,
  1935. props
  1936. } = _ref5;
  1937. const initialProps = callOrAssign(props);
  1938. return autobindMethods(runPlugins(defineProperties(Object.create(component), {
  1939. mount(element, state, parentScope) {
  1940. if (state === void 0) {
  1941. state = {};
  1942. }
  1943. this[ATTRIBUTES_KEY_SYMBOL] = createAttributeBindings(element, attributes).mount(parentScope);
  1944. this.props = Object.freeze(Object.assign({}, initialProps, {}, evaluateProps(element, this[ATTRIBUTES_KEY_SYMBOL].expressions)));
  1945. this.state = computeState(this.state, state);
  1946. this[TEMPLATE_KEY_SYMBOL] = this.template.createDOM(element).clone(); // link this object to the DOM node
  1947. element[DOM_COMPONENT_INSTANCE_PROPERTY] = this; // add eventually the 'is' attribute
  1948. component.name && addCssHook(element, component.name); // define the root element
  1949. defineProperty(this, 'root', element); // define the slots array
  1950. defineProperty(this, 'slots', slots); // before mount lifecycle event
  1951. this.onBeforeMount(this.props, this.state); // mount the template
  1952. this[TEMPLATE_KEY_SYMBOL].mount(element, this, parentScope);
  1953. this.onMounted(this.props, this.state);
  1954. return this;
  1955. },
  1956. update(state, parentScope) {
  1957. if (state === void 0) {
  1958. state = {};
  1959. }
  1960. if (parentScope) {
  1961. this[ATTRIBUTES_KEY_SYMBOL].update(parentScope);
  1962. }
  1963. const newProps = evaluateProps(this.root, this[ATTRIBUTES_KEY_SYMBOL].expressions);
  1964. if (this.shouldUpdate(newProps, this.props) === false) return;
  1965. this.props = Object.freeze(Object.assign({}, initialProps, {}, newProps));
  1966. this.state = computeState(this.state, state);
  1967. this.onBeforeUpdate(this.props, this.state);
  1968. this[TEMPLATE_KEY_SYMBOL].update(this, parentScope);
  1969. this.onUpdated(this.props, this.state);
  1970. return this;
  1971. },
  1972. unmount(preserveRoot) {
  1973. this.onBeforeUnmount(this.props, this.state);
  1974. this[ATTRIBUTES_KEY_SYMBOL].unmount(); // if the preserveRoot is null the template html will be left untouched
  1975. // in that case the DOM cleanup will happen differently from a parent node
  1976. this[TEMPLATE_KEY_SYMBOL].unmount(this, {}, preserveRoot === null ? null : !preserveRoot);
  1977. this.onUnmounted(this.props, this.state);
  1978. return this;
  1979. }
  1980. })), Object.keys(component).filter(prop => isFunction(component[prop])));
  1981. }
  1982. /**
  1983. * Component initialization function starting from a DOM node
  1984. * @param {HTMLElement} element - element to upgrade
  1985. * @param {Object} initialProps - initial component properties
  1986. * @param {string} componentName - component id
  1987. * @returns {Object} a new component instance bound to a DOM node
  1988. */
  1989. function mountComponent(element, initialProps, componentName) {
  1990. const name = componentName || getName(element);
  1991. if (!COMPONENTS_IMPLEMENTATION_MAP.has(name)) panic(`The component named "${name}" was never registered`);
  1992. const component = COMPONENTS_IMPLEMENTATION_MAP.get(name)({
  1993. props: initialProps
  1994. });
  1995. return component.mount(element);
  1996. }
  1997. /**
  1998. * Similar to compose but performs from left-to-right function composition.<br/>
  1999. * {@link https://30secondsofcode.org/function#composeright see also}
  2000. * @param {...[function]} fns) - list of unary function
  2001. * @returns {*} result of the computation
  2002. */
  2003. /**
  2004. * Performs right-to-left function composition.<br/>
  2005. * Use Array.prototype.reduce() to perform right-to-left function composition.<br/>
  2006. * The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.<br/>
  2007. * {@link https://30secondsofcode.org/function#compose original source code}
  2008. * @param {...[function]} fns) - list of unary function
  2009. * @returns {*} result of the computation
  2010. */
  2011. function compose() {
  2012. for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  2013. fns[_key2] = arguments[_key2];
  2014. }
  2015. return fns.reduce((f, g) => function () {
  2016. return f(g(...arguments));
  2017. });
  2018. }
  2019. const {
  2020. DOM_COMPONENT_INSTANCE_PROPERTY: DOM_COMPONENT_INSTANCE_PROPERTY$1,
  2021. COMPONENTS_IMPLEMENTATION_MAP: COMPONENTS_IMPLEMENTATION_MAP$1,
  2022. PLUGINS_SET: PLUGINS_SET$1
  2023. } = globals;
  2024. /**
  2025. * Riot public api
  2026. */
  2027. /**
  2028. * Register a custom tag by name
  2029. * @param {string} name - component name
  2030. * @param {Object} implementation - tag implementation
  2031. * @returns {Map} map containing all the components implementations
  2032. */
  2033. function register(name, _ref) {
  2034. let {
  2035. css,
  2036. template,
  2037. exports
  2038. } = _ref;
  2039. if (COMPONENTS_IMPLEMENTATION_MAP$1.has(name)) panic(`The component "${name}" was already registered`);
  2040. COMPONENTS_IMPLEMENTATION_MAP$1.set(name, createComponent({
  2041. name,
  2042. css,
  2043. template,
  2044. exports
  2045. }));
  2046. return COMPONENTS_IMPLEMENTATION_MAP$1;
  2047. }
  2048. /**
  2049. * Unregister a riot web component
  2050. * @param {string} name - component name
  2051. * @returns {Map} map containing all the components implementations
  2052. */
  2053. function unregister(name) {
  2054. if (!COMPONENTS_IMPLEMENTATION_MAP$1.has(name)) panic(`The component "${name}" was never registered`);
  2055. COMPONENTS_IMPLEMENTATION_MAP$1.delete(name);
  2056. cssManager.remove(name);
  2057. return COMPONENTS_IMPLEMENTATION_MAP$1;
  2058. }
  2059. /**
  2060. * Mounting function that will work only for the components that were globally registered
  2061. * @param {string|HTMLElement} selector - query for the selection or a DOM element
  2062. * @param {Object} initialProps - the initial component properties
  2063. * @param {string} name - optional component name
  2064. * @returns {Array} list of nodes upgraded
  2065. */
  2066. function mount(selector, initialProps, name) {
  2067. return $(selector).map(element => mountComponent(element, initialProps, name));
  2068. }
  2069. /**
  2070. * Sweet unmounting helper function for the DOM node mounted manually by the user
  2071. * @param {string|HTMLElement} selector - query for the selection or a DOM element
  2072. * @param {boolean|null} keepRootElement - if true keep the root element
  2073. * @returns {Array} list of nodes unmounted
  2074. */
  2075. function unmount(selector, keepRootElement) {
  2076. return $(selector).map(element => {
  2077. if (element[DOM_COMPONENT_INSTANCE_PROPERTY$1]) {
  2078. element[DOM_COMPONENT_INSTANCE_PROPERTY$1].unmount(keepRootElement);
  2079. }
  2080. return element;
  2081. });
  2082. }
  2083. /**
  2084. * Define a riot plugin
  2085. * @param {Function} plugin - function that will receive all the components created
  2086. * @returns {Set} the set containing all the plugins installed
  2087. */
  2088. function install(plugin) {
  2089. if (!isFunction(plugin)) panic('Plugins must be of type function');
  2090. if (PLUGINS_SET$1.has(plugin)) panic('This plugin was already install');
  2091. PLUGINS_SET$1.add(plugin);
  2092. return PLUGINS_SET$1;
  2093. }
  2094. /**
  2095. * Uninstall a riot plugin
  2096. * @param {Function} plugin - plugin previously installed
  2097. * @returns {Set} the set containing all the plugins installed
  2098. */
  2099. function uninstall(plugin) {
  2100. if (!PLUGINS_SET$1.has(plugin)) panic('This plugin was never installed');
  2101. PLUGINS_SET$1.delete(plugin);
  2102. return PLUGINS_SET$1;
  2103. }
  2104. /**
  2105. * Helpter method to create component without relying on the registered ones
  2106. * @param {Object} implementation - component implementation
  2107. * @returns {Function} function that will allow you to mount a riot component on a DOM node
  2108. */
  2109. function component(implementation) {
  2110. return (el, props) => compose(c => c.mount(el), c => c({
  2111. props
  2112. }), createComponent)(implementation);
  2113. }
  2114. /** @type {string} current riot version */
  2115. const version = 'v4.5.0'; // expose some internal stuff that might be used from external tools
  2116. const __ = {
  2117. cssManager,
  2118. defineComponent,
  2119. globals
  2120. };
  2121. /***/ }),
  2122. /***/ "./node_modules/smooth-scroll/dist/smooth-scroll.polyfills.min.js":
  2123. /*!************************************************************************!*\
  2124. !*** ./node_modules/smooth-scroll/dist/smooth-scroll.polyfills.min.js ***!
  2125. \************************************************************************/
  2126. /*! no static exports found */
  2127. /***/ (function(module, exports, __webpack_require__) {
  2128. /* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! smooth-scroll v16.1.0 | (c) 2019 Chris Ferdinandi | MIT License | http://github.com/cferdinandi/smooth-scroll */
  2129. window.Element&&!Element.prototype.closest&&(Element.prototype.closest=function(e){var t,n=(this.document||this.ownerDocument).querySelectorAll(e),o=this;do{for(t=n.length;0<=--t&&n.item(t)!==o;);}while(t<0&&(o=o.parentElement));return o}),(function(){if("function"==typeof window.CustomEvent)return;function e(e,t){t=t||{bubbles:!1,cancelable:!1,detail:void 0};var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),n}e.prototype=window.Event.prototype,window.CustomEvent=e})(),(function(){for(var r=0,e=["ms","moz","webkit","o"],t=0;t<e.length&&!window.requestAnimationFrame;++t)window.requestAnimationFrame=window[e[t]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[e[t]+"CancelAnimationFrame"]||window[e[t]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(e,t){var n=(new Date).getTime(),o=Math.max(0,16-(n-r)),a=window.setTimeout((function(){e(n+o)}),o);return r=n+o,a}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)})})(),(function(e,t){ true?!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function(){return t(e)}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
  2130. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)):undefined})("undefined"!=typeof global?global:"undefined"!=typeof window?window:this,(function(q){"use strict";var I={ignore:"[data-scroll-ignore]",header:null,topOnEmptyHash:!0,speed:500,speedAsDuration:!1,durationMax:null,durationMin:null,clip:!0,offset:0,easing:"easeInOutCubic",customEasing:null,updateURL:!0,popstate:!0,emitEvents:!0},F=function(){var n={};return Array.prototype.forEach.call(arguments,(function(e){for(var t in e){if(!e.hasOwnProperty(t))return;n[t]=e[t]}})),n},r=function(e){"#"===e.charAt(0)&&(e=e.substr(1));for(var t,n=String(e),o=n.length,a=-1,r="",i=n.charCodeAt(0);++a<o;){if(0===(t=n.charCodeAt(a)))throw new InvalidCharacterError("Invalid character: the input contains U+0000.");1<=t&&t<=31||127==t||0===a&&48<=t&&t<=57||1===a&&48<=t&&t<=57&&45===i?r+="\\"+t.toString(16)+" ":r+=128<=t||45===t||95===t||48<=t&&t<=57||65<=t&&t<=90||97<=t&&t<=122?n.charAt(a):"\\"+n.charAt(a)}return"#"+r},L=function(){return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)},x=function(e){return e?(t=e,parseInt(q.getComputedStyle(t).height,10)+e.offsetTop):0;var t},H=function(e,t,n,o){if(t.emitEvents&&"function"==typeof q.CustomEvent){var a=new CustomEvent(e,{bubbles:!0,detail:{anchor:n,toggle:o}});document.dispatchEvent(a)}};return function(o,e){var A,a,O,C,M={};M.cancelScroll=function(e){cancelAnimationFrame(C),C=null,e||H("scrollCancel",A)},M.animateScroll=function(i,c,e){M.cancelScroll();var s=F(A||I,e||{}),u="[object Number]"===Object.prototype.toString.call(i),t=u||!i.tagName?null:i;if(u||t){var l=q.pageYOffset;s.header&&!O&&(O=document.querySelector(s.header));var n,o,a,m,r,d,f,h,p=x(O),g=u?i:(function(e,t,n,o){var a=0;if(e.offsetParent)for(;a+=e.offsetTop,e=e.offsetParent;);return a=Math.max(a-t-n,0),o&&(a=Math.min(a,L()-q.innerHeight)),a})(t,p,parseInt("function"==typeof s.offset?s.offset(i,c):s.offset,10),s.clip),y=g-l,v=L(),w=0,S=(n=y,a=(o=s).speedAsDuration?o.speed:Math.abs(n/1e3*o.speed),o.durationMax&&a>o.durationMax?o.durationMax:o.durationMin&&a<o.durationMin?o.durationMin:parseInt(a,10)),E=function(e,t){var n,o,a,r=q.pageYOffset;if(e==t||r==t||(l<t&&q.innerHeight+r)>=v)return M.cancelScroll(!0),o=t,a=u,0===(n=i)&&document.body.focus(),a||(n.focus(),document.activeElement!==n&&(n.setAttribute("tabindex","-1"),n.focus(),n.style.outline="none"),q.scrollTo(0,o)),H("scrollStop",s,i,c),!(C=m=null)},b=function(e){var t,n,o;m||(m=e),w+=e-m,d=l+y*(n=r=1<(r=0===S?0:w/S)?1:r,"easeInQuad"===(t=s).easing&&(o=n*n),"easeOutQuad"===t.easing&&(o=n*(2-n)),"easeInOutQuad"===t.easing&&(o=n<.5?2*n*n:(4-2*n)*n-1),"easeInCubic"===t.easing&&(o=n*n*n),"easeOutCubic"===t.easing&&(o=--n*n*n+1),"easeInOutCubic"===t.easing&&(o=n<.5?4*n*n*n:(n-1)*(2*n-2)*(2*n-2)+1),"easeInQuart"===t.easing&&(o=n*n*n*n),"easeOutQuart"===t.easing&&(o=1- --n*n*n*n),"easeInOutQuart"===t.easing&&(o=n<.5?8*n*n*n*n:1-8*--n*n*n*n),"easeInQuint"===t.easing&&(o=n*n*n*n*n),"easeOutQuint"===t.easing&&(o=1+--n*n*n*n*n),"easeInOutQuint"===t.easing&&(o=n<.5?16*n*n*n*n*n:1+16*--n*n*n*n*n),t.customEasing&&(o=t.customEasing(n)),o||n),q.scrollTo(0,Math.floor(d)),E(d,g)||(C=q.requestAnimationFrame(b),m=e)};0===q.pageYOffset&&q.scrollTo(0,0),f=i,h=s,u||history.pushState&&h.updateURL&&history.pushState({smoothScroll:JSON.stringify(h),anchor:f.id},document.title,f===document.documentElement?"#top":"#"+f.id),"matchMedia"in q&&q.matchMedia("(prefers-reduced-motion)").matches?q.scrollTo(0,Math.floor(g)):(H("scrollStart",s,i,c),M.cancelScroll(!0),q.requestAnimationFrame(b))}};var t=function(e){if(!e.defaultPrevented&&!(0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey)&&"closest"in e.target&&(a=e.target.closest(o))&&"a"===a.tagName.toLowerCase()&&!e.target.closest(A.ignore)&&a.hostname===q.location.hostname&&a.pathname===q.location.pathname&&/#/.test(a.href)){var t,n=r(a.hash);if("#"===n){if(!A.topOnEmptyHash)return;t=document.
  2131. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js")))
  2132. /***/ }),
  2133. /***/ "./node_modules/webpack/buildin/global.js":
  2134. /*!***********************************!*\
  2135. !*** (webpack)/buildin/global.js ***!
  2136. \***********************************/
  2137. /*! no static exports found */
  2138. /***/ (function(module, exports) {
  2139. var g;
  2140. // This works in non-strict mode
  2141. g = (function() {
  2142. return this;
  2143. })();
  2144. try {
  2145. // This works if eval is allowed (see CSP)
  2146. g = g || new Function("return this")();
  2147. } catch (e) {
  2148. // This works if the window reference is available
  2149. if (typeof window === "object") g = window;
  2150. }
  2151. // g can still be undefined, but nothing to do about it...
  2152. // We return undefined, instead of nothing here, so it's
  2153. // easier to handle this case. if(!global) { ...}
  2154. module.exports = g;
  2155. /***/ }),
  2156. /***/ "./src/TinyOnePage.riot":
  2157. /*!******************************!*\
  2158. !*** ./src/TinyOnePage.riot ***!
  2159. \******************************/
  2160. /*! exports provided: default */
  2161. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  2162. "use strict";
  2163. __webpack_require__.r(__webpack_exports__);
  2164. /* harmony import */ var smooth_scroll__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! smooth-scroll */ "./node_modules/smooth-scroll/dist/smooth-scroll.polyfills.min.js");
  2165. /* harmony import */ var smooth_scroll__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(smooth_scroll__WEBPACK_IMPORTED_MODULE_0__);
  2166. /* harmony default export */ __webpack_exports__["default"] = ({
  2167. 'css': null,
  2168. 'exports': {
  2169. /**
  2170. * getting innerHTML and remove
  2171. *
  2172. *
  2173. */
  2174. onBeforeMount()
  2175. {
  2176. this.content = this.root.innerHTML
  2177. this.root.innerHTML = ''
  2178. },
  2179. /**
  2180. *
  2181. *
  2182. *
  2183. */
  2184. onMounted()
  2185. {
  2186. // adding content to wrapper
  2187. const wrapper = this.$('.tiny-one-page__inner');
  2188. wrapper.innerHTML = this.content;
  2189. // adding scroll smooth, get all elements with hash
  2190. this.scroll = new smooth_scroll__WEBPACK_IMPORTED_MODULE_0___default.a('.tiny-one-page__inner a[href*="#"]');
  2191. window.addEventListener('scroll', this.handleScroll.bind(this), false);
  2192. // if hash is set,
  2193. if (window.location.hash) {
  2194. this.$(".tiny-one-page__inner a[href$='" + window.location.hash + "']").click();
  2195. } else {
  2196. this.addClass(this.$$(".tiny-one-page__inner a")[0]);
  2197. }
  2198. },
  2199. /**
  2200. * add css class to parent element
  2201. *
  2202. * @param {Object} element
  2203. */
  2204. addClass(element)
  2205. {
  2206. element
  2207. .parentElement
  2208. .classList
  2209. .add('current');
  2210. },
  2211. /**
  2212. * remove css class from parent element
  2213. *
  2214. * @param {Object} element
  2215. */
  2216. removeClass(element)
  2217. {
  2218. element
  2219. .parentElement
  2220. .classList
  2221. .remove('current');
  2222. },
  2223. /**
  2224. * handle scrolling and check visibility of elements from navigation
  2225. *
  2226. * @param {Object} event
  2227. */
  2228. handleScroll(event)
  2229. {
  2230. // get elements
  2231. const elements = this.$$('.tiny-one-page__inner a');
  2232. // if found
  2233. let hasFound = false;
  2234. // get result
  2235. let result = undefined;
  2236. elements.forEach(function(element, index) {
  2237. // getting target
  2238. let target = document.querySelector(element.hash);
  2239. // check if there is a next element
  2240. let next = undefined;
  2241. // getting offsetTop
  2242. let offsetTop = target.offsetTop;
  2243. // check for next element
  2244. if (elements[index + 1]) {
  2245. next = document.querySelector(elements[index + 1].hash);
  2246. }
  2247. if (index === 0) {
  2248. offsetTop = 0;
  2249. }
  2250. // check if element is visible
  2251. if (!result && ((offsetTop <= window.pageYOffset) && (offsetTop + target.offsetHeight) > window.pageYOffset)) {
  2252. result = target;
  2253. // check if the next element is showing up
  2254. if (next && window.pageYOffset > offsetTop && next.offsetTop > window.pageYOffset && next.offsetTop < (window.pageYOffset + 800)) {
  2255. result = next;
  2256. }
  2257. }
  2258. // remove class from each element
  2259. this.removeClass(element);
  2260. }.bind(this));
  2261. // @TODO small workaround to ignore gaps between elements where no one found
  2262. if (result) {
  2263. this.addClass(this.$(".tiny-one-page__inner a[href$='" + result.id + "']"));
  2264. }
  2265. }
  2266. },
  2267. 'template': function(template, expressionTypes, bindingTypes, getComponent) {
  2268. return template(
  2269. '<div class="tiny-one-page"><div class="tiny-one-page__inner"></div><button class="tiny-one-page__button"><i class="icon icon-menu"></i></button></div>',
  2270. []
  2271. );
  2272. },
  2273. 'name': 'tiny-one-page'
  2274. });
  2275. /***/ }),
  2276. /***/ 0:
  2277. /*!*******************************************!*\
  2278. !*** multi ./demo-386.js ./demo-386.scss ***!
  2279. \*******************************************/
  2280. /*! no static exports found */
  2281. /***/ (function(module, exports, __webpack_require__) {
  2282. __webpack_require__(/*! /home/herrhase/Workspace/tentakelfabrik/tiny-components/tiny-one-page/demo-386.js */"./demo-386.js");
  2283. module.exports = __webpack_require__(/*! /home/herrhase/Workspace/tentakelfabrik/tiny-components/tiny-one-page/demo-386.scss */"./demo-386.scss");
  2284. /***/ })
  2285. /******/ });