graph.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. /*!
  2. * All material copyright ESRI, All Rights Reserved, unless otherwise specified.
  3. * See https://github.com/Esri/calcite-components/blob/master/LICENSE.md for details.
  4. * v1.0.0-beta.97
  5. */
  6. import { proxyCustomElement, HTMLElement, forceUpdate, h } from '@stencil/core/internal/client/index.js';
  7. import { g as guid } from './guid.js';
  8. import { c as createObserver } from './observers.js';
  9. /**
  10. * Calculate slope of the tangents
  11. * uses Steffen interpolation as it's monotonic
  12. * http://jrwalsh1.github.io/posts/interpolations/
  13. *
  14. * @param p0
  15. * @param p1
  16. * @param p2
  17. */
  18. function slope(p0, p1, p2) {
  19. const dx = p1[0] - p0[0];
  20. const dx1 = p2[0] - p1[0];
  21. const dy = p1[1] - p0[1];
  22. const dy1 = p2[1] - p1[1];
  23. const m = dy / (dx || (dx1 < 0 && 0));
  24. const m1 = dy1 / (dx1 || (dx < 0 && 0));
  25. const p = (m * dx1 + m1 * dx) / (dx + dx1);
  26. return (Math.sign(m) + Math.sign(m1)) * Math.min(Math.abs(m), Math.abs(m1), 0.5 * Math.abs(p)) || 0;
  27. }
  28. /**
  29. * Calculate slope for just one tangent (single-sided)
  30. *
  31. * @param p0
  32. * @param p1
  33. * @param m
  34. */
  35. function slopeSingle(p0, p1, m) {
  36. const dx = p1[0] - p0[0];
  37. const dy = p1[1] - p0[1];
  38. return dx ? ((3 * dy) / dx - m) / 2 : m;
  39. }
  40. /**
  41. * Given two points and their tangent slopes,
  42. * calculate the bezier handle coordinates and return draw command.
  43. *
  44. * Translates Hermite Spline to Beziér curve:
  45. * stackoverflow.com/questions/42574940/
  46. *
  47. * @param p0
  48. * @param p1
  49. * @param m0
  50. * @param m1
  51. * @param t
  52. */
  53. function bezier(p0, p1, m0, m1, t) {
  54. const [x0, y0] = p0;
  55. const [x1, y1] = p1;
  56. const dx = (x1 - x0) / 3;
  57. const h1 = t([x0 + dx, y0 + dx * m0]).join(",");
  58. const h2 = t([x1 - dx, y1 - dx * m1]).join(",");
  59. const p = t([x1, y1]).join(",");
  60. return `C ${h1} ${h2} ${p}`;
  61. }
  62. /**
  63. * Generate a function which will translate a point
  64. * from the data coordinate space to svg viewbox oriented pixels
  65. *
  66. * @param root0
  67. * @param root0.width
  68. * @param root0.height
  69. * @param root0.min
  70. * @param root0.max
  71. */
  72. function translate({ width, height, min, max }) {
  73. const rangeX = max[0] - min[0];
  74. const rangeY = max[1] - min[1];
  75. return (point) => {
  76. const x = ((point[0] - min[0]) / rangeX) * width;
  77. const y = height - (point[1] / rangeY) * height;
  78. return [x, y];
  79. };
  80. }
  81. /**
  82. * Get the min and max values from the dataset
  83. *
  84. * @param data
  85. */
  86. function range(data) {
  87. const [startX, startY] = data[0];
  88. const min = [startX, startY];
  89. const max = [startX, startY];
  90. return data.reduce(({ min, max }, [x, y]) => ({
  91. min: [Math.min(min[0], x), Math.min(min[1], y)],
  92. max: [Math.max(max[0], x), Math.max(max[1], y)]
  93. }), { min, max });
  94. }
  95. /**
  96. * Generate drawing commands for an area graph
  97. * returns a string can can be passed directly to a path element's `d` attribute
  98. *
  99. * @param root0
  100. * @param root0.data
  101. * @param root0.min
  102. * @param root0.max
  103. * @param root0.t
  104. */
  105. function area({ data, min, max, t }) {
  106. if (data.length === 0) {
  107. return "";
  108. }
  109. // important points for beginning and ending the path
  110. const [startX, startY] = t(data[0]);
  111. const [minX, minY] = t(min);
  112. const [maxX] = t(max);
  113. // keep track of previous slope/points
  114. let m;
  115. let p0;
  116. let p1;
  117. // iterate over data points, calculating command for each
  118. const commands = data.reduce((acc, point, i) => {
  119. p0 = data[i - 2];
  120. p1 = data[i - 1];
  121. if (i > 1) {
  122. const m1 = slope(p0, p1, point);
  123. const m0 = m === undefined ? slopeSingle(p0, p1, m1) : m;
  124. const command = bezier(p0, p1, m0, m1, t);
  125. m = m1;
  126. return `${acc} ${command}`;
  127. }
  128. return acc;
  129. }, `M ${minX},${minY} L ${minX},${startY} L ${startX},${startY}`);
  130. // close the path
  131. const last = data[data.length - 1];
  132. const end = bezier(p1, last, m, slopeSingle(p1, last, m), t);
  133. return `${commands} ${end} L ${maxX},${minY} Z`;
  134. }
  135. const graphCss = "@keyframes in{0%{opacity:0}100%{opacity:1}}@keyframes in-down{0%{opacity:0;transform:translate3D(0, -5px, 0)}100%{opacity:1;transform:translate3D(0, 0, 0)}}@keyframes in-up{0%{opacity:0;transform:translate3D(0, 5px, 0)}100%{opacity:1;transform:translate3D(0, 0, 0)}}@keyframes in-scale{0%{opacity:0;transform:scale3D(0.95, 0.95, 1)}100%{opacity:1;transform:scale3D(1, 1, 1)}}:root{--calcite-animation-timing:calc(150ms * var(--calcite-internal-duration-factor));--calcite-internal-duration-factor:var(--calcite-duration-factor, 1);--calcite-internal-animation-timing-fast:calc(100ms * var(--calcite-internal-duration-factor));--calcite-internal-animation-timing-medium:calc(200ms * var(--calcite-internal-duration-factor));--calcite-internal-animation-timing-slow:calc(300ms * var(--calcite-internal-duration-factor))}.calcite-animate{opacity:0;animation-fill-mode:both;animation-duration:var(--calcite-animation-timing)}.calcite-animate__in{animation-name:in}.calcite-animate__in-down{animation-name:in-down}.calcite-animate__in-up{animation-name:in-up}.calcite-animate__in-scale{animation-name:in-scale}@media (prefers-reduced-motion: reduce){:root{--calcite-internal-duration-factor:0.01}}:root{--calcite-floating-ui-transition:var(--calcite-animation-timing)}:host([hidden]){display:none}:host{display:block;block-size:100%}.svg{fill:currentColor;stroke:transparent;margin:0px;display:block;block-size:100%;inline-size:100%;padding:0px}.svg .graph-path--highlight{fill:var(--calcite-ui-brand);opacity:0.5}";
  136. const Graph = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  137. constructor() {
  138. super();
  139. this.__registerHost();
  140. this.__attachShadow();
  141. //--------------------------------------------------------------------------
  142. //
  143. // Properties
  144. //
  145. //--------------------------------------------------------------------------
  146. /**
  147. * Array of tuples describing a single data point ([x, y])
  148. * These data points should be sorted by x-axis value
  149. */
  150. this.data = [];
  151. //--------------------------------------------------------------------------
  152. //
  153. // Private State/Props
  154. //
  155. //--------------------------------------------------------------------------
  156. this.graphId = `calcite-graph-${guid()}`;
  157. this.resizeObserver = createObserver("resize", () => forceUpdate(this));
  158. }
  159. //--------------------------------------------------------------------------
  160. //
  161. // Lifecycle
  162. //
  163. //--------------------------------------------------------------------------
  164. connectedCallback() {
  165. var _a;
  166. (_a = this.resizeObserver) === null || _a === void 0 ? void 0 : _a.observe(this.el);
  167. }
  168. disconnectedCallback() {
  169. var _a;
  170. (_a = this.resizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
  171. }
  172. render() {
  173. const { data, colorStops, el, highlightMax, highlightMin, min, max } = this;
  174. const id = this.graphId;
  175. const { clientHeight: height, clientWidth: width } = el;
  176. // if we have no data, return empty svg
  177. if (!data || data.length === 0) {
  178. return (h("svg", { class: "svg", height: height, preserveAspectRatio: "none", viewBox: `0 0 ${width} ${height}`, width: width }));
  179. }
  180. const { min: rangeMin, max: rangeMax } = range(data);
  181. let currentMin = rangeMin;
  182. let currentMax = rangeMax;
  183. if (min < rangeMin[0] || min > rangeMin[0]) {
  184. currentMin = [min, 0];
  185. }
  186. if (max > rangeMax[0] || max < rangeMax[0]) {
  187. currentMax = [max, rangeMax[1]];
  188. }
  189. const t = translate({ min: currentMin, max: currentMax, width, height });
  190. const [hMinX] = t([highlightMin, currentMax[1]]);
  191. const [hMaxX] = t([highlightMax, currentMax[1]]);
  192. const areaPath = area({ data, min: rangeMin, max: rangeMax, t });
  193. const fill = colorStops ? `url(#linear-gradient-${id})` : undefined;
  194. return (h("svg", { class: "svg", height: height, preserveAspectRatio: "none", viewBox: `0 0 ${width} ${height}`, width: width }, colorStops ? (h("defs", null, h("linearGradient", { id: `linear-gradient-${id}`, x1: "0", x2: "1", y1: "0", y2: "0" }, colorStops.map(({ offset, color, opacity }) => (h("stop", { offset: `${offset * 100}%`, "stop-color": color, "stop-opacity": opacity })))))) : null, highlightMin !== undefined ? ([
  195. h("mask", { height: "100%", id: `${id}1`, width: "100%", x: "0%", y: "0%" }, h("path", { d: `
  196. M 0,0
  197. L ${hMinX - 1},0
  198. L ${hMinX - 1},${height}
  199. L 0,${height}
  200. Z
  201. `, fill: "white" })),
  202. h("mask", { height: "100%", id: `${id}2`, width: "100%", x: "0%", y: "0%" }, h("path", { d: `
  203. M ${hMinX + 1},0
  204. L ${hMaxX - 1},0
  205. L ${hMaxX - 1},${height}
  206. L ${hMinX + 1}, ${height}
  207. Z
  208. `, fill: "white" })),
  209. h("mask", { height: "100%", id: `${id}3`, width: "100%", x: "0%", y: "0%" }, h("path", { d: `
  210. M ${hMaxX + 1},0
  211. L ${width},0
  212. L ${width},${height}
  213. L ${hMaxX + 1}, ${height}
  214. Z
  215. `, fill: "white" })),
  216. h("path", { class: "graph-path", d: areaPath, fill: fill, mask: `url(#${id}1)` }),
  217. h("path", { class: "graph-path--highlight", d: areaPath, fill: fill, mask: `url(#${id}2)` }),
  218. h("path", { class: "graph-path", d: areaPath, fill: fill, mask: `url(#${id}3)` })
  219. ]) : (h("path", { class: "graph-path", d: areaPath, fill: fill }))));
  220. }
  221. get el() { return this; }
  222. static get style() { return graphCss; }
  223. }, [1, "calcite-graph", {
  224. "data": [16],
  225. "colorStops": [16],
  226. "highlightMin": [2, "highlight-min"],
  227. "highlightMax": [2, "highlight-max"],
  228. "min": [514],
  229. "max": [514]
  230. }]);
  231. function defineCustomElement() {
  232. if (typeof customElements === "undefined") {
  233. return;
  234. }
  235. const components = ["calcite-graph"];
  236. components.forEach(tagName => { switch (tagName) {
  237. case "calcite-graph":
  238. if (!customElements.get(tagName)) {
  239. customElements.define(tagName, Graph);
  240. }
  241. break;
  242. } });
  243. }
  244. defineCustomElement();
  245. export { Graph as G, defineCustomElement as d };