tiny-spark 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -101,6 +101,39 @@ Render a bar chart:
101
101
  </div>
102
102
  ```
103
103
 
104
+ ### Keyboard and touch
105
+
106
+ Each chart with data adds one tab stop unless you provide a `tabindex`. Use the left and right arrow keys to inspect points, Home and End to jump to the first and last points, and Escape to hide the tooltip. On touch screens, tap a point to show its tooltip. Tap it again or tap outside the chart to dismiss it. Use `role="group"` and a descriptive `aria-label` to distinguish each chart from nearby charts.
107
+
108
+ ### Comparing charts
109
+
110
+ Set the same `data-y-min` and `data-y-max` on charts you want to compare. For example, `data-y-min="0" data-y-max="200"` uses a fixed vertical scale from 0 to 200 for both line and bar charts. You can supply just one bound. The other then includes zero and the data, as appropriate. Values outside the range are drawn at the nearest bound and keep their original values in tooltips. An invalid range falls back to automatic scaling.
111
+
112
+ ### Formatting values
113
+
114
+ The tooltip and last-value label both use `data-number-locale` and `data-number-rounding`. Add a style to display currency, percentages, or units.
115
+
116
+ | Display | Attributes | Example |
117
+ | --- | --- | --- |
118
+ | Currency | `data-number-style="currency" data-number-currency="USD" data-number-rounding="2"` | `12.5` becomes `$12.50` in `en-US` |
119
+ | Percentage | `data-number-style="percent"` | `0.25` becomes `25%` |
120
+ | Unit | `data-number-style="unit" data-number-unit="kilometer"` | `12` becomes `12 km` in `en-US` |
121
+
122
+ ### Rendering within a container
123
+
124
+ Pass a chart or its container to initialize just that part of the page. Call `destroy` before unmounting a component to disconnect its observers, remove generated SVG and tooltip elements, and release interaction handlers. Calling either function with no argument targets the current document.
125
+
126
+ ```js
127
+ import { destroy, render } from "tiny-spark";
128
+
129
+ const dashboard = document.querySelector("#dashboard");
130
+ if (dashboard) {
131
+ render(dashboard);
132
+ // In the component's unmount hook
133
+ // destroy(dashboard);
134
+ }
135
+ ```
136
+
104
137
  ## Styling
105
138
 
106
139
  tiny-spark is headless.
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Tiny Spark - render
3
+ * ---
4
+ * Renders `.tiny-spark` charts from their data attributes.
5
+ *
6
+ * Charts update when their supported attributes change or their parent resizes.
7
+ *
8
+ * Call after adding charts to the DOM or loading their data. Calling again
9
+ * restarts animations for charts with `data-animation="true"`.
10
+ *
11
+ * @param root - A chart, containing element, document, or document fragment.
12
+ * Defaults to the current document.
13
+ */
14
+ export declare function render(root: ParentNode | undefined): void;
15
+ /** Renders all `.tiny-spark` charts in the current document. */
16
+ export declare function render(): void;
17
+ /**
18
+ * Stops observing matching charts and removes their generated SVG and tooltip.
19
+ * Call `render` to initialize them again.
20
+ *
21
+ * @param root - A chart, containing element, document, or document fragment.
22
+ * Defaults to the current document.
23
+ */
24
+ export declare function destroy(root?: ParentNode): void;
25
+ /**
26
+ * Tiny Spark - tinyFormat
27
+ * ---
28
+ * Serializes chart values or date labels as a JSON array for a data attribute.
29
+ *
30
+ * @param arr - Chart values or date labels, with `null` for missing entries.
31
+ * @returns The JSON string to pass to `setAttribute` or assign through `dataset`.
32
+ * @example
33
+ * chart.dataset.set = tinyFormat([1, null, 3]);
34
+ * chart.dataset.dates = tinyFormat(["Jan", "Feb", "Mar"]);
35
+ */
36
+ export declare function tinyFormat(arr: Array<number | string | null>): string;
@@ -1,543 +1,6 @@
1
- //#region types/index.ts
2
- var e = "http://www.w3.org/2000/svg", t = 1e3, n = /* @__PURE__ */ function(e) {
3
- return e.BAR = "bar", e.LINE = "line", e;
4
- }({}), r = /* @__PURE__ */ function(e) {
5
- return e.ANIMATION = "animation", e.AREA_COLOR = "areaColor", e.CURVE = "curve", e.DATES = "dates", e.ID = "id", e.INDICATOR_COLOR = "indicatorColor", e.INDICATOR_WIDTH = "indicatorWidth", e.LINE_COLOR = "lineColor", e.LINE_THICKNESS = "lineThickness", e.NUMBER_LOCALE = "numberLocale", e.NUMBER_ROUNDING = "numberRounding", e.NUMBER_SHOW_ON = "numberShowOn", e.PLOT_COLOR = "plotColor", e.PLOT_RADIUS = "plotRadius", e.SET = "set", e.HIDE_PLOTS_ABOVE = "hidePlotsAbove", e.SHOW_LAST_VALUE = "showLastValue", e.LAST_VALUE_FONT_SIZE = "lastValueFontSize", e.LAST_VALUE_COLOR = "lastValueColor", e.TYPE = "type", e.TOOLTIP_SMOOTHING = "tooltipSmoothing", e.CUT_NULL = "cutNull", e.GRADIENT_FROM = "gradientFrom", e.GRADIENT_TO = "gradientTo", e.GRADIENT_FROM_OPACITY = "gradientFromOpacity", e.GRADIENT_TO_OPACITY = "gradientToOpacity", e.TEMPERATURE_COLORS = "temperatureColors", e;
6
- }({}), i = /* @__PURE__ */ function(e) {
7
- return e.ANIMATION = "data-animation", e.AREA_COLOR = "data-area-color", e.CURVE = "data-curve", e.DATES = "data-dates", e.ID = "data-id", e.INDICATOR_COLOR = "data-indicator-color", e.INDICATOR_WIDTH = "data-indicator-width", e.LINE_COLOR = "data-line-color", e.LINE_THICKNESS = "data-line-thickness", e.NUMBER_LOCALE = "data-number-locale", e.NUMBER_ROUNDING = "data-number-rounding", e.NUMBER_SHOW_ON = "data-number-show-on", e.PLOT_COLOR = "data-plot-color", e.PLOT_RADIUS = "data-plot-radius", e.SET = "data-set", e.HIDE_PLOTS_ABOVE = "data-hide-plots-above", e.SHOW_LAST_VALUE = "data-show-last-value", e.LAST_VALUE_FONT_SIZE = "data-last-value-font-size", e.LAST_VALUE_COLOR = "data-last-value-color", e.TYPE = "data-type", e.TOOLTIP_SMOOTHING = "data-tooltip-smoothing", e.CUT_NULL = "data-cut-null", e.GRADIENT_FROM = "data-gradient-from", e.GRADIENT_TO = "data-gradient-to", e.GRADIENT_FROM_OPACITY = "data-gradient-from-opacity", e.GRADIENT_TO_OPACITY = "data-gradient-to-opacity", e.TEMPERATURE_COLORS = "data-temperature-colors", e;
8
- }({}), a = {
9
- name: "tiny-spark",
10
- private: !1,
11
- version: "1.2.3",
12
- type: "module",
13
- description: "An elegant, reactive and responsive sparkline chart solution without dependency.",
14
- author: "Alec Lloyd Probert",
15
- main: "./dist/tiny-spark.es.js",
16
- exports: "./dist/tiny-spark.es.js",
17
- keywords: [
18
- "sparkline",
19
- "chart",
20
- "mini chart",
21
- "line",
22
- "framework agnostic"
23
- ],
24
- license: "MIT",
25
- repository: {
26
- type: "git",
27
- url: "git+https://github.com/graphieros/tiny-spark.git"
28
- },
29
- homepage: "https://tiny-spark.graphieros.com/",
30
- scripts: {
31
- dev: "vite",
32
- build: "tsc && vite build"
33
- },
34
- files: ["dist"],
35
- devDependencies: {
36
- "@types/node": "^24.0.8",
37
- typescript: "~5.8.3",
38
- vite: "^8.2.1"
39
- }
40
- };
41
- //#endregion
42
- //#region src/svg.ts
43
- function o(t) {
44
- let { width: n, height: i } = t.parentElement.getBoundingClientRect(), o = {
45
- width: 300,
46
- height: 100
47
- }, s = String(v(t, r.SHOW_LAST_VALUE, "false")) === "true", c = b(t), l = c && c.length ? c.at(-1) : null, u = 0;
48
- if (!(t.dataset.type && t.dataset.type === "bar") && s && ![null, void 0].includes(l)) {
49
- let e = Number(String(v(t, r.NUMBER_ROUNDING, 0)));
50
- u = 6 + l.toFixed(e).length * (Number(v(t, r.LAST_VALUE_FONT_SIZE, 12)) / 2);
51
- }
52
- let d = `0 0 ${(n || o.width) + u} ${i || o.height}`, f = document.createElementNS(e, "svg"), p = t.dataset.id;
53
- f.id = p, f.setAttribute("viewBox", d), f.style.width = "100%", f.style.height = "100%";
54
- let m = document.createElementNS(e, "desc");
55
- return m.setAttribute("aria-hidden", "true"), m.innerHTML = `Composed with tiny-spark v${a.version}`, f.appendChild(m), {
56
- svg: f,
57
- svgId: p,
58
- width: n || o.width,
59
- height: i || o.height,
60
- viewBox: d
61
- };
62
- }
63
- function s(e, t = 0) {
64
- return isNaN(e) ? t : e;
65
- }
66
- function c(e) {
67
- let t = [];
68
- for (let n = 0; n < e.length; n += 1) t.push(`${s(e[n].x)},${s(e[n].y)} `);
69
- return t.join(" ").trim();
70
- }
71
- function l(e) {
72
- if (e.length < 2) return "0,0";
73
- let t = e.length - 1, n = [`${s(e[0].x)},${s(e[0].y)}`], r = [], i = [], a = [], o = [];
74
- for (let n = 0; n < t; n += 1) r[n] = e[n + 1].x - e[n].x, i[n] = e[n + 1].y - e[n].y, a[n] = i[n] / r[n];
75
- o[0] = a[0], o[t] = a[t - 1];
76
- for (let e = 1; e < t; e += 1) if (a[e - 1] * a[e] <= 0) o[e] = 0;
77
- else {
78
- let t = 2 * a[e - 1] * a[e] / (a[e - 1] + a[e]);
79
- o[e] = t;
80
- }
81
- for (let r = 0; r < t; r += 1) {
82
- let t = e[r].x, i = e[r].y, a = e[r + 1].x, c = e[r + 1].y, l = o[r], u = o[r + 1], d = t + (a - t) / 3, f = i + l * (a - t) / 3, p = a - (a - t) / 3, m = c - u * (a - t) / 3;
83
- n.push(`C ${s(d)},${s(f)} ${s(p)},${s(m)} ${s(a)},${s(c)}`);
84
- }
85
- return n.join(" ");
86
- }
87
- function u(e) {
88
- let t = [], n = [];
89
- for (let r of e) r.v == null || Number.isNaN(r.x) || Number.isNaN(r.y) ? (n.length > 1 && t.push(n), n = []) : n.push(r);
90
- return n.length > 1 && t.push(n), t;
91
- }
92
- function d(e) {
93
- let t = u(e);
94
- if (!t.length) return "";
95
- let n = "";
96
- for (let [e, r] of t.entries()) {
97
- if (r.length < 2) continue;
98
- let t = r.length - 1, i = [], a = [], o = [], c = [];
99
- for (let e = 0; e < t; e += 1) i[e] = r[e + 1].x - r[e].x, a[e] = r[e + 1].y - r[e].y, o[e] = a[e] / i[e];
100
- c[0] = o[0], c[t] = o[t - 1];
101
- for (let e = 1; e < t; e += 1) if (o[e - 1] * o[e] <= 0) c[e] = 0;
102
- else {
103
- let t = 2 * o[e - 1] * o[e] / (o[e - 1] + o[e]);
104
- c[e] = t;
105
- }
106
- n += `${e === 0 ? "" : "M"}${s(r[0].x)},${s(r[0].y)} `;
107
- for (let e = 0; e < t; e += 1) {
108
- let t = r[e].x, i = r[e].y, a = r[e + 1].x, o = r[e + 1].y, l = c[e], u = c[e + 1], d = t + (a - t) / 3, f = i + l * (a - t) / 3, p = a - (a - t) / 3, m = o - u * (a - t) / 3;
109
- n += `C${s(d)},${s(f)} ${s(p)},${s(m)} ${s(a)},${s(o)} `;
110
- }
111
- }
112
- return n.trim();
113
- }
114
- function f(e) {
115
- let t = "", n = !1, r = (e) => e.v != null && Number.isFinite(e.x) && Number.isFinite(e.y);
116
- for (let i = 0; i < e.length; i++) {
117
- let a = e[i];
118
- if (!r(a)) continue;
119
- let o = `${s(a.x)},${s(a.y)}`;
120
- if (!n) t += o, n = !0;
121
- else {
122
- let n = e[i - 1], a = r(n) ? "L" : "M";
123
- t += `${a}${o}`;
124
- }
125
- t += " ";
126
- }
127
- return t.trim();
128
- }
129
- function p(e) {
130
- let t = [], n = [];
131
- for (let r of e) !r || r.v == null || Number.isNaN(r.x) || Number.isNaN(r.y) ? (n.length && t.push(n), n = []) : n.push(r);
132
- return n.length && t.push(n), t;
133
- }
134
- function m(e, t) {
135
- if (!e[0]) return [
136
- -10,
137
- -10,
138
- "",
139
- -10,
140
- -10
141
- ].toString();
142
- let n = p(e);
143
- return n.length ? n.map((e) => {
144
- let n = {
145
- x: e[0].x,
146
- y: t
147
- }, r = {
148
- x: e.at(-1)?.x,
149
- y: t
150
- }, i = [];
151
- return e.forEach((e) => {
152
- i.push(`${e.x},${e.y} `);
153
- }), [
154
- n.x,
155
- n.y,
156
- ...i,
157
- r.x,
158
- r.y
159
- ].toString();
160
- }).join(";") : "";
161
- }
162
- function h(e, t, n = !1, r = !0) {
163
- function i(e) {
164
- let t = [], n = [];
165
- for (let r of e) !r || r.v == null || Number.isNaN(r.x) || Number.isNaN(r.y) ? (n.length > 1 && t.push(n), n = []) : n.push(r);
166
- return n.length > 1 && t.push(n), t;
167
- }
168
- return (n ? i(e) : [e]).map((e) => {
169
- if (e.length < 2) return "";
170
- let n = e.length - 1, i = [], a = [], o = [], s = [];
171
- for (let t = 0; t < n; t += 1) i[t] = e[t + 1].x - e[t].x, a[t] = e[t + 1].y - e[t].y, o[t] = a[t] / i[t];
172
- s[0] = o[0], s[n] = o[n - 1];
173
- for (let e = 1; e < n; e += 1) if (o[e - 1] * o[e] <= 0) s[e] = 0;
174
- else {
175
- let t = 2 * o[e - 1] * o[e] / (o[e - 1] + o[e]);
176
- s[e] = t;
177
- }
178
- let c = `M${e[0].x},${t}`;
179
- c += ` L${e[0].x},${e[0].y}`;
180
- for (let t = 0; t < n; t += 1) {
181
- let n = e[t].x, r = e[t].y, i = e[t + 1].x, a = e[t + 1].y, o = s[t], l = s[t + 1], u = n + (i - n) / 3, d = r + o * (i - n) / 3, f = i - (i - n) / 3, p = a - l * (i - n) / 3;
182
- c += ` C${u},${d} ${f},${p} ${i},${a}`;
183
- }
184
- return c += ` L${e[n].x},${t} ${r ? "Z" : ""}`, c;
185
- }).filter(Boolean);
186
- }
187
- function ee(e, n = t, r) {
188
- e.style.opacity = "1";
189
- let i = e.getTotalLength();
190
- e.style.strokeDasharray = String(i), e.style.strokeDashoffset = String(i), e.getBoundingClientRect(), e.style.transition = `stroke-dashoffset ${n}ms ease-in-out`, e.style.strokeDashoffset = "0", e.addEventListener("transitionend", function t() {
191
- e.style.transition = "", e.removeEventListener("transitionend", t), r && r();
192
- });
193
- }
194
- function te(e, n, r = t) {
195
- n.style.opacity = "1";
196
- let i = n.getBBox(), a = i.width, o = document.createElementNS("http://www.w3.org/2000/svg", "clipPath"), s = "clip-" + Math.random().toString(36).substr(2, 9);
197
- o.setAttribute("id", s);
198
- let c = document.createElementNS("http://www.w3.org/2000/svg", "rect");
199
- c.setAttribute("x", i.x.toString()), c.setAttribute("y", i.y.toString()), c.setAttribute("width", "0"), c.setAttribute("height", i.height.toString()), o.appendChild(c);
200
- let l = e.querySelector("defs");
201
- l || (l = document.createElementNS("http://www.w3.org/2000/svg", "defs"), e.insertBefore(l, e.firstChild)), l.appendChild(o), n.setAttribute("clip-path", `url(#${s})`), c.style.transition = `width ${r}ms ease-out`, c.getBoundingClientRect(), c.setAttribute("width", a.toString()), c.addEventListener("transitionend", function e() {
202
- n.removeAttribute("clip-path"), o.parentNode && o.parentNode.removeChild(o), c.removeEventListener("transitionend", e);
203
- });
204
- }
205
- //#endregion
206
- //#region src/lib.ts
207
- function g() {
208
- return document.querySelectorAll(".tiny-spark");
209
- }
210
- function _(e, t) {
211
- return Object.keys(e.dataset).includes(t);
212
- }
213
- function v(e, t, n) {
214
- return _(e, t) ? e.dataset[t] : n;
215
- }
216
- function ne(e) {
217
- if (!e) return {
218
- color: "#1A1A1A",
219
- backgroundColor: "#FFFFFF"
220
- };
221
- let t = window.getComputedStyle(e), n = t.getPropertyValue("color") || "#1A1A1A", r = t.getPropertyValue("background-color"), i = t.getPropertyValue("background");
222
- return {
223
- color: n,
224
- backgroundColor: r || i || "#FFFFFF"
225
- };
226
- }
227
- function y() {
228
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(e) {
229
- let t = Math.random() * 16 | 0;
230
- return (e == "x" ? t : t & 3 | 8).toString(16);
231
- });
232
- }
233
- function b(e) {
234
- let t = e.getAttribute(i.SET);
235
- if (!t) return [];
236
- let n = t.replace(/,(?=,)/g, ",null").replace(/\[,/g, "[null,").replace(/,\]/g, ",null]");
237
- try {
238
- let e = JSON.parse(n);
239
- return Array.isArray(e) && e.every((e) => typeof e == "number" || [null, void 0].includes(e)) ? e : (console.warn("data-set is not an array of numbers."), []);
240
- } catch (e) {
241
- return console.error("Error parsing data-set:", e), [];
242
- }
243
- }
244
- function re(e, t) {
245
- return t <= 1 ? "0%" : `${e * 100 / (t - 1)}%`;
246
- }
247
- function ie(e) {
248
- let t = e.getAttribute(i.DATES);
249
- if (!t) return [];
250
- try {
251
- let e = JSON.parse(t.replaceAll("'", "\""));
252
- return Array.isArray(e) && e.every((e) => typeof e == "string") ? e : (console.warn("data-dates is not an array of strings"), []);
253
- } catch (e) {
254
- return console.error("Error parsing data-dates", e), [];
255
- }
256
- }
257
- function ae(e) {
258
- let t = e.getAttribute(i.TEMPERATURE_COLORS);
259
- if (!t) return [];
260
- try {
261
- let e = JSON.parse(t.replaceAll("'", "\""));
262
- return Array.isArray(e) && e.every((e) => typeof e == "string") ? e : (console.warn("data-temperature-colors is not an array of strings"), []);
263
- } catch (e) {
264
- return console.error("Error parsing data-temperature-colors", e), [];
265
- }
266
- }
267
- function x(e) {
268
- return {
269
- min: Math.min(...e),
270
- max: Math.max(...e)
271
- };
272
- }
273
- function S() {
274
- return new Promise((e) => setTimeout(e, 0));
275
- }
276
- function C(e, t) {
277
- let n = String(v(e, r.NUMBER_LOCALE, navigator.language || "en-US")), i = Number(String(v(e, r.NUMBER_ROUNDING, 0)));
278
- return t.toLocaleString(n, {
279
- useGrouping: !0,
280
- minimumFractionDigits: i,
281
- maximumFractionDigits: i
282
- });
283
- }
284
- function w(e, t, n) {
285
- if (!e.createSVGPoint || !e.getScreenCTM) return console.error("Your browser does not support SVG coordinate transformation."), {
286
- x: 0,
287
- y: 0
288
- };
289
- let r = e.getScreenCTM();
290
- if (!r) return console.error("Cannot obtain the screen CTM."), {
291
- x: 0,
292
- y: 0
293
- };
294
- let i = e.createSVGPoint();
295
- i.x = t, i.y = n;
296
- let a = i.matrixTransform(r);
297
- return {
298
- x: a.x,
299
- y: a.y
300
- };
301
- }
302
- var T = {};
303
- function oe(e, t, i, a, o) {
304
- let s = T[a];
305
- if (!o) {
306
- s && (cancelAnimationFrame(s.frameId), s.frameId = null, s.tool.style.opacity = "0");
307
- return;
308
- }
309
- let c = t.dataset.type === n.BAR, { x: l, y: u } = w(e, i.x, c && !i.isPositive ? i.bar.y : i.y);
310
- if (!s) {
311
- let e = document.createElement("div");
312
- e.classList.add("tiny-spark-tooltip"), e.setAttribute("id", `tooltip_${a}`), e.setAttribute("role", "tooltip"), e.setAttribute("aria-live", "polite"), e.style.position = "fixed", e.style.pointerEvents = "none", e.style.opacity = "0", e.style.willChange = "top, left", document.body.appendChild(e), s = T[a] = {
313
- targetX: 0,
314
- targetY: 0,
315
- displayX: 0,
316
- displayY: 0,
317
- frameId: null,
318
- tool: e,
319
- width: 0,
320
- height: 0,
321
- hasSnapped: !1
322
- };
323
- }
324
- s.tool.setAttribute("aria-hidden", "false"), s.tool.innerHTML = `
325
- <div class="tiny-spark-tooltip-content">
326
- ${i.d ? `${i.d}: ` : ""}${[null, void 0].includes(i.v) ? "-" : C(t, Number(i.v))}
327
- </div>
328
- `;
329
- let { width: d, height: f } = s.tool.getBoundingClientRect();
330
- s.width = d, s.height = f;
331
- let p = Number(v(t, r.PLOT_RADIUS, 3));
332
- if (s.targetX = l - s.width / 2, s.targetY = u - s.height - p * 1.5, !s.hasSnapped) {
333
- s.displayX = s.targetX, s.displayY = s.targetY, s.tool.style.left = `${s.displayX}px`, s.tool.style.top = `${s.displayY}px`, s.tool.style.opacity = "1", s.hasSnapped = !0;
334
- return;
335
- }
336
- let m = Number(v(t, r.TOOLTIP_SMOOTHING, 1)) / 10;
337
- function h() {
338
- s.displayX += (s.targetX - s.displayX) * m, s.displayY += (s.targetY - s.displayY) * m, s.tool.style.left = `${Math.round(s.displayX)}px`, s.tool.style.top = `${Math.round(s.displayY)}px`, s.tool.style.opacity = "1", s.frameId = requestAnimationFrame(h);
339
- }
340
- s.frameId ?? h();
341
- }
342
- function E({ id: t, colorStart: n, colorEnd: r, opacityStart: i, opacityEnd: a }) {
343
- let o = document.createElementNS(e, "linearGradient");
344
- o.setAttribute("id", t), o.setAttribute("x1", "0"), o.setAttribute("x2", "0"), o.setAttribute("y1", "0"), o.setAttribute("y2", "1");
345
- let s = document.createElementNS(e, "stop");
346
- s.setAttribute("offset", "0%"), s.setAttribute("stop-color", n), s.setAttribute("stop-opacity", String(i));
347
- let c = document.createElementNS(e, "stop");
348
- return c.setAttribute("offset", "100%"), c.setAttribute("stop-color", r), c.setAttribute("stop-opacity", String(a)), [s, c].forEach((e) => {
349
- o.appendChild(e);
350
- }), o;
351
- }
352
- function se(e) {
353
- if (e.length <= 1) return !0;
354
- let t = e[0];
355
- for (let n = 1; n < e.length; n += 1) if (e[n] !== t) return !1;
356
- return !0;
357
- }
358
- function ce(e) {
359
- e.innerHTML = "";
360
- }
361
- function D(n, i) {
362
- let a = n.dataset.type && n.dataset.type === "bar", s = i;
363
- ce(n);
364
- let { svg: u, svgId: p, width: g, height: _, viewBox: w } = o(n), { color: D, backgroundColor: O } = ne(n), k = {
365
- T: 12,
366
- R: 12,
367
- B: 12,
368
- L: 12
369
- }, A = y(), j = String(v(n, r.SHOW_LAST_VALUE, "false")) === "true", M = {
370
- left: k.L,
371
- top: k.T,
372
- width: g - k.L - k.R,
373
- height: _ - k.T - k.B,
374
- bottom: _ - k.B,
375
- right: g - k.R
376
- }, N = b(n), { min: P } = x(N), F = N.map((e) => [null, void 0].includes(e) ? e : e + (P < 0 ? Math.abs(P) : 0)), { max: I } = x(F), L = M.width / (N.length - 1) == Infinity ? M.width : M.width / (N.length - 1);
377
- if (a) {
378
- let [e, t, n, r] = w.split(" ");
379
- u.setAttribute("viewBox", `${Number(e) - L / 2} ${t} ${Number(n) + L} ${r}`);
380
- }
381
- let R = !N.some((e) => e >= 0), le = ie(n), z = F.map((e, t) => {
382
- let n = {
383
- w: F.length === 1 ? L / 2 : 0,
384
- h: F.length === 1 ? M.height / 2 : 0
385
- }, r = M.left + L * t + n.w, i = (1 - (e || 0) / I) * M.height + n.h + k.T, a = (1 - (P < 0 ? Math.abs(P) : 0) / I) * M.height + k.T + n.h, o = N[t] >= 0;
386
- return {
387
- y: R && N.length === 1 ? M.top + M.height / 2 : i,
388
- x: r,
389
- v: N[t],
390
- d: le[t] || null,
391
- isPositive: o,
392
- bar: {
393
- x: r - L / 2,
394
- y: N.length === 1 ? M.top : o ? i : R ? M.top : a,
395
- h: N.length === 1 ? M.height : o ? a - i : R && N.length === 0 ? M.height : isNaN(i - a) ? 0 : i - a,
396
- w: L
397
- }
398
- };
399
- });
400
- function B() {
401
- let t = document.createElementNS(e, "path");
402
- return t.classList.add("tiny-spark-line-area"), t;
403
- }
404
- function ue(t) {
405
- let i = document.createElementNS(e, "defs");
406
- return i.appendChild(E({
407
- id: t,
408
- colorStart: String(v(n, r.GRADIENT_FROM, "#FFFFFF")),
409
- colorEnd: String(v(n, r.GRADIENT_TO, "#FFFFFF")),
410
- opacityStart: Math.max(0, Math.min(1, Number(v(n, r.GRADIENT_FROM_OPACITY, 1)))),
411
- opacityEnd: Math.max(0, Math.min(1, Number(v(n, r.GRADIENT_TO_OPACITY, 1))))
412
- })), i;
413
- }
414
- function de(t) {
415
- let i = document.createElementNS(e, "defs");
416
- return i.appendChild(E({
417
- id: `pos_${t}`,
418
- colorStart: String(v(n, r.GRADIENT_FROM, "#FFFFFF")),
419
- colorEnd: String(v(n, r.GRADIENT_TO, "#FFFFFF")),
420
- opacityStart: Math.max(0, Math.min(1, Number(v(n, r.GRADIENT_FROM_OPACITY, 1)))),
421
- opacityEnd: Math.max(0, Math.min(1, Number(v(n, r.GRADIENT_TO_OPACITY, 1))))
422
- })), i.appendChild(E({
423
- id: `neg_${t}`,
424
- colorStart: String(v(n, r.GRADIENT_TO, "#FFFFFF")),
425
- colorEnd: String(v(n, r.GRADIENT_FROM, "#FFFFFF")),
426
- opacityStart: Math.max(0, Math.min(1, Number(v(n, r.GRADIENT_TO_OPACITY, 1)))),
427
- opacityEnd: Math.max(0, Math.min(1, Number(v(n, r.GRADIENT_FROM_OPACITY, 1))))
428
- })), i;
429
- }
430
- let V = [...z].map((e) => [
431
- null,
432
- void 0,
433
- Infinity,
434
- -Infinity,
435
- NaN,
436
- "NaN"
437
- ].includes(e.v) ? {
438
- ...e,
439
- v: null
440
- } : e), H = n.getAttribute("data-animation"), U = document.createElementNS(e, "path");
441
- U.classList.add("tiny-spark-line-path");
442
- let W = B(), G = [], K = !!v(n, r.GRADIENT_FROM, "") && !!v(n, r.GRADIENT_TO, ""), q = y();
443
- if (!a) {
444
- !n.dataset.curve || n.dataset.curve === "true" ? !n.dataset.cutNull || n.dataset.cutNull === "false" ? U.setAttribute("d", `M ${l(V)}`) : U.setAttribute("d", `M ${d(V)}`) : !n.dataset.cutNull || n.dataset.cutNull === "false" ? U.setAttribute("d", `M ${c(V)}`) : U.setAttribute("d", `M ${f(V)}`), U.setAttribute("fill", "none");
445
- let t = ae(n);
446
- if (t.length && !se(V.map((e) => e.y))) {
447
- let n = y(), r = document.createElementNS(e, "defs"), i = document.createElementNS(e, "linearGradient");
448
- i.setAttribute("gradientTransform", "rotate(90)"), i.setAttribute("id", n), t.forEach((n, r) => {
449
- let a = document.createElementNS(e, "stop");
450
- a.setAttribute("offset", re(r, t.length)), a.setAttribute("stop-color", n), i.appendChild(a);
451
- }), r.appendChild(i), u.prepend(r), U.setAttribute("stroke", `url(#${n})`);
452
- } else U.setAttribute("stroke", String(v(n, r.LINE_COLOR, D)));
453
- U.setAttribute("stroke-width", String(v(n, r.LINE_THICKNESS, 2))), U.setAttribute("stroke-linecap", "round"), H === "true" && s && (U.style.opacity = "0", W.style.opacity = "0"), K && u.appendChild(ue(q)), z.length && (!n.dataset.curve || n.dataset.curve === "true" ? !n.dataset.cutNull || n.dataset.cutNull === "false" ? W.setAttribute("d", `M ${V[0].x},${M.bottom} ${l(V)} L ${V.at(-1).x},${M.bottom} Z`) : h(V, M.bottom, !0, !0).forEach((e) => {
454
- let t = B();
455
- t.setAttribute("d", e), K ? t.setAttribute("fill", `url(#${q})`) : t.setAttribute("fill", String(v(n, r.AREA_COLOR, "transparent"))), G.push(t);
456
- }) : !n.dataset.cutNull || n.dataset.cutNull === "false" ? W.setAttribute("d", `M ${V[0].x},${M.bottom} ${c(V)} L ${V.at(-1).x},${M.bottom} Z`) : m(V, M.bottom).split(";").forEach((e) => {
457
- let t = B();
458
- t.setAttribute("d", `M ${e} Z`), K ? t.setAttribute("fill", `url(#${q})`) : t.setAttribute("fill", String(v(n, r.AREA_COLOR, "transparent"))), G.push(t);
459
- })), K ? W.setAttribute("fill", `url(#${q})`) : W.setAttribute("fill", String(v(n, r.AREA_COLOR, "transparent"))), z.length > 1 && (G.length ? G.forEach((e) => {
460
- u.appendChild(e);
461
- }) : u.appendChild(W), u.appendChild(U));
462
- }
463
- let J = [];
464
- z.forEach((t, i) => {
465
- let a = document.createElementNS(e, "line");
466
- a.classList.add("tiny-spark-indicator"), a.setAttribute("id", `indicator_${p}_${i}`), a.setAttribute("x1", String(M.left + (z.length === 1 ? M.width / 2 : i * L))), a.setAttribute("x2", String(M.left + (z.length === 1 ? M.width / 2 : i * L))), a.setAttribute("y1", String(M.top)), a.setAttribute("y2", String(M.bottom)), a.setAttribute("stroke", String(v(n, r.INDICATOR_COLOR, "#1A1A1A"))), a.setAttribute("stroke-width", String(v(n, r.INDICATOR_WIDTH, "1"))), a.setAttribute("stroke-linecap", "round"), a.style.pointerEvents = "none", a.style.opacity = "0", J.push(a), u.appendChild(a);
467
- });
468
- let Y = [], X = [], fe = Number(String(v(n, r.PLOT_RADIUS, 0))) > 0, pe = !String(v(n, r.HIDE_PLOTS_ABOVE, "")) || z.length <= Number(String(v(n, r.HIDE_PLOTS_ABOVE, 0))), Z = fe && pe, Q = document.createElementNS(e, "g");
469
- a && (K && u.appendChild(de(q)), z.forEach(({ bar: i, v: a }, o) => {
470
- if (![null, void 0].includes(a)) {
471
- let s = document.createElementNS(e, "rect");
472
- s.classList.add("tiny-spark-datapoint-bar"), s.setAttribute("x", String(i.x)), s.setAttribute("y", String(i.y)), s.setAttribute("width", String(i.w)), s.setAttribute("height", String(i.h)), K ? a >= 0 ? s.setAttribute("fill", `url(#pos_${q})`) : s.setAttribute("fill", `url(#neg_${q})`) : s.setAttribute("fill", String(v(n, r.PLOT_COLOR, String(v(n, "lineColor", D))))), s.style.opacity = z.length === 1 ? "1" : "0", s.style.transition = `opacity ${o * (t * 2 / z.length)}ms ease-in`, X.push(s), Q.appendChild(s);
473
- }
474
- }), u.appendChild(Q)), fe && !a && (z.forEach(({ x: i, y: a, v: o }, s) => {
475
- if (![null, void 0].includes(o)) {
476
- let o = document.createElementNS(e, "circle");
477
- o.classList.add("tiny-spark-datapoint-circle"), o.classList.add(`circle-${p}`), o.setAttribute("id", `circle_${p}_${s}`), o.setAttribute("cx", String(i || 0)), o.setAttribute("cy", String(a || 0)), o.setAttribute("r", String(v(n, r.PLOT_RADIUS, 3))), o.setAttribute("fill", String(v(n, r.PLOT_COLOR, String(v(n, "lineColor", D))))), o.setAttribute("stroke", O), o.style.opacity = z.length === 1 ? "1" : "0", o.style.transition = `opacity ${s * (t * 2 / z.length)}ms ease-in`, o.style.pointerEvents = "none", Y.push(o), Z && Q.appendChild(o);
478
- }
479
- }), u.appendChild(Q));
480
- let $ = null;
481
- if (j && z.length && z.at(-1)) {
482
- let t = Number(v(n, r.LAST_VALUE_FONT_SIZE, 12));
483
- $ = document.createElementNS(e, "text"), $.classList.add("tiny-spark-last-value"), $.setAttribute("id", A), a ? ($.setAttribute("x", String(z.at(-1).x + Number(v(n, r.LINE_THICKNESS, 2)))), $.setAttribute("y", z.at(-1)?.isPositive ? String(z.at(-1).y - t / 3) : String(z.at(-1).bar.y + z.at(-1).bar.h + t)), $.setAttribute("text-anchor", "middle")) : ($.setAttribute("x", String(z.at(-1).x + 6 + Number(v(n, r.LINE_THICKNESS, 2)))), $.setAttribute("y", String(z.at(-1).y + t / 3)), $.setAttribute("text-anchor", "start")), $.setAttribute("font-size", String(t) + "px"), $.setAttribute("fill", String(v(n, r.LAST_VALUE_COLOR, String(v(n, r.INDICATOR_COLOR, "#1A1A1A"))))), $.innerHTML = C(n, Number(z.at(-1).v)), $.style.opacity = z.length === 1 ? "1" : "0", u.appendChild($);
484
- }
485
- let me = document.createElementNS(e, "g");
486
- z.forEach((t, i) => {
487
- let a = Y[i], o = document.createElementNS(e, "rect");
488
- o.classList.add("tiny-spark-tooltip-trap"), o.setAttribute("x", `${z.length === 1 ? 0 : M.left + i * L - L / 2}`), o.setAttribute("y", `${M.top}`), o.setAttribute("height", `${M.height}`), o.setAttribute("width", `${L}`), o.setAttribute("fill", "transparent"), o.setAttribute("aria-describedby", `tooltip_${p}`), o.addEventListener("mouseenter", () => {
489
- oe(u, n, t, p, !0), Z ? document.getElementById(`circle_${p}_${i}`)?.setAttribute("r", String(Number(v(n, r.PLOT_RADIUS, 3)) * 1.5)) : u.appendChild(a), J[i].style.opacity = "1", j && $ && (i === z.length - 1 ? $.style.opacity = "0" : $.style.opacity = "1");
490
- }), o.addEventListener("mouseout", () => {
491
- oe(u, n, t, p, !1), Z ? document.getElementById(`circle_${p}_${i}`)?.setAttribute("r", String(Number(v(n, r.PLOT_RADIUS, 3)))) : a.remove(), J.forEach((e) => e.style.opacity = "0"), j && $ && ($.style.opacity = "1");
492
- }), me.appendChild(o);
493
- }), u.appendChild(me), H === "true" && s ? S().then(() => {
494
- Y.forEach((e) => {
495
- e.style.opacity = "1";
496
- }), X.forEach((e) => {
497
- e.style.opacity = "1";
498
- }), ee(U, t, () => {
499
- $ && ($.style.opacity = "1");
500
- }), te(u, W);
501
- }) : (Y.forEach((e) => {
502
- e.style.opacity = "1";
503
- }), X.forEach((e) => {
504
- e.style.opacity = "1";
505
- }), $ && ($.style.opacity = "1")), n.appendChild(u), n.addEventListener("mouseleave", () => {
506
- let e = T[p];
507
- e && (cancelAnimationFrame(e.frameId), e.frameId = null, e.tool.style.opacity = "0", e.hasSnapped = !1);
508
- });
509
- }
510
- //#endregion
511
- //#region src/index.ts
512
- function O() {
513
- let e = g();
514
- e.length && Array.from(e).forEach((e) => {
515
- if (!e.dataset.id) {
516
- let t = y();
517
- e.setAttribute("data-id", t);
518
- }
519
- let t = e;
520
- A(t), t.__renderCount = 0, k(t), S().then(() => {
521
- let e = new ResizeObserver((e) => {
522
- e.forEach(() => k(t));
523
- });
524
- t.parentElement && e.observe(t.parentElement), new MutationObserver((e) => {
525
- for (let n of e) if (n.type === "attributes" && n.attributeName && Object.values(i).includes(n.attributeName)) {
526
- k(t);
527
- break;
528
- }
529
- }).observe(t, { attributes: !0 });
530
- });
531
- });
532
- }
533
- function k(e) {
534
- _(e, "set") && D(e, e.__renderCount < 2), e.__renderCount += 1;
535
- }
536
- function A(e) {
537
- e.dataset.set || console.error("Tiny-spark exception:\n\n[data-set] data attribute is missing.\nProvide an array of numbers, for example:\n\n data-set=\"[1, 2, 3]\"");
538
- }
539
- function j(e) {
540
- return JSON.stringify(e);
541
- }
542
- //#endregion
543
- export { O as render, j as tinyFormat };
1
+ var e=`http://www.w3.org/2000/svg`,t=1e3;function n(t,n){let r={width:300,height:100},{width:i,height:a}=t.parentElement?.getBoundingClientRect()??r,o=String(_(t,`showLastValue`,`false`))===`true`,s=0;if(!(t.dataset.type&&t.dataset.type===`bar`)&&o&&n!=null){let e=Number(String(_(t,`numberRounding`,0)));s=6+(t.dataset.numberStyle?se(t,n):n.toFixed(e)).length*(Number(_(t,`lastValueFontSize`,12))/2)}let c=`0 0 ${(i||r.width)+s} ${a||r.height}`,l=document.createElementNS(e,`svg`),u=t.dataset.id;l.id=u,l.setAttribute(`viewBox`,c),l.style.width=`100%`,l.style.height=`100%`;let d=document.createElementNS(e,`desc`);return d.setAttribute(`aria-hidden`,`true`),d.innerHTML=`Composed with tiny-spark v1.3.0`,l.appendChild(d),{svg:l,svgId:u,width:i||r.width,height:a||r.height,viewBox:c}}function r(e,t=0){return isNaN(e)?t:e}function i(e){let t=[];for(let n=0;n<e.length;n+=1)t.push(`${r(e[n].x)},${r(e[n].y)} `);return t.join(` `).trim()}function a(e,t,n){let r=e.length-1,i=[],a=[];for(let t=0;t<r;t+=1)i[t]=(e[t+1].y-e[t].y)/(e[t+1].x-e[t].x);a[0]=i[0],a[r]=i[r-1];for(let e=1;e<r;e+=1){let t=i[e-1],n=i[e];a[e]=t*n<=0?0:2*t*n/(t+n)}let o=``;for(let i=0;i<r;i+=1){let{x:r,y:s}=e[i],{x:c,y:l}=e[i+1],u=c-r,d=r+u/3,f=s+a[i]*u/3,p=c-u/3,m=l-a[i+1]*u/3;o+=` ${t}${n(d)},${n(f)} ${n(p)},${n(m)} ${n(c)},${n(l)}`}return o}function o(e){if(e.length<2)return`0,0`;let{x:t,y:n}=e[0];return`${r(t)},${r(n)}${a(e,`C `,r)}`}function s(e){let t=[],n=[];for(let r of e)r.v==null||Number.isNaN(r.x)||Number.isNaN(r.y)?(n.length>1&&t.push(n),n=[]):n.push(r);return n.length>1&&t.push(n),t}function c(e){return s(e).map(e=>{let{x:t,y:n}=e[0];return`${r(t)},${r(n)}${a(e,`C`,r)}`}).join(` M`)}function l(e){let t=``,n=!1,i=e=>e.v!=null&&Number.isFinite(e.x)&&Number.isFinite(e.y);for(let a=0;a<e.length;a++){let o=e[a];if(!i(o))continue;let s=`${r(o.x)},${r(o.y)}`;if(!n)t+=s,n=!0;else{let n=e[a-1],r=i(n)?`L`:`M`;t+=`${r}${s}`}t+=` `}return t.trim()}function u(e){let t=[],n=[];for(let r of e)!r||r.v==null||Number.isNaN(r.x)||Number.isNaN(r.y)?(n.length&&t.push(n),n=[]):n.push(r);return n.length&&t.push(n),t}function d(e,t){if(!e[0])return[-10,-10,``,-10,-10].toString();let n=u(e);return n.length?n.map(e=>{let n={x:e[0].x,y:t},r={x:e.at(-1)?.x,y:t},i=[];return e.forEach(e=>{i.push(`${e.x},${e.y} `)}),[n.x,n.y,...i,r.x,r.y].toString()}).join(`;`):``}function f(e,t,n=!1,r=!0){function i(e){let t=[],n=[];for(let r of e)!r||r.v==null||Number.isNaN(r.x)||Number.isNaN(r.y)?(n.length>1&&t.push(n),n=[]):n.push(r);return n.length>1&&t.push(n),t}return(n?i(e):[e]).map(e=>{if(e.length<2)return``;let{x:n,y:i}=e[0];return`M${n},${t} L${n},${i}${a(e,`C`,e=>e)} L${e.at(-1).x},${t} ${r?`Z`:``}`}).filter(Boolean)}function p(e,n=t,r){e.style.opacity=`1`;let i=e.getTotalLength();e.style.strokeDasharray=String(i),e.style.strokeDashoffset=String(i),e.getBoundingClientRect(),e.style.transition=`stroke-dashoffset ${n}ms ease-in-out`,e.style.strokeDashoffset=`0`,e.addEventListener(`transitionend`,function t(){e.style.transition=``,e.removeEventListener(`transitionend`,t),r&&r()})}function m(e,n,r=t){n.style.opacity=`1`;let i=n.getBBox(),a=i.width,o=document.createElementNS(`http://www.w3.org/2000/svg`,`clipPath`),s=`clip-`+Math.random().toString(36).substr(2,9);o.setAttribute(`id`,s);let c=document.createElementNS(`http://www.w3.org/2000/svg`,`rect`);c.setAttribute(`x`,i.x.toString()),c.setAttribute(`y`,i.y.toString()),c.setAttribute(`width`,`0`),c.setAttribute(`height`,i.height.toString()),o.appendChild(c);let l=e.querySelector(`defs`);l||(l=document.createElementNS(`http://www.w3.org/2000/svg`,`defs`),e.insertBefore(l,e.firstChild)),l.appendChild(o),n.setAttribute(`clip-path`,`url(#${s})`),c.style.transition=`width ${r}ms ease-out`,c.getBoundingClientRect(),c.setAttribute(`width`,a.toString()),c.addEventListener(`transitionend`,function e(){n.removeAttribute(`clip-path`),o.parentNode&&o.parentNode.removeChild(o),c.removeEventListener(`transitionend`,e)})}function h(e){let t=Array.from(e.querySelectorAll(`.tiny-spark`));return e.nodeType===1&&e.matches(`.tiny-spark`)&&t.unshift(e),t}function g(e,t){return Object.keys(e.dataset).includes(t)}function _(e,t,n){return g(e,t)?e.dataset[t]:n}function ee(e){if(!e)return{color:`#1A1A1A`,backgroundColor:`#FFFFFF`};let t=window.getComputedStyle(e),n=t.getPropertyValue(`color`)||`#1A1A1A`,r=t.getPropertyValue(`background-color`),i=t.getPropertyValue(`background`);return{color:n,backgroundColor:r||i||`#FFFFFF`}}function v(){return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e==`x`?t:t&3|8).toString(16)})}function te(e){let t=e.getAttribute(`data-set`);if(!t)return[];let n=t.replace(/,(?=,)/g,`,null`).replace(/\[,/g,`[null,`).replace(/,\]/g,`,null]`);try{let e=JSON.parse(n);return Array.isArray(e)&&e.every(e=>typeof e==`number`||[null,void 0].includes(e))?e:(console.warn(`data-set is not an array of numbers.`),[])}catch(e){return console.error(`Error parsing data-set:`,e),[]}}function ne(e,t){return t<=1?`0%`:`${e*100/(t-1)}%`}function re(e){let t=e.getAttribute(`data-dates`);if(!t)return[];try{let e;try{e=JSON.parse(t)}catch{e=JSON.parse(t.replaceAll(`'`,`"`))}return Array.isArray(e)&&e.every(e=>e===null||typeof e==`string`)?e:(console.warn(`data-dates is not an array of strings or nulls`),[])}catch(e){return console.error(`Error parsing data-dates`,e),[]}}function ie(e){let t=e.getAttribute(`data-temperature-colors`);if(!t)return[];try{let e=JSON.parse(t.replaceAll(`'`,`"`));return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:(console.warn(`data-temperature-colors is not an array of strings`),[])}catch(e){return console.error(`Error parsing data-temperature-colors`,e),[]}}function ae(e){return{min:Math.min(...e),max:Math.max(...e)}}function oe(){return new Promise(e=>setTimeout(e,0))}function se(e,t){let n=String(_(e,`numberLocale`,navigator.language||`en-US`)),r=Number(String(_(e,`numberRounding`,0))),i={useGrouping:!0,minimumFractionDigits:r,maximumFractionDigits:r},{numberStyle:a,numberCurrency:o,numberUnit:s}=e.dataset;if(a===`currency`||a===`percent`||a===`unit`)try{return t.toLocaleString(n,{...i,style:a,currency:o,unit:s})}catch{}return t.toLocaleString(n,i)}function y(e,t,n){if(!e.createSVGPoint||!e.getScreenCTM)return console.error(`Your browser does not support SVG coordinate transformation.`),{x:0,y:0};let r=e.getScreenCTM();if(!r)return console.error(`Cannot obtain the screen CTM.`),{x:0,y:0};let i=e.createSVGPoint();i.x=t,i.y=n;let a=i.matrixTransform(r);return{x:a.x,y:a.y}}var b=new WeakMap;function x(e){e.frameId!==null&&cancelAnimationFrame(e.frameId),e.frameId=null,e.tool.style.opacity=`0`,e.tool.setAttribute(`aria-hidden`,`true`)}function ce(e,t,n,r){let i=b.get(t),a=t.dataset.type===`bar`,{x:o,y:s}=y(e,n.x,a&&!n.isPositive?n.bar.y:n.y);if(!i){let e=document.createElement(`div`);e.classList.add(`tiny-spark-tooltip`),e.setAttribute(`role`,`tooltip`),e.setAttribute(`aria-live`,`polite`),e.style.position=`fixed`,e.style.pointerEvents=`none`,e.style.opacity=`0`,e.style.willChange=`top, left`;let n=document.createElement(`div`);n.classList.add(`tiny-spark-tooltip-content`),e.appendChild(n),t.ownerDocument.body.appendChild(e);let r={targetX:0,targetY:0,displayX:0,displayY:0,frameId:null,tool:e,content:n,width:0,height:0,hasSnapped:!1};b.set(t,r),i=r}let c=i;c.tool.id=`tooltip_${r}`,c.tool.setAttribute(`aria-hidden`,`false`);let l=n.v==null?`-`:se(t,Number(n.v));c.content.textContent=n.d?`${n.d}: ${l}`:l;let{width:u,height:d}=c.tool.getBoundingClientRect();c.width=u,c.height=d;let f=Number(_(t,`plotRadius`,3));if(c.targetX=o-c.width/2,c.targetY=s-c.height-f*1.5,!c.hasSnapped){c.displayX=c.targetX,c.displayY=c.targetY,c.tool.style.left=`${c.displayX}px`,c.tool.style.top=`${c.displayY}px`,c.tool.style.opacity=`1`,c.hasSnapped=!0;return}let p=Math.min(1,Math.max(0,Number(_(t,`tooltipSmoothing`,1))/10))||1;function m(){c.displayX+=(c.targetX-c.displayX)*p,c.displayY+=(c.targetY-c.displayY)*p;let e=Math.abs(c.targetX-c.displayX)<=.5&&Math.abs(c.targetY-c.displayY)<=.5;e&&(c.displayX=c.targetX,c.displayY=c.targetY),c.tool.style.left=`${c.displayX}px`,c.tool.style.top=`${c.displayY}px`,c.tool.style.opacity=`1`,c.frameId=e?null:requestAnimationFrame(m)}c.frameId??m()}function S({id:t,colorStart:n,colorEnd:r,opacityStart:i,opacityEnd:a}){let o=document.createElementNS(e,`linearGradient`);o.setAttribute(`id`,t),o.setAttribute(`x1`,`0`),o.setAttribute(`x2`,`0`),o.setAttribute(`y1`,`0`),o.setAttribute(`y2`,`1`);let s=document.createElementNS(e,`stop`);s.setAttribute(`offset`,`0%`),s.setAttribute(`stop-color`,n),s.setAttribute(`stop-opacity`,String(i));let c=document.createElementNS(e,`stop`);return c.setAttribute(`offset`,`100%`),c.setAttribute(`stop-color`,r),c.setAttribute(`stop-opacity`,String(a)),[s,c].forEach(e=>{o.appendChild(e)}),o}function le(e){if(e.length<=1)return!0;let t=e[0];for(let n=1;n<e.length;n+=1)if(e[n]!==t)return!1;return!0}var C=new WeakMap;function w(e){let t=C.get(e);t?.events.abort(),t?.svg.remove(),t?.ownsTabIndex&&e.getAttribute(`tabindex`)===`0`&&e.removeAttribute(`tabindex`),C.delete(e);let n=b.get(e);n&&(x(n),n.tool.remove(),b.delete(e))}function ue(e,t){let n=Number(e.dataset.yMin?.trim()||NaN),r=Number(e.dataset.yMax?.trim()||NaN),i=Number.isFinite(n),a=Number.isFinite(r);if(!i&&!a)return;let o=0,s=0;for(let e of t)Number.isFinite(e)&&(o=Math.min(o,e),s=Math.max(s,e));return de(i?n:o,a?r:s)}function de(e,t){let n=t-e;if(n>0)return r=>{let i=Math.min(t,Math.max(e,r||0));return Number.isFinite(n)?(t-i)/n:(t/2-i/2)/(t/2-e/2)}}function T(r,a){let s=r.dataset.type&&r.dataset.type===`bar`,u=a,h=C.get(r);h?.events.abort();let g=b.get(r);g&&(x(g),g.hasSnapped=!1),r.replaceChildren();let y=te(r),{svg:w,svgId:T,width:fe,height:E,viewBox:pe}=n(r,y.at(-1)),D=new AbortController,O={svg:w,events:D,ownsTabIndex:h?.ownsTabIndex??!1};C.set(r,O);let{color:k,backgroundColor:me}=ee(r),A={T:12,R:12,B:12,L:12},he=v(),ge=String(_(r,`showLastValue`,`false`))===`true`,j={left:A.L,top:A.T,width:fe-A.L-A.R,height:E-A.T-A.B,bottom:E-A.B,right:fe-A.R},{min:M}=ae(y),N=y.map(e=>[null,void 0].includes(e)?e:e+(M<0?Math.abs(M):0)),{max:P}=ae(N),F=ue(r,y)??(P===0?de(Math.min(M,0),M<0?0:1):void 0),I=j.width/(y.length-1)==1/0?j.width:j.width/(y.length-1);if(s){let[e,t,n,r]=pe.split(` `);w.setAttribute(`viewBox`,`${Number(e)-I/2} ${t} ${Number(n)+I} ${r}`)}let L=!y.some(e=>e>=0),_e=re(r),R=N.map((e,t)=>{let n={w:N.length===1?I/2:0,h:N.length===1?j.height/2:0},r=j.left+I*t+n.w,i=F?j.top+F(y[t])*j.height:(1-(e||0)/P)*j.height+n.h+A.T,a=F?j.top+F(0)*j.height:(1-(M<0?Math.abs(M):0)/P)*j.height+A.T+n.h,o=y[t]>=0;return{y:!F&&L&&y.length===1?j.top+j.height/2:i,x:r,v:y[t],d:_e[t]||null,isPositive:o,bar:{x:r-I/2,y:F?Math.min(i,a):y.length===1?j.top:o?i:L?j.top:a,h:F?Math.abs(i-a):y.length===1?j.height:o?a-i:L&&y.length===0?j.height:isNaN(i-a)?0:i-a,w:I}}});function z(){let t=document.createElementNS(e,`path`);return t.classList.add(`tiny-spark-line-area`),t}function ve(t){let n=document.createElementNS(e,`defs`);return n.appendChild(S({id:t,colorStart:String(_(r,`gradientFrom`,`#FFFFFF`)),colorEnd:String(_(r,`gradientTo`,`#FFFFFF`)),opacityStart:Math.max(0,Math.min(1,Number(_(r,`gradientFromOpacity`,1)))),opacityEnd:Math.max(0,Math.min(1,Number(_(r,`gradientToOpacity`,1))))})),n}function ye(t){let n=document.createElementNS(e,`defs`);return n.appendChild(S({id:`pos_${t}`,colorStart:String(_(r,`gradientFrom`,`#FFFFFF`)),colorEnd:String(_(r,`gradientTo`,`#FFFFFF`)),opacityStart:Math.max(0,Math.min(1,Number(_(r,`gradientFromOpacity`,1)))),opacityEnd:Math.max(0,Math.min(1,Number(_(r,`gradientToOpacity`,1))))})),n.appendChild(S({id:`neg_${t}`,colorStart:String(_(r,`gradientTo`,`#FFFFFF`)),colorEnd:String(_(r,`gradientFrom`,`#FFFFFF`)),opacityStart:Math.max(0,Math.min(1,Number(_(r,`gradientToOpacity`,1)))),opacityEnd:Math.max(0,Math.min(1,Number(_(r,`gradientFromOpacity`,1))))})),n}let B=[...R].map(e=>[null,void 0,1/0,-1/0,NaN,`NaN`].includes(e.v)?{...e,v:null}:e),be=r.getAttribute(`data-animation`),V=document.createElementNS(e,`path`);V.classList.add(`tiny-spark-line-path`);let H=z(),U=[],W=!!_(r,`gradientFrom`,``)&&!!_(r,`gradientTo`,``),G=v();if(!s){!r.dataset.curve||r.dataset.curve===`true`?!r.dataset.cutNull||r.dataset.cutNull===`false`?V.setAttribute(`d`,`M ${o(B)}`):V.setAttribute(`d`,`M ${c(B)}`):!r.dataset.cutNull||r.dataset.cutNull===`false`?V.setAttribute(`d`,`M ${i(B)}`):V.setAttribute(`d`,`M ${l(B)}`),V.setAttribute(`fill`,`none`);let t=ie(r);if(t.length&&!le(B.map(e=>e.y))){let n=v(),r=document.createElementNS(e,`defs`),i=document.createElementNS(e,`linearGradient`);i.setAttribute(`gradientTransform`,`rotate(90)`),i.setAttribute(`id`,n),t.forEach((n,r)=>{let a=document.createElementNS(e,`stop`);a.setAttribute(`offset`,ne(r,t.length)),a.setAttribute(`stop-color`,n),i.appendChild(a)}),r.appendChild(i),w.prepend(r),V.setAttribute(`stroke`,`url(#${n})`)}else V.setAttribute(`stroke`,String(_(r,`lineColor`,k)));V.setAttribute(`stroke-width`,String(_(r,`lineThickness`,2))),V.setAttribute(`stroke-linecap`,`round`),be===`true`&&u&&(V.style.opacity=`0`,H.style.opacity=`0`),W&&w.appendChild(ve(G)),R.length&&(!r.dataset.curve||r.dataset.curve===`true`?!r.dataset.cutNull||r.dataset.cutNull===`false`?H.setAttribute(`d`,`M ${B[0].x},${j.bottom} ${o(B)} L ${B.at(-1).x},${j.bottom} Z`):f(B,j.bottom,!0,!0).forEach(e=>{let t=z();t.setAttribute(`d`,e),W?t.setAttribute(`fill`,`url(#${G})`):t.setAttribute(`fill`,String(_(r,`areaColor`,`transparent`))),U.push(t)}):!r.dataset.cutNull||r.dataset.cutNull===`false`?H.setAttribute(`d`,`M ${B[0].x},${j.bottom} ${i(B)} L ${B.at(-1).x},${j.bottom} Z`):d(B,j.bottom).split(`;`).forEach(e=>{let t=z();t.setAttribute(`d`,`M ${e} Z`),W?t.setAttribute(`fill`,`url(#${G})`):t.setAttribute(`fill`,String(_(r,`areaColor`,`transparent`))),U.push(t)})),W?H.setAttribute(`fill`,`url(#${G})`):H.setAttribute(`fill`,String(_(r,`areaColor`,`transparent`))),R.length>1&&(U.length?U.forEach(e=>{w.appendChild(e)}):w.appendChild(H),w.appendChild(V))}let K=[];R.forEach((t,n)=>{let i=document.createElementNS(e,`line`);i.classList.add(`tiny-spark-indicator`),i.setAttribute(`id`,`indicator_${T}_${n}`),i.setAttribute(`x1`,String(j.left+(R.length===1?j.width/2:n*I))),i.setAttribute(`x2`,String(j.left+(R.length===1?j.width/2:n*I))),i.setAttribute(`y1`,String(j.top)),i.setAttribute(`y2`,String(j.bottom)),i.setAttribute(`stroke`,String(_(r,`indicatorColor`,`#1A1A1A`))),i.setAttribute(`stroke-width`,String(_(r,`indicatorWidth`,`1`))),i.setAttribute(`stroke-linecap`,`round`),i.style.pointerEvents=`none`,i.style.opacity=`0`,K.push(i),w.appendChild(i)});let q=[],xe=[],Se=Number(String(_(r,`plotRadius`,0)))>0,Ce=!String(_(r,`hidePlotsAbove`,``))||R.length<=Number(String(_(r,`hidePlotsAbove`,0))),we=Se&&Ce,J=document.createElementNS(e,`g`);s&&(W&&w.appendChild(ye(G)),R.forEach(({bar:n,v:i},a)=>{if(![null,void 0].includes(i)){let o=document.createElementNS(e,`rect`);o.classList.add(`tiny-spark-datapoint-bar`),o.setAttribute(`x`,String(n.x)),o.setAttribute(`y`,String(n.y)),o.setAttribute(`width`,String(n.w)),o.setAttribute(`height`,String(n.h)),W?i>=0?o.setAttribute(`fill`,`url(#pos_${G})`):o.setAttribute(`fill`,`url(#neg_${G})`):o.setAttribute(`fill`,String(_(r,`plotColor`,String(_(r,`lineColor`,k))))),o.style.opacity=R.length===1?`1`:`0`,o.style.transition=`opacity ${a*(t*2/R.length)}ms ease-in`,xe.push(o),J.appendChild(o)}}),w.appendChild(J)),Se&&!s&&(R.forEach(({x:n,y:i,v:a},o)=>{if(![null,void 0].includes(a)){let a=document.createElementNS(e,`circle`);a.classList.add(`tiny-spark-datapoint-circle`),a.classList.add(`circle-${T}`),a.setAttribute(`id`,`circle_${T}_${o}`),a.setAttribute(`cx`,String(n||0)),a.setAttribute(`cy`,String(i||0)),a.setAttribute(`r`,String(_(r,`plotRadius`,3))),a.setAttribute(`fill`,String(_(r,`plotColor`,String(_(r,`lineColor`,k))))),a.setAttribute(`stroke`,me),a.style.opacity=R.length===1?`1`:`0`,a.style.transition=`opacity ${o*(t*2/R.length)}ms ease-in`,a.style.pointerEvents=`none`,q[o]=a,we&&J.appendChild(a)}}),w.appendChild(J));let Y=null,X=R.at(-1);if(ge&&X?.v!=null){let t=Number(_(r,`lastValueFontSize`,12));Y=document.createElementNS(e,`text`),Y.classList.add(`tiny-spark-last-value`),Y.setAttribute(`id`,he),s?(Y.setAttribute(`x`,String(X.x+Number(_(r,`lineThickness`,2)))),Y.setAttribute(`y`,X.isPositive?String(X.y-t/3):String(X.bar.y+X.bar.h+t)),Y.setAttribute(`text-anchor`,`middle`)):(Y.setAttribute(`x`,String(X.x+6+Number(_(r,`lineThickness`,2)))),Y.setAttribute(`y`,String(X.y+t/3)),Y.setAttribute(`text-anchor`,`start`)),Y.setAttribute(`font-size`,String(t)+`px`),Y.setAttribute(`fill`,String(_(r,`lastValueColor`,String(_(r,`indicatorColor`,`#1A1A1A`))))),Y.textContent=se(r,X.v),Y.style.opacity=R.length===1?`1`:`0`,w.appendChild(Y)}let Te=document.createElementNS(e,`g`),Z={signal:D.signal},Ee=Number(_(r,`plotRadius`,3));function De(){let e=O.selection;if(!e)return;let t=e.index;we?q[t]?.setAttribute(`r`,String(Ee)):q[t]?.remove(),K[t].style.opacity=`0`,Y&&(Y.style.opacity=`1`),O.selection=void 0}function Q(){r.ownerDocument.removeEventListener(`pointerdown`,Oe,!0),De();let e=b.get(r);e&&(x(e),e.hasSnapped=!1)}function Oe(e){e.composedPath().includes(r)||Q()}function $(e,t){De(),O.selection={index:e,source:t},ce(w,r,R[e],T);let n=q[e];we?n?.setAttribute(`r`,String(Ee*1.5)):n&&w.appendChild(n),K[e].style.opacity=`1`,Y&&(Y.style.opacity=e===R.length-1?`0`:`1`)}R.forEach((t,n)=>{let i=document.createElementNS(e,`rect`);i.classList.add(`tiny-spark-tooltip-trap`),i.setAttribute(`x`,`${R.length===1?0:j.left+n*I-I/2}`),i.setAttribute(`y`,`${j.top}`),i.setAttribute(`height`,`${j.height}`),i.setAttribute(`width`,`${I}`),i.setAttribute(`fill`,`transparent`),i.setAttribute(`aria-describedby`,`tooltip_${T}`),i.addEventListener(`pointerenter`,e=>{e.pointerType!==`touch`&&O.selection?.source!==`touch`&&$(n,`mouse`)},Z),i.addEventListener(`pointerleave`,()=>{if(O.selection?.source===`mouse`&&O.selection.index===n){De();let e=b.get(r);e&&x(e)}},Z),i.addEventListener(`pointerup`,e=>{e.pointerType===`touch`&&(O.selection?.source===`touch`&&O.selection.index===n?Q():($(n,`touch`),r.focus({preventScroll:!0}),r.ownerDocument.addEventListener(`pointerdown`,Oe,{...Z,capture:!0})))},Z),Te.appendChild(i)}),w.appendChild(Te),R.length?(r.hasAttribute(`tabindex`)||(r.tabIndex=0,O.ownsTabIndex=!0),r.addEventListener(`focus`,()=>{O.selection||$(0,`keyboard`)},Z),r.addEventListener(`blur`,Q,Z),r.addEventListener(`pointerleave`,()=>{(!O.selection||O.selection.source===`mouse`)&&Q()},Z),r.addEventListener(`keydown`,e=>{let t=O.selection?.index,n=R.length-1,r;switch(e.key){case`ArrowLeft`:r=Math.max(0,(t??n+1)-1);break;case`ArrowRight`:r=Math.min(n,(t??-1)+1);break;case`Home`:r=0;break;case`End`:r=n;break;case`Escape`:if(!O.selection)return;Q(),e.preventDefault();return;default:return}e.preventDefault(),$(r,`keyboard`)},Z)):O.ownsTabIndex&&r.getAttribute(`tabindex`)===`0`&&(r.removeAttribute(`tabindex`),O.ownsTabIndex=!1),be===`true`&&u?oe().then(()=>{if(D.signal.aborted)return;q.forEach(e=>{e.style.opacity=`1`}),xe.forEach(e=>{e.style.opacity=`1`});let e=()=>{Y&&O.selection?.index!==R.length-1&&(Y.style.opacity=`1`)};V.parentNode===w&&V.getAttribute(`d`)?.trim()!==`M`?p(V,t,e):e(),H.parentNode===w&&m(w,H)}):(q.forEach(e=>{e.style.opacity=`1`}),xe.forEach(e=>{e.style.opacity=`1`}),Y&&(Y.style.opacity=`1`)),r.appendChild(w),r.matches(`:focus`)&&h?.selection?.source===`keyboard`&&R.length&&$(Math.min(h.selection.index,R.length-1),`keyboard`)}var fe=`data-animation.data-area-color.data-curve.data-dates.data-id.data-indicator-color.data-indicator-width.data-line-color.data-line-thickness.data-number-locale.data-number-rounding.data-number-style.data-number-currency.data-number-unit.data-number-show-on.data-plot-color.data-plot-radius.data-set.data-hide-plots-above.data-show-last-value.data-last-value-font-size.data-last-value-color.data-type.data-tooltip-smoothing.data-cut-null.data-gradient-from.data-gradient-to.data-gradient-from-opacity.data-gradient-to-opacity.data-temperature-colors.data-y-min.data-y-max`.split(`.`),E=new WeakMap;function pe(e){h(e&&typeof e.nodeType==`number`&&typeof e.querySelectorAll==`function`?e:document).forEach(e=>{if(!e.dataset.id){let t=v();e.setAttribute(`data-id`,t)}let t=E.get(e);t||(t={resize:new ResizeObserver(()=>O(e)),mutation:new MutationObserver(()=>O(e)),parent:null},E.set(e,t));let n=t;k(e),e.__renderCount=0,O(e),n.parent&&n.parent===e.parentElement&&(e.__renderCount=2),oe().then(()=>{if(E.get(e)!==n)return;n.mutation.observe(e,{attributeFilter:fe});let t=e.parentElement;n.parent!==t&&(n.resize.disconnect(),t&&n.resize.observe(t),n.parent=t)})})}function D(e=document){[e,...e.querySelectorAll(`*`)].forEach(e=>{let t=e,n=E.get(t);n&&(n.resize.disconnect(),n.mutation.disconnect(),E.delete(t),w(t),delete t.__renderCount)})}function O(e){g(e,`set`)&&T(e,e.__renderCount<2),e.__renderCount+=1}function k(e){e.dataset.set||console.error(`Tiny-spark exception:
2
+
3
+ [data-set] data attribute is missing.
4
+ Provide an array of numbers, for example:
5
+
6
+ data-set="[1, 2, 3]"`)}function me(e){return JSON.stringify(e)}export{D as destroy,pe as render,me as tinyFormat};
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "tiny-spark",
3
3
  "private": false,
