Source: marketdatacard.js

  1. /**
  2. * Marketdatacard Component<BR>
  3. * <BR><BR><img src=/tk/lib/components/w/img/MarketDataCard.png width=30% style="border:1px lime dashed;padding:20px">
  4. * <BR><BR><a href="/tk/lib/components/w/html/MarketDataCard.html">DEMO</a>
  5. */
  6. class Marketdatacard extends HTMLElement {
  7. constructor() {
  8. wc.group("Marketdatacard.constructor")
  9. super();
  10. wc.groupEnd();
  11. };
  12. /**
  13. * Set observable values here. When Changed, attributeChangedCallback is invoked
  14. * @observedAttributes
  15. */
  16. static get observedAttributes() {
  17. wc.group("Marketdatacard.observedAttributes");
  18. this.observables = [];
  19. wc.groupEnd();
  20. return this.observables;
  21. };
  22. /**
  23. * Called when this is attached to DOM
  24. * @connectedCallback.
  25. */
  26. connectedCallback() {
  27. wc.group("Marketdatacard.connectedCallback")
  28. let self = this;
  29. // ADD A RANDOM ID IF NONE EXIST
  30. if (!this.id) {
  31. this.id = this.constructor.name.toLowerCase() + "-" + wc.uid();
  32. }
  33. // GET PROPERTIES AND INTERESTING ELEMENTS
  34. this._initialize();
  35. // ADD COMPONENT MARKTOP
  36. this.innerHTML = this._template()
  37. // PUBLISH ALL EVENTS OF INTEREST
  38. this._publish();
  39. // SUBSCRIBE TO ALL EVENTS OF INTEREST
  40. this._subscribe();
  41. // ADD STATS AND OTHER FINAL STUFF
  42. this._finalize();
  43. ga('send', {'hitType': 'event','eventCategory': 'wc-connected','eventAction': 'connected','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});
  44. wc.groupEnd();
  45. };
  46. /**
  47. * Initial Markup
  48. * @private
  49. * @_template
  50. */
  51. _template() {
  52. wc.group("Marketdatacard.template");
  53. let self = this;
  54. var temp = `
  55. <span class="marketdatacard-container">
  56. <span class="marketdatacard-logo-container clearfix">
  57. <span class="marketdatacard-logo float-left">
  58. <img src="/tk/img/common/crypto/${this.properties.asset}.png" alt="${this.properties.asset}" />
  59. </span>
  60. <span class="marketdatacard-asset float-left">
  61. <h1 class="wc-font-b">${this.properties.asset}</h1>
  62. <h3 class="wc-font-m">${this.properties.assetname}</h3>
  63. </span>
  64. </span>
  65. <span class="marketdatacard-chart-container pt-3">
  66. <svg class="sparkline sparkline-${this.properties.color}" width="500" height="40" stroke-width="4"></svg>
  67. </span>
  68. </span>`
  69. setTimeout(function(){
  70. document.querySelectorAll(`#${self.id} .sparkline`).forEach(function (svg) {
  71. sparkline.sparkline(svg, JSON.parse(self.properties.data));
  72. });
  73. }, 10);
  74. wc.groupEnd();
  75. return temp;
  76. };
  77. /**
  78. * Called with .setAttribute(...) function call
  79. * @attributeChangedCallback
  80. */
  81. attributeChangedCallback(attr, oldval, newval) {
  82. wc.group("Marketdatacard.attributeChangedCallback:", attr, oldval, newval);
  83. this.properties = this.properties || [];
  84. let obs = Marketdatacard.observedAttributes;
  85. for (let i = 0; i < obs.length; i++) {
  86. if (newval) {
  87. this.properties[obs[i]] = newval;
  88. }
  89. }
  90. // YOUR CODE FOR CHANGES GO HERE (MAYBE NULL FIRST TIME THROUGH)
  91. try {
  92. switch(attr)
  93. {
  94. case "header":
  95. //this.querySelector("h1").innerHTML = newval;
  96. break;
  97. default:
  98. break;
  99. }
  100. } catch(e) {
  101. wc.warn(e.name + ' > ' + e.message);
  102. }
  103. wc.groupEnd();
  104. };
  105. /**
  106. * Stores DOM elements of interest for future use
  107. * @private
  108. * @_fetchElements
  109. */
  110. _fetchElements() {
  111. wc.group("Marketdatacard._fetchElements");
  112. this.dom = this.dom || [];
  113. this.dom.content = this.innerHTML;
  114. wc.groupEnd();
  115. };
  116. /**
  117. * Component attributes are _fetched and defaults are set if undefined
  118. * @private
  119. * @_fetchAttributes
  120. */
  121. _fetchAttributes() {
  122. wc.group("Marketdatacard._fetchAttributes");
  123. this.properties = {
  124. uparam : "",
  125. cname : "Marketdatacard",
  126. author : "Mel M. Heravi, Ph.D.",
  127. version : "1.0"
  128. };
  129. // SAVE WIDGET SPECIFIC PROPERTIES
  130. this.propertiesW = [];
  131. // SAVE ALL OTHER PROPERTIES
  132. let attrs = wc.getAttributes(this)
  133. for (var key in attrs) {
  134. let attr = this.getAttribute(key) || this.properties.key;
  135. this.properties[key] = this.getAttribute(key);
  136. this.propertiesW[key] = this.getAttribute(key);
  137. wc.log(key + ": " + attrs[key]);
  138. }
  139. // SET ALL INITIAL ATTRIBUTES
  140. for (var key in this.properties) {
  141. switch(key)
  142. {
  143. case "header":
  144. break;
  145. default:
  146. break;
  147. }
  148. }
  149. wc.log("ATTRIBUTES: ", this.properties);
  150. wc.groupEnd();
  151. };
  152. /**
  153. * configure the instance object and artifacts
  154. * @configure
  155. * @param {string} data use data if exist else use 'this.properties.cfg' parameter
  156. */
  157. configure(data) {
  158. wc.group("Marketdatacard.configure:", data);
  159. // IF JSON VARIABLE (data) IS PROVIDED
  160. if (data) {
  161. this._process(data);
  162. } else {
  163. let self = this;
  164. $.getJSON(this.properties.cfg, function(data) {
  165. self._process(data);
  166. }).fail(function(jqXHR, textStatus, errorThrown) {
  167. alert("ERROR: INCOMING TEXT " + jqXHR.responseText);
  168. });
  169. }
  170. wc.groupEnd();
  171. };
  172. /**
  173. * _process the instance object and artifacts
  174. * @private
  175. * @_process
  176. */
  177. _process(data) {
  178. wc.group("Marketdatacard._process:", data);
  179. // DO WHATEVER WITH THE DATA
  180. wc.groupEnd();
  181. };
  182. /**
  183. * Initialize component
  184. * @private
  185. * @_initialize
  186. */
  187. _initialize() {
  188. wc.group("Marketdatacard._initialize:", this.id);
  189. // FETCH ALL INTERESTING ELEMENTS
  190. this._fetchElements();
  191. // FETCH ALL ATTRIBUTES
  192. this._fetchAttributes();
  193. wc.groupEnd();
  194. };
  195. /**
  196. * Save data for analytics and final wrap up
  197. * @private
  198. * @_finalize
  199. */
  200. _finalize() {
  201. wc.group("Marketdatacard._finalize:", this.id);
  202. this.classList.add("wc");
  203. // ADD ANALYTICS HERE
  204. wc.setStats(this, this.properties.cname, this.properties.version);
  205. // SHOW IT NOW (NO FLICKERS)
  206. this.style.visibility = "visible";
  207. wc.groupEnd();
  208. };
  209. /**
  210. * Invoked When component is removed. Usually with a .remove() function call
  211. * @disconnectedCallback
  212. */
  213. disconnectedCallback() {
  214. wc.group("Marketdatacard.disconnectedCallback")
  215. ga('send', {'hitType': 'event','eventCategory': 'wc-disconnected','eventAction': 'disconnected','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});
  216. wc.groupEnd();
  217. };
  218. /**
  219. * Destroy the instance object and artifacts
  220. * @destroy
  221. */
  222. destroy() {
  223. wc.group("Marketdatacard.destroy");
  224. // FREE ALL MEMORY
  225. // you should delete all created objects here
  226. // FREE POINTER
  227. delete this;
  228. // REMOVE ITEM FROM DOM
  229. this.parentNode.removeChild(this);
  230. ga('send', {'hitType': 'event','eventCategory': 'wc-destroyed','eventAction': 'distroy','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});
  231. wc.groupEnd();
  232. };
  233. /**
  234. * @_publish
  235. */
  236. _publish() {
  237. wc.group("Marketdatacard._publish");
  238. let self = this;
  239. // PUBLISH CLICK EVENTS
  240. $(this).on("click", () => {
  241. wc.publish("wc-marketdatacard", {
  242. id: self.id,
  243. time: new Date().getTime(),
  244. action: "click"
  245. });
  246. ga('send', {'hitType': 'event','eventCategory': 'wc-MarketDataCard','eventAction': 'click','eventLabel': self.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});
  247. });
  248. wc.groupEnd();
  249. return true;
  250. };
  251. /**
  252. * Subscribe all to events of interest
  253. * @private
  254. * @_subscribe
  255. */
  256. _subscribe() {
  257. wc.group("Marketdatacard._subscribe:", this.id);
  258. let self = this;
  259. wc.subscribe("wc-marketdatacard", function(msg, e) {
  260. console.log(">>>>>> E:", self.id, JSON.stringify(e));
  261. if (e.id == self.id && e.action == "update") {
  262. self._update(e.id, e.data);
  263. }
  264. wc.info("'wc-marketdatacard-update' subscription was triggered:", JSON.stringify(e));
  265. });
  266. wc.groupEnd();
  267. }
  268. /**
  269. * @private
  270. * @_update
  271. */
  272. _update(id, data) {
  273. wc.group("Marketdatacard._update:", id, JSON.stringify(data));
  274. let self = this;
  275. document.querySelectorAll(`#${id} .sparkline`).forEach(function (svg) {
  276. sparkline.sparkline(svg, JSON.parse(data));
  277. });
  278. wc.groupEnd();
  279. }
  280. /**
  281. * @_request
  282. */
  283. _request(e) {
  284. wc.group("Marketdatacard._request:", this.id, JSON.stringify(e.detail));
  285. switch(e.detail.request)
  286. {
  287. case "label":
  288. let h1 = this.querySelector("h1");
  289. h1.innerHTML = e.detail.str;
  290. this._publish("labelChanged");
  291. break;
  292. default:
  293. alert("DO NOT HAVE SUCH REQUEST: " + e.detail.request);
  294. break;
  295. }
  296. wc.groupEnd();
  297. return true;
  298. };
  299. /**
  300. * @test
  301. */
  302. static test(what) {
  303. wc.group("Marketdatacard.test:", what);
  304. switch(what)
  305. {
  306. case "label":
  307. wc.publish("my-MarketDataCard", {time:new Date().getTime(), requestor:"my-MarketDataCard", request:"label", str:"Hello Mel !"})
  308. break;
  309. }
  310. wc.groupEnd();
  311. return true;
  312. }
  313. }
  314. window.customElements.define('wc-marketdatacard', Marketdatacard);
  315. var sparkline=function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=1)}([function(t,e,r){var n=r(2),o=r(3),i=r(4);t.exports=function(t){return n(t)||o(t)||i()}},function(t,e,r){"use strict";r.r(e),r.d(e,"sparkline",function(){return c});var n=r(0),o=r.n(n);function i(t,e,r,n){return parseFloat((e-n*e/t+r).toFixed(2))}function a(t){return t.value}function u(t,e){var r=document.createElementNS("http://www.w3.org/2000/svg",t);for(var n in e)r.setAttribute(n,e[n]);return r}function c(t,e,r){var n;if(n=t,o()(n.querySelectorAll("*")).forEach(function(t){return n.removeChild(t)}),!(e.length<=1)){r=r||{},"number"==typeof e[0]&&(e=e.map(function(t){return{value:t}}));var c=r.onmousemove,l=r.onmouseout,s="interactive"in r?r.interactive:!!c,f=r.spotRadius||2,p=2*f,d=r.cursorWidth||2,v=parseFloat(t.attributes["stroke-width"].value),b=r.fetch||a,h=e.map(function(t){return b(t)}),y=parseFloat(t.attributes.width.value)-2*p,x=parseFloat(t.attributes.height.value),m=x-2*v-p,g=Math.max.apply(Math,o()(h)),A=-1e3,w=h.length-1,j=y/w,k=[],O=i(g,m,v+f,h[0]),S="M".concat(p," ").concat(O);h.forEach(function(t,r){var n=r*j+p,o=i(g,m,v+f,t);k.push(Object.assign({},e[r],{index:r,x:n,y:o})),S+=" L ".concat(n," ").concat(o)});var M=u("path",{class:"sparkline--line",d:S,fill:"none"}),C=u("path",{class:"sparkline--fill",d:"".concat(S," V ").concat(x," L ").concat(p," ").concat(x," Z"),stroke:"none"});if(t.appendChild(C),t.appendChild(M),s){var E=u("line",{class:"sparkline--cursor",x1:A,x2:A,y1:0,y2:x,"stroke-width":d}),_=u("circle",{class:"sparkline--spot",cx:A,cy:A,r:f});t.appendChild(E),t.appendChild(_);var F=u("rect",{width:t.attributes.width.value,height:t.attributes.height.value,style:"fill: transparent; stroke: transparent",class:"sparkline--interaction-layer"});t.appendChild(F),F.addEventListener("mouseout",function(t){E.setAttribute("x1",A),E.setAttribute("x2",A),_.setAttribute("cx",A),l&&l(t)}),F.addEventListener("mousemove",function(t){var e=t.offsetX,r=k.find(function(t){return t.x>=e});r||(r=k[w]);var n,o=k[k.indexOf(r)-1],i=(n=o?o.x+(r.x-o.x)/2<=e?r:o:r).x,a=n.y;_.setAttribute("cx",i),_.setAttribute("cy",a),E.setAttribute("x1",i),E.setAttribute("x2",i),c&&c(t,n)})}}}e.default=c},function(t,e){t.exports=function(t){if(Array.isArray(t)){for(var e=0,r=new Array(t.length);e<t.length;e++)r[e]=t[e];return r}}},function(t,e){t.exports=function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}},function(t,e){t.exports=function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}}]);
  316. //# sourceMappingURL=sparkline.js.map