4
- "version": "1.2.3",
4
+ "version": "1.3.0",
5
5
  "type": "module",
6
6
  "description": "An elegant, reactive and responsive sparkline chart solution without dependency.",
7
7
  "author": "Alec Lloyd Probert",
8
8
  "main": "./dist/tiny-spark.es.js",
9
- "exports": "./dist/tiny-spark.es.js",
9
+ "types": "./dist/src/index.d.ts",
10
+ "exports": {
11
+ "types": "./dist/src/index.d.ts",
12
+ "default": "./dist/tiny-spark.es.js"
13
+ },
10
14
  "keywords": [
11
15
  "sparkline",
12
16
  "chart",
@@ -20,16 +24,17 @@
20
24
  "url": "git+https://github.com/graphieros/tiny-spark.git"
21
25
  },
22
26
  "homepage": "https://tiny-spark.graphieros.com/",
23
- "scripts": {
24
- "dev": "vite",
25
- "build": "tsc && vite build"
26
- },
27
27
  "files": [
28
- "dist"
28
+ "dist/tiny-spark.es.js",
29
+ "dist/src/index.d.ts"
29
30
  ],
30
31
  "devDependencies": {
31
32
  "@types/node": "^24.0.8",
32
33
  "typescript": "~5.8.3",
33
34
  "vite": "^8.2.1"
35
+ },
36
+ "scripts": {
37
+ "dev": "vite",
38
+ "build": "vite build && tsc --noEmit false --declaration --emitDeclarationOnly --noEmitOnError --outDir dist"
34
39
  }
35
- }
40
+ }