@tradeglotnpm/charts 0.0.0-stage → 0.2.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/dist/index.js ADDED
@@ -0,0 +1,1763 @@
1
+ /*! Glot Charts 0.2.0 | Apache-2.0 with NOTICE | https://github.com/tradeglot/glot-charts */
2
+ var __defProp = Object.defineProperty;
3
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+
6
+ // src/scale.ts
7
+ function visibleRange(n, width, v) {
8
+ const count = Math.ceil(width / v.barWidth) + 1;
9
+ const last = Math.min(n - 1, Math.floor(v.end));
10
+ const first = Math.max(0, last - count + 1);
11
+ return [first, last];
12
+ }
13
+ function xOf(i, width, v) {
14
+ return width - (v.end - i + 0.5) * v.barWidth;
15
+ }
16
+ function barAt(x, width, v) {
17
+ return Math.round(v.end + 0.5 - (width - x) / v.barWidth);
18
+ }
19
+ function extent(values, pad2 = 0.05) {
20
+ let lo = Infinity;
21
+ let hi = -Infinity;
22
+ for (const x of values) {
23
+ if (x === null || !Number.isFinite(x)) continue;
24
+ if (x < lo) lo = x;
25
+ if (x > hi) hi = x;
26
+ }
27
+ if (lo === Infinity) return [0, 1];
28
+ if (lo === hi) return [lo - 1, hi + 1];
29
+ const p = (hi - lo) * pad2;
30
+ return [lo - p, hi + p];
31
+ }
32
+ function niceStep(range, ticks) {
33
+ const raw = range / Math.max(1, ticks);
34
+ const mag = 10 ** Math.floor(Math.log10(raw));
35
+ const norm = raw / mag;
36
+ const nice = norm < 1.5 ? 1 : norm < 3 ? 2 : norm < 7 ? 5 : 10;
37
+ return nice * mag;
38
+ }
39
+ function decimalsFor(step) {
40
+ return Math.max(0, Math.min(8, -Math.floor(Math.log10(step) + 1e-9)));
41
+ }
42
+ function formatNumber(v, decimals) {
43
+ const s = Math.abs(v).toFixed(decimals);
44
+ const [i = "0", f] = s.split(".");
45
+ const g = i.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
46
+ return (v < 0 ? "\u2212" : "") + g + (f ? "." + f : "");
47
+ }
48
+
49
+ // src/marks.ts
50
+ function resolveColor(c, th) {
51
+ if (!c) return null;
52
+ switch (c) {
53
+ case "up":
54
+ return th.up;
55
+ case "down":
56
+ return th.down;
57
+ case "accent":
58
+ return th.accent;
59
+ case "neutral":
60
+ return th.muted;
61
+ default:
62
+ return c;
63
+ }
64
+ }
65
+ function coloredLine(ctx, s, fallback, th, a, b, x, y) {
66
+ ctx.lineWidth = 1.5;
67
+ for (let i = Math.max(a, 1); i <= b; i++) {
68
+ const p = s.values[i - 1];
69
+ const q = s.values[i];
70
+ if (p === null || p === void 0 || q === null || q === void 0) continue;
71
+ ctx.strokeStyle = resolveColor(s.colors?.[i], th) ?? fallback;
72
+ ctx.beginPath();
73
+ ctx.moveTo(x(i - 1), y(p));
74
+ ctx.lineTo(x(i), y(q));
75
+ ctx.stroke();
76
+ }
77
+ ctx.lineWidth = 1;
78
+ }
79
+ function drawFill(ctx, f, lines, th, a, b, x, y) {
80
+ const la = lines.find((l) => l.name === f.a)?.values;
81
+ const lb = lines.find((l) => l.name === f.b)?.values;
82
+ if (!la || !lb) return;
83
+ for (let i = Math.max(a, 1); i <= b; i++) {
84
+ const v = [la[i - 1], la[i], lb[i], lb[i - 1]];
85
+ const color = resolveColor(f.colors[i], th);
86
+ if (!color || v.some((n) => n === null || n === void 0)) continue;
87
+ const [a0, a1, b1, b0] = v;
88
+ ctx.fillStyle = color;
89
+ ctx.beginPath();
90
+ ctx.moveTo(x(i - 1), y(a0));
91
+ ctx.lineTo(x(i), y(a1));
92
+ ctx.lineTo(x(i), y(b1));
93
+ ctx.lineTo(x(i - 1), y(b0));
94
+ ctx.closePath();
95
+ ctx.fill();
96
+ }
97
+ }
98
+ function drawShapes(ctx, s, bars, th, a, b, x, y, paneH) {
99
+ const r = 6;
100
+ for (let i = a; i <= b; i++) {
101
+ if (!s.values[i]) continue;
102
+ const bar = bars[i];
103
+ const cx = x(i);
104
+ const cy = s.at === "below_bar" ? y(bar.low) + 2 * r + 2 : s.at === "top" ? 2 * r : s.at === "bottom" ? paneH - 2 * r : y(bar.high) - 2 * r - 2;
105
+ const color = resolveColor(s.colors?.[i], th) ?? th.accent;
106
+ ctx.fillStyle = ctx.strokeStyle = color;
107
+ shape(ctx, s.shape, cx, cy, r);
108
+ if (s.text) {
109
+ ctx.font = `11px ${th.font}`;
110
+ ctx.textAlign = "center";
111
+ const below = s.at === "below_bar" || s.at === "bottom";
112
+ ctx.fillText(s.text, cx, below ? cy + 2 * r + 4 : cy - 2 * r - 4);
113
+ ctx.textAlign = "start";
114
+ }
115
+ }
116
+ }
117
+ function shape(ctx, kind, cx, cy, r) {
118
+ ctx.beginPath();
119
+ switch (kind) {
120
+ case "triangle_up":
121
+ case "arrow_up":
122
+ case "label_up":
123
+ poly(ctx, [cx, cy - r, cx + r, cy + r, cx - r, cy + r]);
124
+ break;
125
+ case "triangle_down":
126
+ case "arrow_down":
127
+ case "label_down":
128
+ poly(ctx, [cx, cy + r, cx + r, cy - r, cx - r, cy - r]);
129
+ break;
130
+ case "square":
131
+ ctx.rect(cx - r * 0.8, cy - r * 0.8, r * 1.6, r * 1.6);
132
+ break;
133
+ case "diamond":
134
+ poly(ctx, [cx, cy - r, cx + r, cy, cx, cy + r, cx - r, cy]);
135
+ break;
136
+ case "cross":
137
+ case "x_cross": {
138
+ const d = kind === "cross" ? 0 : Math.PI / 4;
139
+ ctx.lineWidth = 2;
140
+ for (const t of [d, d + Math.PI / 2]) {
141
+ ctx.moveTo(cx - r * Math.cos(t), cy - r * Math.sin(t));
142
+ ctx.lineTo(cx + r * Math.cos(t), cy + r * Math.sin(t));
143
+ }
144
+ ctx.stroke();
145
+ ctx.lineWidth = 1;
146
+ return;
147
+ }
148
+ case "flag":
149
+ poly(ctx, [cx - r * 0.6, cy - r, cx + r, cy - r * 0.4, cx - r * 0.6, cy + r * 0.2]);
150
+ break;
151
+ default:
152
+ ctx.arc(cx, cy, r * 0.7, 0, Math.PI * 2);
153
+ }
154
+ ctx.fill();
155
+ }
156
+ function poly(ctx, pts) {
157
+ ctx.moveTo(pts[0], pts[1]);
158
+ for (let k = 2; k < pts.length; k += 2) ctx.lineTo(pts[k], pts[k + 1]);
159
+ ctx.closePath();
160
+ }
161
+
162
+ // src/draw.ts
163
+ var AXIS_W = 72;
164
+ var AXIS_H = 24;
165
+ function drawFrame(ctx, d, v, th, f) {
166
+ const plotW = f.width - AXIS_W;
167
+ const series = d.series ?? [];
168
+ const lower = series.filter((s) => !s.overlay);
169
+ const mainH = (f.height - AXIS_H) * (lower.length ? 0.72 : 1);
170
+ const lowerTop = mainH;
171
+ const lowerH = f.height - AXIS_H - mainH;
172
+ ctx.clearRect(0, 0, f.width, f.height);
173
+ ctx.fillStyle = th.bg;
174
+ ctx.fillRect(0, 0, f.width, f.height);
175
+ if (d.bars.length === 0) return;
176
+ const [a, b] = visibleRange(d.bars.length, plotW, v);
177
+ const vis = d.bars.slice(a, b + 1);
178
+ const overlays = series.filter((s) => s.overlay);
179
+ const [lo, hi] = extent([
180
+ ...vis.flatMap((x2) => [x2.low, x2.high]),
181
+ ...overlays.flatMap((s) => s.values.slice(a, b + 1))
182
+ ]);
183
+ const y = (p) => (hi - p) / (hi - lo) * (mainH - 8) + 4;
184
+ const x = (i) => xOf(i, plotW, v);
185
+ const step = niceStep(hi - lo, Math.max(2, Math.floor(mainH / 60)));
186
+ const dec = decimalsFor(step);
187
+ ctx.font = `12px ${th.mono}`;
188
+ ctx.textBaseline = "middle";
189
+ for (let p = Math.ceil(lo / step) * step; p <= hi; p += step) {
190
+ line(ctx, th.grid, 0, y(p), plotW, y(p));
191
+ ctx.fillStyle = th.muted;
192
+ ctx.fillText(formatNumber(p, dec), plotW + 6, y(p));
193
+ }
194
+ if (f.marked !== null && f.marked >= a && f.marked <= b) {
195
+ ctx.fillStyle = th.grid;
196
+ ctx.fillRect(x(f.marked) - v.barWidth / 2, 0, v.barWidth, f.height - AXIS_H);
197
+ }
198
+ const bw = Math.max(1, v.barWidth * 0.7);
199
+ for (let i = a; i <= b; i++) {
200
+ const bar = d.bars[i];
201
+ const up = bar.close >= bar.open;
202
+ ctx.strokeStyle = ctx.fillStyle = up ? th.up : th.down;
203
+ const cx = Math.round(x(i)) + 0.5;
204
+ line(ctx, ctx.strokeStyle, cx, y(bar.high), cx, y(bar.low));
205
+ const top = y(Math.max(bar.open, bar.close));
206
+ ctx.fillRect(cx - bw / 2, top, bw, Math.max(1, y(Math.min(bar.open, bar.close)) - top));
207
+ }
208
+ for (const fl of d.fills ?? []) drawFill(ctx, fl, series, th, a, b, x, y);
209
+ overlays.forEach((s, k) => {
210
+ const color = th.series[k % th.series.length];
211
+ if (s.colors?.some((c) => c)) coloredLine(ctx, s, color, th, a, b, x, y);
212
+ else polyline(ctx, color, s.values, a, b, x, y, k >= th.series.length);
213
+ });
214
+ for (const sh of d.shapes ?? []) drawShapes(ctx, sh, d.bars, th, a, b, x, y, mainH);
215
+ const index = (t) => bisect(d.bars, t);
216
+ for (const t of d.trades ?? []) {
217
+ const ie = index(t.entryTime);
218
+ const ix = index(t.exitTime);
219
+ const color = t.side === "buy" ? th.up : th.down;
220
+ if (ie >= a && ie <= b) triangle(ctx, color, x(ie), y(t.entryPrice), t.side === "buy");
221
+ if (ix >= a && ix <= b) ring(ctx, color, x(ix), y(t.exitPrice));
222
+ }
223
+ if (lower.length) {
224
+ line(ctx, th.grid, 0, lowerTop, f.width, lowerTop);
225
+ const [llo, lhi] = extent(lower.flatMap((s) => s.values.slice(a, b + 1)));
226
+ const ly = (p) => lowerTop + 4 + (lhi - p) / (lhi - llo) * (lowerH - 8);
227
+ lower.forEach((s, k) => {
228
+ const color = th.series[k % th.series.length];
229
+ if (s.colors?.some((c) => c)) coloredLine(ctx, s, color, th, a, b, x, ly);
230
+ else polyline(ctx, color, s.values, a, b, x, ly, false);
231
+ });
232
+ const ld = decimalsFor(niceStep(lhi - llo, 2));
233
+ ctx.fillStyle = th.muted;
234
+ ctx.fillText(formatNumber(lhi, ld), plotW + 6, lowerTop + 10);
235
+ ctx.fillText(formatNumber(llo, ld), plotW + 6, lowerTop + lowerH - 10);
236
+ }
237
+ drawTimeAxis(ctx, d, v, th, f, a, b);
238
+ drawCrosshair(ctx, d, th, f, x, y, mainH, dec);
239
+ }
240
+ function drawTimeAxis(ctx, d, v, th, f, a, b) {
241
+ const plotW = f.width - AXIS_W;
242
+ const top = f.height - AXIS_H;
243
+ line(ctx, th.grid, 0, top, f.width, top);
244
+ ctx.fillStyle = th.muted;
245
+ ctx.font = `12px ${th.font}`;
246
+ const every = Math.max(1, Math.ceil(110 / v.barWidth));
247
+ for (let i = a - a % every; i <= b; i += every) {
248
+ if (i < a) continue;
249
+ const t = new Date(d.bars[i].time).toISOString();
250
+ ctx.fillText(`${t.slice(5, 10)} ${t.slice(11, 16)}`, xOf(i, plotW, v) - 30, top + 12);
251
+ }
252
+ ctx.fillText("UTC", plotW + 6, top + 12);
253
+ }
254
+ function drawCrosshair(ctx, d, th, f, x, y, mainH, dec) {
255
+ if (f.hover === null || !d.bars[f.hover]) return;
256
+ const bar = d.bars[f.hover];
257
+ ctx.setLineDash([4, 4]);
258
+ line(
259
+ ctx,
260
+ th.muted,
261
+ Math.round(x(f.hover)) + 0.5,
262
+ 0,
263
+ Math.round(x(f.hover)) + 0.5,
264
+ f.height - AXIS_H
265
+ );
266
+ ctx.setLineDash([]);
267
+ const yc = y(bar.close);
268
+ if (yc >= 0 && yc <= mainH) {
269
+ ctx.fillStyle = th.grid;
270
+ ctx.fillRect(f.width - AXIS_W, yc - 9, AXIS_W, 18);
271
+ ctx.fillStyle = th.text;
272
+ ctx.font = `12px ${th.mono}`;
273
+ ctx.fillText(formatNumber(bar.close, dec + 1), f.width - AXIS_W + 6, yc);
274
+ }
275
+ }
276
+ function polyline(ctx, color, vals, a, b, x, y, dashed) {
277
+ ctx.strokeStyle = color;
278
+ ctx.lineWidth = 1.5;
279
+ ctx.setLineDash(dashed ? [6, 3] : []);
280
+ ctx.beginPath();
281
+ let pen = false;
282
+ for (let i = a; i <= b; i++) {
283
+ const val = vals[i];
284
+ if (val === null || val === void 0 || !Number.isFinite(val)) {
285
+ pen = false;
286
+ continue;
287
+ }
288
+ if (pen) ctx.lineTo(x(i), y(val));
289
+ else ctx.moveTo(x(i), y(val));
290
+ pen = true;
291
+ }
292
+ ctx.stroke();
293
+ ctx.setLineDash([]);
294
+ ctx.lineWidth = 1;
295
+ }
296
+ function line(ctx, color, x1, y1, x2, y2) {
297
+ ctx.strokeStyle = color;
298
+ ctx.beginPath();
299
+ ctx.moveTo(x1, y1);
300
+ ctx.lineTo(x2, y2);
301
+ ctx.stroke();
302
+ }
303
+ function triangle(ctx, color, cx, cy, up) {
304
+ const s = 6;
305
+ const yy = up ? cy + 10 : cy - 10;
306
+ ctx.fillStyle = color;
307
+ ctx.beginPath();
308
+ ctx.moveTo(cx, up ? yy - s : yy + s);
309
+ ctx.lineTo(cx - s, up ? yy + s : yy - s);
310
+ ctx.lineTo(cx + s, up ? yy + s : yy - s);
311
+ ctx.fill();
312
+ }
313
+ function ring(ctx, color, cx, cy) {
314
+ ctx.strokeStyle = color;
315
+ ctx.lineWidth = 2;
316
+ ctx.beginPath();
317
+ ctx.arc(cx, cy, 4, 0, Math.PI * 2);
318
+ ctx.stroke();
319
+ ctx.lineWidth = 1;
320
+ }
321
+ function bisect(bars, t) {
322
+ let lo = 0;
323
+ let hi = bars.length - 1;
324
+ while (lo < hi) {
325
+ const mid = lo + hi + 1 >> 1;
326
+ if (bars[mid].time <= t) lo = mid;
327
+ else hi = mid - 1;
328
+ }
329
+ return lo;
330
+ }
331
+
332
+ // src/attribution.ts
333
+ var ATTRIBUTION_SRC = new URL("../assets/glot-charts-attribution.svg", import.meta.url).href;
334
+ var ATTRIBUTION_HREF = "https://tradeglot.com/";
335
+
336
+ // src/styles.ts
337
+ var CSS = `
338
+ :where(.glot-chart-legend){position:absolute;left:8px;top:6px;right:80px;font:12px var(--glot-chart-mono);color:var(--glot-chart-text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;pointer-events:none}
339
+ :where(.glot-chart-label){position:absolute;right:80px;bottom:30px;font:600 12px var(--glot-chart-font);color:var(--glot-chart-muted);border:1px solid var(--glot-chart-grid);border-radius:999px;padding:2px 10px;pointer-events:none}
340
+ `;
341
+ function injectStyles(doc) {
342
+ if (doc.querySelector("style[data-glot-charts]")) return;
343
+ const style = doc.createElement("style");
344
+ style.dataset.glotCharts = "";
345
+ style.textContent = CSS;
346
+ doc.head.append(style);
347
+ }
348
+ function applyThemeVars(el, th) {
349
+ el.style.setProperty("--glot-chart-text", th.text);
350
+ el.style.setProperty("--glot-chart-muted", th.muted);
351
+ el.style.setProperty("--glot-chart-grid", th.grid);
352
+ el.style.setProperty("--glot-chart-font", th.font);
353
+ el.style.setProperty("--glot-chart-mono", th.mono);
354
+ }
355
+
356
+ // src/theme.ts
357
+ var FONT_UI = '"Be Vietnam Pro", "Inter", sans-serif';
358
+ var FONT_MONO = '"JetBrains Mono", Menlo, monospace';
359
+ var THEMES = {
360
+ dark: {
361
+ bg: "#0E0F1A",
362
+ text: "#ECEEF8",
363
+ muted: "#A3A8C3",
364
+ grid: "#2A2E48",
365
+ up: "#3D8BFF",
366
+ down: "#FF7A3D",
367
+ accent: "#A99FFF",
368
+ font: FONT_UI,
369
+ mono: FONT_MONO,
370
+ series: ["#A99FFF", "#ECEEF8", "#A3A8C3"]
371
+ },
372
+ light: {
373
+ bg: "#F6F6FB",
374
+ text: "#14152B",
375
+ muted: "#5A5F7A",
376
+ grid: "#DCDDEA",
377
+ up: "#2266DE",
378
+ down: "#BA481A",
379
+ accent: "#5B4BE0",
380
+ font: FONT_UI,
381
+ mono: FONT_MONO,
382
+ series: ["#5B4BE0", "#14152B", "#5A5F7A"]
383
+ }
384
+ };
385
+ function readTheme(el, option = "dark") {
386
+ const base = typeof option === "string" ? THEMES[option] : { ...THEMES.dark, ...option };
387
+ const css = getComputedStyle(el);
388
+ const v = (name, fallback) => css.getPropertyValue(name).trim() || fallback;
389
+ const accent = v("--tg-text-accent", base.accent);
390
+ const text = v("--tg-text", base.text);
391
+ const muted = v("--tg-muted", base.muted);
392
+ const fromCss = css.getPropertyValue("--tg-text-accent").trim() !== "";
393
+ return {
394
+ bg: v("--tg-bg", base.bg),
395
+ text,
396
+ muted,
397
+ grid: v("--tg-border", base.grid),
398
+ up: v("--tg-chart-candle-up", base.up),
399
+ down: v("--tg-chart-candle-down", base.down),
400
+ accent,
401
+ font: v("--tg-font-ui", base.font),
402
+ mono: v("--tg-font-mono", base.mono),
403
+ // Lines: accent, then text, then muted.
404
+ series: fromCss ? [accent, text, muted] : base.series
405
+ };
406
+ }
407
+
408
+ // src/chart.ts
409
+ var MIN_BAR = 2;
410
+ var MAX_BAR = 40;
411
+ var GlotChart = class {
412
+ constructor(host, opts = {}) {
413
+ this.opts = opts;
414
+ __publicField(this, "el");
415
+ __publicField(this, "canvas");
416
+ __publicField(this, "legend");
417
+ __publicField(this, "labelEl");
418
+ __publicField(this, "data", { bars: [] });
419
+ __publicField(this, "view", { end: 0, barWidth: 8 });
420
+ __publicField(this, "frame", { width: 0, height: 0, hover: null, marked: null });
421
+ __publicField(this, "drag", null);
422
+ __publicField(this, "moved", false);
423
+ __publicField(this, "raf", 0);
424
+ __publicField(this, "resize");
425
+ this.el = document.createElement("div");
426
+ this.el.className = "glot-chart";
427
+ this.el.style.cssText = "position:relative;width:100%;height:100%;overflow:hidden;touch-action:none";
428
+ this.canvas = document.createElement("canvas");
429
+ this.canvas.style.cssText = "position:absolute;inset:0;width:100%;height:100%;cursor:crosshair";
430
+ this.canvas.setAttribute("role", "img");
431
+ this.legend = document.createElement("div");
432
+ this.legend.className = "glot-chart-legend";
433
+ this.labelEl = document.createElement("span");
434
+ this.labelEl.className = "glot-chart-label";
435
+ this.el.append(this.canvas, this.legend, this.labelEl);
436
+ if (opts.attributionLogo !== false) {
437
+ const link = document.createElement("a");
438
+ link.className = "glot-chart-attribution";
439
+ link.href = opts.attributionHref ?? ATTRIBUTION_HREF;
440
+ link.target = "_blank";
441
+ link.rel = "noopener";
442
+ link.title = "Charts by Glot Charts (TradeGlot)";
443
+ link.style.cssText = "position:absolute;left:8px;bottom:28px;height:18px;opacity:0.7";
444
+ const logo = document.createElement("img");
445
+ logo.src = opts.attributionSrc ?? ATTRIBUTION_SRC;
446
+ logo.alt = "Glot Charts";
447
+ logo.height = 18;
448
+ logo.style.cssText = "height:18px;display:block";
449
+ link.append(logo);
450
+ this.el.append(link);
451
+ }
452
+ injectStyles(host.ownerDocument);
453
+ host.append(this.el);
454
+ this.bind();
455
+ this.resize = new ResizeObserver(() => this.schedule());
456
+ this.resize.observe(this.el);
457
+ }
458
+ setData(data, keepView = false) {
459
+ const wasAtEnd = this.view.end >= this.data.bars.length - 1;
460
+ this.data = data;
461
+ if (!keepView || wasAtEnd) this.view.end = Math.max(0, data.bars.length - 1);
462
+ this.labelEl.textContent = data.label ?? "";
463
+ this.labelEl.hidden = !data.label;
464
+ this.canvas.setAttribute("aria-label", this.ariaLabel());
465
+ this.schedule();
466
+ }
467
+ /**
468
+ * Adds or changes the newest bar, for live data. A bar with the same time as the last bar
469
+ * replaces it; a later bar is appended. Indicator values for the new bar can follow through
470
+ * `setData`. Throws on a bar older than the last one.
471
+ */
472
+ update(bar) {
473
+ const bars = this.data.bars;
474
+ const last = bars[bars.length - 1];
475
+ const atEnd = this.view.end >= bars.length - 1;
476
+ if (last && bar.time < last.time) {
477
+ throw new RangeError(`update: bar time ${bar.time} is older than the last bar ${last.time}`);
478
+ }
479
+ if (last && bar.time === last.time) bars[bars.length - 1] = bar;
480
+ else {
481
+ bars.push(bar);
482
+ if (atEnd) this.view.end = bars.length - 1;
483
+ }
484
+ this.canvas.setAttribute("aria-label", this.ariaLabel());
485
+ this.schedule();
486
+ }
487
+ /** Switches between the built-in themes or your own colors. */
488
+ setTheme(theme) {
489
+ this.opts = { ...this.opts, theme };
490
+ this.schedule();
491
+ }
492
+ /** The data the chart currently draws. */
493
+ getData() {
494
+ return this.data;
495
+ }
496
+ /** Highlights one bar (debugger cursor) and scrolls it into view. */
497
+ mark(bar) {
498
+ this.frame.marked = bar;
499
+ if (bar !== null) {
500
+ const visible = (this.frame.width - AXIS_W) / this.view.barWidth;
501
+ if (bar > this.view.end || bar < this.view.end - visible + 1) {
502
+ this.view.end = Math.min(this.data.bars.length - 1, bar + Math.floor(visible / 2));
503
+ }
504
+ }
505
+ this.schedule();
506
+ }
507
+ /** Re-reads the theme colors (after a theme switch). */
508
+ refresh() {
509
+ this.schedule();
510
+ }
511
+ dispose() {
512
+ this.resize.disconnect();
513
+ cancelAnimationFrame(this.raf);
514
+ this.el.remove();
515
+ }
516
+ ariaLabel() {
517
+ const label = this.data.label;
518
+ return `${this.data.bars.length} bars${label ? `, ${label}` : ""}`;
519
+ }
520
+ bind() {
521
+ const c = this.canvas;
522
+ c.addEventListener(
523
+ "wheel",
524
+ (e) => {
525
+ e.preventDefault();
526
+ const factor = e.deltaY > 0 ? 0.85 : 1.15;
527
+ this.view.barWidth = Math.min(MAX_BAR, Math.max(MIN_BAR, this.view.barWidth * factor));
528
+ this.schedule();
529
+ },
530
+ { passive: false }
531
+ );
532
+ c.addEventListener("pointerdown", (e) => {
533
+ this.drag = { x: e.clientX, end: this.view.end };
534
+ this.moved = false;
535
+ c.setPointerCapture(e.pointerId);
536
+ });
537
+ c.addEventListener("pointermove", (e) => {
538
+ const r = c.getBoundingClientRect();
539
+ if (this.drag) {
540
+ const dx = e.clientX - this.drag.x;
541
+ if (Math.abs(dx) > 3) this.moved = true;
542
+ const n = this.data.bars.length;
543
+ this.view.end = Math.min(n - 1 + 20, Math.max(0, this.drag.end - dx / this.view.barWidth));
544
+ }
545
+ this.hover(barAt(e.clientX - r.left, r.width - AXIS_W, this.view));
546
+ });
547
+ c.addEventListener("pointerup", (e) => {
548
+ const r = c.getBoundingClientRect();
549
+ if (this.drag && !this.moved) {
550
+ const bar = barAt(e.clientX - r.left, r.width - AXIS_W, this.view);
551
+ if (bar >= 0 && bar < this.data.bars.length) this.opts.onBarClick?.(bar);
552
+ }
553
+ this.drag = null;
554
+ });
555
+ c.addEventListener("pointerleave", () => this.hover(null));
556
+ }
557
+ hover(bar) {
558
+ const valid = bar !== null && bar >= 0 && bar < this.data.bars.length ? bar : null;
559
+ this.frame.hover = valid;
560
+ this.renderLegend(valid ?? this.frame.marked ?? this.data.bars.length - 1);
561
+ this.schedule();
562
+ }
563
+ renderLegend(i) {
564
+ const b = this.data.bars[i];
565
+ if (!b) {
566
+ this.legend.textContent = "";
567
+ return;
568
+ }
569
+ const f = (v) => formatNumber(v, 2);
570
+ const parts = [`O ${f(b.open)} H ${f(b.high)} L ${f(b.low)} C ${f(b.close)}`];
571
+ for (const s of this.data.series ?? []) {
572
+ const v = s.values[i];
573
+ parts.push(`${s.name} ${v === null || v === void 0 ? "na" : f(v)}`);
574
+ }
575
+ this.legend.textContent = parts.join(" ");
576
+ }
577
+ schedule() {
578
+ cancelAnimationFrame(this.raf);
579
+ this.raf = requestAnimationFrame(() => this.draw());
580
+ }
581
+ draw() {
582
+ const dpr = window.devicePixelRatio || 1;
583
+ const w = this.el.clientWidth;
584
+ const h = this.el.clientHeight;
585
+ if (w === 0 || h === 0) return;
586
+ if (this.canvas.width !== Math.round(w * dpr) || this.canvas.height !== Math.round(h * dpr)) {
587
+ this.canvas.width = Math.round(w * dpr);
588
+ this.canvas.height = Math.round(h * dpr);
589
+ }
590
+ const ctx = this.canvas.getContext("2d");
591
+ if (!ctx) return;
592
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
593
+ this.frame.width = w;
594
+ this.frame.height = h;
595
+ if (this.frame.hover === null)
596
+ this.renderLegend(this.frame.marked ?? this.data.bars.length - 1);
597
+ const theme = readTheme(this.el, this.opts.theme);
598
+ applyThemeVars(this.el, theme);
599
+ drawFrame(ctx, this.data, this.view, theme, this.frame);
600
+ }
601
+ };
602
+ function createChart(host, options = {}) {
603
+ return new GlotChart(host, options);
604
+ }
605
+
606
+ // src/version.ts
607
+ var VERSION = "0.2.0";
608
+
609
+ // src/csv.ts
610
+ function barsFromCsv(text) {
611
+ const lines = text.split("\n").filter((l2) => l2.trim());
612
+ const head = (lines.shift() ?? "").split(",").map((h2) => h2.trim().toLowerCase());
613
+ const col = (n) => head.indexOf(n);
614
+ const [t, o, h, l, c] = ["time", "open", "high", "low", "close"].map(col);
615
+ if ([t, o, h, l, c].some((i) => i === void 0 || i < 0)) return [];
616
+ const out = [];
617
+ for (const line2 of lines) {
618
+ const cells = line2.split(",");
619
+ const bar = {
620
+ time: Number(cells[t]),
621
+ open: Number(cells[o]),
622
+ high: Number(cells[h]),
623
+ low: Number(cells[l]),
624
+ close: Number(cells[c])
625
+ };
626
+ if (Object.values(bar).every(Number.isFinite)) out.push(bar);
627
+ }
628
+ return out;
629
+ }
630
+
631
+ // src/series/logo.ts
632
+ function attributionLink(opts) {
633
+ const link = document.createElement("a");
634
+ link.className = "glot-chart-attribution";
635
+ link.href = opts.attributionHref ?? ATTRIBUTION_HREF;
636
+ link.target = "_blank";
637
+ link.rel = "noopener";
638
+ link.title = "Charts by Glot Charts (TradeGlot)";
639
+ const axisH = opts.timeAxisHeight ?? 24;
640
+ link.style.cssText = `position:absolute;left:8px;bottom:${axisH + 6}px;height:18px;opacity:0.7;z-index:3`;
641
+ const img = document.createElement("img");
642
+ img.src = opts.attributionSrc ?? ATTRIBUTION_SRC;
643
+ img.alt = "Glot Charts";
644
+ img.height = 18;
645
+ img.style.cssText = "height:18px;display:block";
646
+ link.append(img);
647
+ return link;
648
+ }
649
+
650
+ // src/series/paint.ts
651
+ function dash(style, w) {
652
+ switch (style) {
653
+ case "dotted":
654
+ return [w, w];
655
+ case "dashed":
656
+ return [2 * w, 2 * w];
657
+ case "large-dashed":
658
+ return [6 * w, 6 * w];
659
+ case "sparse-dotted":
660
+ return [w, 4 * w];
661
+ default:
662
+ return [];
663
+ }
664
+ }
665
+ function* visiblePoints(points, L) {
666
+ for (const p of points) {
667
+ const i = L.at(p.time);
668
+ if (i === void 0 || i < L.first - 1 || i > L.last + 1) continue;
669
+ yield [p, i];
670
+ }
671
+ }
672
+ function paintSeries(ctx, s, L) {
673
+ if (!s.visible) return;
674
+ if (s.kind === "candles") paintCandles(ctx, s, L);
675
+ else if (s.kind === "line") paintLine(ctx, s, L);
676
+ else paintHistogram(ctx, s, L);
677
+ }
678
+ function paintCandles(ctx, s, L) {
679
+ const o = s.opts;
680
+ const up = o.upColor ?? L.theme.up;
681
+ const down = o.downColor ?? L.theme.down;
682
+ const bw = Math.max(1, Math.min(L.bw * 0.7, L.bw - 1));
683
+ ctx.lineWidth = 1;
684
+ ctx.setLineDash([]);
685
+ for (const [b, i] of visiblePoints(s.data(), L)) {
686
+ const rising = b.close >= b.open;
687
+ const cx = Math.round(L.x(i)) + 0.5;
688
+ ctx.strokeStyle = rising ? o.wickUpColor ?? up : o.wickDownColor ?? down;
689
+ ctx.beginPath();
690
+ ctx.moveTo(cx, L.y(b.high));
691
+ ctx.lineTo(cx, L.y(b.low));
692
+ ctx.stroke();
693
+ ctx.fillStyle = rising ? up : down;
694
+ const top = L.y(Math.max(b.open, b.close));
695
+ const h = Math.max(1, L.y(Math.min(b.open, b.close)) - top);
696
+ ctx.fillRect(Math.round(cx - bw / 2), top, Math.max(1, Math.round(bw)), h);
697
+ }
698
+ }
699
+ function paintLine(ctx, s, L) {
700
+ const w = s.opts.width ?? 1.5;
701
+ ctx.strokeStyle = s.opts.color ?? L.theme.series[0];
702
+ ctx.lineWidth = w;
703
+ ctx.setLineDash(dash(s.opts.style, w));
704
+ ctx.beginPath();
705
+ let pen = false;
706
+ let prev = -2;
707
+ for (const [p, i] of visiblePoints(s.data(), L)) {
708
+ if (!Number.isFinite(p.value)) {
709
+ pen = false;
710
+ continue;
711
+ }
712
+ if (pen && i > prev) ctx.lineTo(L.x(i), L.y(p.value));
713
+ else ctx.moveTo(L.x(i), L.y(p.value));
714
+ pen = true;
715
+ prev = i;
716
+ }
717
+ ctx.stroke();
718
+ ctx.setLineDash([]);
719
+ ctx.lineWidth = 1;
720
+ }
721
+ function paintHistogram(ctx, s, L) {
722
+ const base = L.y(s.opts.base ?? 0);
723
+ const bw = Math.max(1, Math.round(L.bw * 0.8));
724
+ const fallback = s.opts.color ?? L.theme.series[0];
725
+ for (const [p, i] of visiblePoints(s.data(), L)) {
726
+ if (!Number.isFinite(p.value)) continue;
727
+ const y = L.y(p.value);
728
+ ctx.fillStyle = p.color ?? fallback;
729
+ ctx.fillRect(
730
+ Math.round(L.x(i) - bw / 2),
731
+ Math.min(y, base),
732
+ bw,
733
+ Math.max(1, Math.abs(base - y))
734
+ );
735
+ }
736
+ }
737
+ function paintPriceLines(ctx, s, L) {
738
+ if (!s.visible) return;
739
+ ctx.font = `11px ${L.theme.font}`;
740
+ ctx.textBaseline = "bottom";
741
+ ctx.textAlign = "right";
742
+ for (const l of s.lines) {
743
+ const o = l.opts;
744
+ const y = Math.round(L.y(o.price)) + 0.5;
745
+ if (y < 0 || y > L.plotH) continue;
746
+ const w = o.width ?? 1;
747
+ ctx.strokeStyle = o.color ?? L.theme.muted;
748
+ ctx.lineWidth = w;
749
+ ctx.setLineDash(dash(o.style, w));
750
+ ctx.beginPath();
751
+ ctx.moveTo(0, y);
752
+ ctx.lineTo(L.plotW, y);
753
+ ctx.stroke();
754
+ if (o.title && o.axisLabel === false) {
755
+ ctx.setLineDash([]);
756
+ ctx.fillStyle = o.color ?? L.theme.muted;
757
+ ctx.fillText(o.title, L.plotW - 6, y - 2);
758
+ }
759
+ }
760
+ const lastP = lastPoint(s, L.theme);
761
+ if (lastP && s.opts.lastPriceLine === true) {
762
+ const y = Math.round(L.y(lastP.value)) + 0.5;
763
+ ctx.strokeStyle = lastP.color;
764
+ ctx.lineWidth = 1;
765
+ ctx.setLineDash([1, 2]);
766
+ ctx.beginPath();
767
+ ctx.moveTo(0, y);
768
+ ctx.lineTo(L.plotW, y);
769
+ ctx.stroke();
770
+ }
771
+ ctx.setLineDash([]);
772
+ ctx.lineWidth = 1;
773
+ ctx.textAlign = "left";
774
+ }
775
+ function contrast(color) {
776
+ let r = 0;
777
+ let g = 0;
778
+ let b = 0;
779
+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})/i.exec(color);
780
+ const rgb = /rgba?\(([^)]+)\)/i.exec(color);
781
+ if (hex) {
782
+ const h = hex[1].length === 3 ? [...hex[1]].map((c) => c + c).join("") : hex[1];
783
+ [r, g, b] = [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
784
+ } else if (rgb)
785
+ [r, g, b] = rgb[1].split(",").map((v) => parseFloat(v));
786
+ else return "#ffffff";
787
+ return 0.299 * r + 0.587 * g + 0.114 * b > 150 ? "#000000" : "#ffffff";
788
+ }
789
+ function lastPoint(s, th) {
790
+ const pts = s.data();
791
+ const p = pts[pts.length - 1];
792
+ if (!p) return null;
793
+ if (s.kind === "candles") {
794
+ const b = p;
795
+ const up = b.close >= b.open;
796
+ return {
797
+ value: b.close,
798
+ color: (up ? s.opts.upColor : s.opts.downColor) ?? (up ? th.up : th.down)
799
+ };
800
+ }
801
+ const v = p;
802
+ const color = v.color ?? s.opts.color ?? th.series[0];
803
+ return { value: v.value, color };
804
+ }
805
+ function paintMarkers(ctx, s, L) {
806
+ if (!s.visible || s.markers.length === 0) return;
807
+ const pts = s.data();
808
+ const byTime = new Map(pts.map((p) => [p.time, p]));
809
+ const stack = /* @__PURE__ */ new Map();
810
+ const base = Math.max(7, Math.min(12, L.bw * 0.9));
811
+ ctx.font = `11px ${L.theme.font}`;
812
+ ctx.textAlign = "center";
813
+ for (const m of s.markers) {
814
+ const i = L.at(m.time);
815
+ const p = byTime.get(m.time);
816
+ if (i === void 0 || !p || i < L.first || i > L.last) continue;
817
+ const hiLo = "high" in p ? [p.high, p.low] : [p.value, p.value];
818
+ const key = `${m.time}:${m.position}`;
819
+ const off = stack.get(key) ?? 0;
820
+ const size = base * (m.size ?? 1);
821
+ const used = paintMarker(ctx, m, L.x(i), hiLo, L, size, off);
822
+ stack.set(key, off + used);
823
+ }
824
+ ctx.textAlign = "left";
825
+ }
826
+ function paintMarker(ctx, m, cx, [high, low], L, size, off) {
827
+ const color = m.color ?? L.theme.accent;
828
+ const above = m.position === "above";
829
+ const anchor = m.position === "inside" ? L.y(high) : above ? L.y(high) - 4 : L.y(low) + 4;
830
+ const dir = above ? -1 : 1;
831
+ const start = anchor + dir * off;
832
+ const cy = m.position === "inside" ? anchor : start + dir * size / 2;
833
+ ctx.fillStyle = color;
834
+ if (size >= 3) shape2(ctx, m.shape, cx, cy, size);
835
+ let used = size + 2;
836
+ if (m.text) {
837
+ ctx.textBaseline = above ? "bottom" : "top";
838
+ const ty = m.position === "inside" ? cy - size : start + dir * (size + 2);
839
+ ctx.fillText(m.text, cx, ty);
840
+ used += 13;
841
+ }
842
+ return used;
843
+ }
844
+ function shape2(ctx, kind, cx, cy, s) {
845
+ const h = s / 2;
846
+ ctx.beginPath();
847
+ if (kind === "circle") ctx.arc(cx, cy, h * 0.8, 0, Math.PI * 2);
848
+ else if (kind === "square") ctx.rect(cx - h * 0.8, cy - h * 0.8, h * 1.6, h * 1.6);
849
+ else {
850
+ const d = kind === "arrow_up" ? -1 : 1;
851
+ ctx.moveTo(cx, cy + d * h);
852
+ ctx.lineTo(cx - h, cy);
853
+ ctx.lineTo(cx - h * 0.35, cy);
854
+ ctx.lineTo(cx - h * 0.35, cy - d * h);
855
+ ctx.lineTo(cx + h * 0.35, cy - d * h);
856
+ ctx.lineTo(cx + h * 0.35, cy);
857
+ ctx.lineTo(cx + h, cy);
858
+ ctx.closePath();
859
+ }
860
+ ctx.fill();
861
+ }
862
+
863
+ // src/series/axes.ts
864
+ var MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ");
865
+ var DAY = 864e5;
866
+ function priceTicks(lo, hi, plotH, decimals) {
867
+ const step = niceStep(hi - lo, Math.max(2, Math.floor(plotH / 50)));
868
+ const ticks = [];
869
+ for (let p = Math.ceil(lo / step) * step; p <= hi; p += step) ticks.push(p);
870
+ return { ticks, dec: decimals ?? decimalsFor(step) };
871
+ }
872
+ var STEPS = [
873
+ 1,
874
+ 5,
875
+ 10,
876
+ 15,
877
+ 30,
878
+ 60,
879
+ 120,
880
+ 300,
881
+ 600,
882
+ 900,
883
+ 1800,
884
+ 3600,
885
+ 7200,
886
+ 10800,
887
+ 14400,
888
+ 21600,
889
+ 43200,
890
+ 86400,
891
+ 172800,
892
+ 604800,
893
+ 2592e3,
894
+ 7776e3,
895
+ 31536e3
896
+ ].map((x) => x * 1e3);
897
+ function timeTicks(L, tl) {
898
+ const want = 90 / L.bw * tl.step();
899
+ const period = STEPS.find((p) => p >= want) ?? STEPS[STEPS.length - 1];
900
+ const out = [];
901
+ let prev = null;
902
+ for (let i = Math.max(0, L.first - 1); i <= L.last; i++) {
903
+ const t = tl.times[i];
904
+ if (t === void 0) continue;
905
+ const slot = Math.floor(t / period);
906
+ if (prev !== null && slot !== prev && i >= L.first) out.push(i);
907
+ prev = slot;
908
+ }
909
+ return out;
910
+ }
911
+ var pad = (n) => String(n).padStart(2, "0");
912
+ function dayLabel(d) {
913
+ return d.getUTCMonth() === 0 && d.getUTCDate() === 1 ? String(d.getUTCFullYear()) : `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}`;
914
+ }
915
+ function timeText(t, prev, step, o) {
916
+ const d = new Date(t);
917
+ const newDay = prev === null || Math.floor(prev / DAY) !== Math.floor(t / DAY);
918
+ if (!o.timeVisible || step >= DAY || newDay && t % DAY === 0) return dayLabel(d);
919
+ const clock = `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`;
920
+ return o.secondsVisible ? `${clock}:${pad(d.getUTCSeconds())}` : clock;
921
+ }
922
+ function fullTime(t, o) {
923
+ const d = new Date(t);
924
+ const date = `${pad(d.getUTCDate())} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
925
+ if (!o.timeVisible) return date;
926
+ const s = o.secondsVisible ? `:${pad(d.getUTCSeconds())}` : "";
927
+ return `${date} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}${s}`;
928
+ }
929
+ function paintGrid(ctx, L, ticks, times, o) {
930
+ if (o.grid === "none") return;
931
+ ctx.strokeStyle = L.theme.grid;
932
+ ctx.lineWidth = 1;
933
+ ctx.setLineDash(o.grid === "dotted" ? [1, 3] : []);
934
+ ctx.beginPath();
935
+ for (const p of ticks) {
936
+ const y = Math.round(L.y(p)) + 0.5;
937
+ ctx.moveTo(0, y);
938
+ ctx.lineTo(L.plotW, y);
939
+ }
940
+ for (const i of times) {
941
+ const x = Math.round(L.x(i)) + 0.5;
942
+ ctx.moveTo(x, 0);
943
+ ctx.lineTo(x, L.plotH);
944
+ }
945
+ ctx.stroke();
946
+ ctx.setLineDash([]);
947
+ }
948
+ var LABEL_H = 18;
949
+ function spreadLabels(ys, bottom = Infinity, h = LABEL_H) {
950
+ const order = ys.map((y, i) => ({ y, i })).sort((a, b) => a.y - b.y);
951
+ const pos = order.map((o) => o.y);
952
+ for (let k = 1; k < pos.length; k++) pos[k] = Math.max(pos[k], pos[k - 1] + h);
953
+ let ceil = bottom;
954
+ for (let k = pos.length - 1; k >= 0; k--) {
955
+ pos[k] = Math.min(pos[k], ceil);
956
+ ceil = pos[k] - h;
957
+ }
958
+ const out = new Array(ys.length);
959
+ order.forEach((o, k) => out[o.i] = pos[k]);
960
+ return out;
961
+ }
962
+ function axisLabel(ctx, L, y, text, bg, fg = contrast(bg)) {
963
+ if (y < -LABEL_H / 2 || y > L.plotH + LABEL_H / 2) return;
964
+ ctx.fillStyle = bg;
965
+ ctx.fillRect(L.plotW, Math.round(y) - 9, L.width - L.plotW, LABEL_H);
966
+ ctx.fillStyle = fg;
967
+ ctx.textBaseline = "middle";
968
+ ctx.fillText(text, L.plotW + 6, Math.round(y));
969
+ }
970
+ function titleBox(ctx, L, y, title, bg) {
971
+ const w = ctx.measureText(title).width + 10;
972
+ ctx.fillStyle = bg;
973
+ ctx.fillRect(L.plotW - w - 2, Math.round(y) - 9, w, LABEL_H);
974
+ ctx.fillStyle = contrast(bg);
975
+ ctx.textBaseline = "middle";
976
+ ctx.fillText(title, L.plotW - w + 3, Math.round(y));
977
+ }
978
+ function collectLabels(series, L, dec) {
979
+ const out = [];
980
+ for (const s of series) {
981
+ if (!s.visible) continue;
982
+ const d = s.opts.priceDecimals ?? dec;
983
+ for (const l of s.lines) {
984
+ if (l.opts.axisLabel === false) continue;
985
+ const bg = l.opts.color ?? L.theme.muted;
986
+ out.push({
987
+ y: L.y(l.opts.price),
988
+ text: formatNumber(l.opts.price, d),
989
+ bg,
990
+ title: l.opts.title
991
+ });
992
+ }
993
+ const last = s.opts.lastValueLabel !== false ? lastPoint(s, L.theme) : null;
994
+ if (last) out.push({ y: L.y(last.value), text: formatNumber(last.value, d), bg: last.color });
995
+ }
996
+ return out.filter((l) => l.y >= -LABEL_H && l.y <= L.plotH + LABEL_H);
997
+ }
998
+ function paintPriceAxis(ctx, L, series, ticks, dec) {
999
+ const th = L.theme;
1000
+ ctx.fillStyle = th.bg;
1001
+ ctx.fillRect(L.plotW, 0, L.width - L.plotW, L.height);
1002
+ ctx.strokeStyle = th.grid;
1003
+ ctx.beginPath();
1004
+ ctx.moveTo(L.plotW + 0.5, 0);
1005
+ ctx.lineTo(L.plotW + 0.5, L.plotH);
1006
+ ctx.stroke();
1007
+ ctx.font = `11px ${th.mono}`;
1008
+ ctx.textBaseline = "middle";
1009
+ ctx.fillStyle = th.muted;
1010
+ for (const p of ticks) ctx.fillText(formatNumber(p, dec), L.plotW + 6, L.y(p));
1011
+ const labels = collectLabels(series, L, dec);
1012
+ const ys = spreadLabels(
1013
+ labels.map((l) => l.y),
1014
+ L.plotH - LABEL_H / 2
1015
+ );
1016
+ labels.forEach((l, i) => {
1017
+ if (l.title) titleBox(ctx, L, ys[i], l.title, l.bg);
1018
+ axisLabel(ctx, L, ys[i], l.text, l.bg);
1019
+ });
1020
+ }
1021
+ function paintTimeAxis(ctx, L, tl, ticks, o) {
1022
+ const th = L.theme;
1023
+ ctx.fillStyle = th.bg;
1024
+ ctx.fillRect(0, L.plotH, L.width, L.height - L.plotH);
1025
+ ctx.strokeStyle = th.grid;
1026
+ ctx.beginPath();
1027
+ ctx.moveTo(0, L.plotH + 0.5);
1028
+ ctx.lineTo(L.width, L.plotH + 0.5);
1029
+ ctx.stroke();
1030
+ ctx.font = `11px ${th.font}`;
1031
+ ctx.textBaseline = "middle";
1032
+ ctx.textAlign = "center";
1033
+ ctx.fillStyle = th.muted;
1034
+ const step = tl.step();
1035
+ let prev = ticks[0] !== void 0 ? tl.toTime(ticks[0] - 1) : null;
1036
+ const cy = L.plotH + (L.height - L.plotH) / 2;
1037
+ for (const i of ticks) {
1038
+ const t = tl.toTime(i);
1039
+ if (t === null) continue;
1040
+ const x = L.x(i);
1041
+ if (x > 20 && x < L.plotW - 20) ctx.fillText(timeText(t, prev, step, o), x, cy);
1042
+ prev = t;
1043
+ }
1044
+ ctx.textAlign = "left";
1045
+ if (o.timeLabel) ctx.fillText(o.timeLabel, L.plotW + 6, cy);
1046
+ }
1047
+ function paintCrosshair(ctx, L, tl, hover, price, dec, o) {
1048
+ const th = L.theme;
1049
+ const x = Math.round(L.x(hover.index)) + 0.5;
1050
+ ctx.strokeStyle = th.muted;
1051
+ ctx.lineWidth = 1;
1052
+ ctx.setLineDash([4, 4]);
1053
+ ctx.beginPath();
1054
+ ctx.moveTo(x, 0);
1055
+ ctx.lineTo(x, L.plotH);
1056
+ if (hover.y >= 0 && hover.y <= L.plotH) {
1057
+ ctx.moveTo(0, Math.round(hover.y) + 0.5);
1058
+ ctx.lineTo(L.plotW, Math.round(hover.y) + 0.5);
1059
+ }
1060
+ ctx.stroke();
1061
+ ctx.setLineDash([]);
1062
+ ctx.font = `11px ${th.mono}`;
1063
+ axisLabel(ctx, L, hover.y, formatNumber(price, dec), th.grid, th.text);
1064
+ const t = tl.toTime(hover.index);
1065
+ if (t === null) return;
1066
+ const text = fullTime(t, o);
1067
+ const w = ctx.measureText(text).width + 12;
1068
+ const left = Math.max(0, Math.min(L.plotW - w, x - w / 2));
1069
+ ctx.fillStyle = th.grid;
1070
+ ctx.fillRect(left, L.plotH + 1, w, L.height - L.plotH - 1);
1071
+ ctx.fillStyle = th.text;
1072
+ ctx.textBaseline = "middle";
1073
+ ctx.fillText(text, left + 6, L.plotH + (L.height - L.plotH) / 2);
1074
+ }
1075
+
1076
+ // src/series/frame.ts
1077
+ function priceRange(series, tl, first, last) {
1078
+ let lo = Infinity;
1079
+ let hi = -Infinity;
1080
+ for (const s of series) {
1081
+ if (!s.visible) continue;
1082
+ let slo = Infinity;
1083
+ let shi = -Infinity;
1084
+ for (const p of s.data()) {
1085
+ const i = tl.exact(p.time);
1086
+ if (i === void 0 || i < first || i > last) continue;
1087
+ const [a, b] = s.span(p);
1088
+ if (Number.isFinite(a) && a < slo) slo = a;
1089
+ if (Number.isFinite(b) && b > shi) shi = b;
1090
+ }
1091
+ const base = slo <= shi ? [slo, shi] : null;
1092
+ const r = s.opts.autoscale ? s.opts.autoscale(base) : base;
1093
+ if (!r) continue;
1094
+ lo = Math.min(lo, r[0]);
1095
+ hi = Math.max(hi, r[1]);
1096
+ }
1097
+ if (lo === Infinity) return null;
1098
+ if (lo === hi) return [lo - 1, hi + 1];
1099
+ return [lo, hi];
1100
+ }
1101
+ function makeLayout(st, scale) {
1102
+ const plotW = Math.max(0, st.width - st.axisW);
1103
+ const plotH = Math.max(0, st.height - st.axisH);
1104
+ const { end, bw } = st.view;
1105
+ const n = st.timeline.length;
1106
+ const first = Math.max(0, Math.floor(end - plotW / bw));
1107
+ const last = Math.min(n - 1, Math.ceil(end));
1108
+ return {
1109
+ width: st.width,
1110
+ height: st.height,
1111
+ plotW,
1112
+ plotH,
1113
+ bw,
1114
+ first,
1115
+ last,
1116
+ x: (i) => plotW - (end - i + 0.5) * bw,
1117
+ y: (p) => scale.top + (scale.hi - p) / (scale.hi - scale.lo) * scale.inner,
1118
+ at: (t) => st.timeline.exact(t),
1119
+ theme: st.theme
1120
+ };
1121
+ }
1122
+ function makeScale(st, prev) {
1123
+ const plotW = Math.max(0, st.width - st.axisW);
1124
+ const plotH = Math.max(0, st.height - st.axisH);
1125
+ const first = Math.max(0, Math.floor(st.view.end - plotW / st.view.bw));
1126
+ const last = Math.min(st.timeline.length - 1, Math.ceil(st.view.end));
1127
+ const r = priceRange(st.series, st.timeline, first, last);
1128
+ const [lo, hi] = r ?? (prev ? [prev.lo, prev.hi] : [0, 1]);
1129
+ const top = plotH * 0.2;
1130
+ return { lo, hi, top, inner: Math.max(1, plotH - top - plotH * 0.1) };
1131
+ }
1132
+ function paintFrame(ctx, st, scale) {
1133
+ const L = makeLayout(st, scale);
1134
+ ctx.clearRect(0, 0, st.width, st.height);
1135
+ ctx.fillStyle = st.theme.bg;
1136
+ ctx.fillRect(0, 0, st.width, st.height);
1137
+ const decimals = st.axis.priceDecimals ?? st.series.find((s) => s.visible)?.opts.priceDecimals;
1138
+ const { ticks, dec } = priceTicks(scale.lo, scale.hi, L.plotH, decimals);
1139
+ const times = timeTicks(L, st.timeline);
1140
+ paintGrid(ctx, L, ticks, times, st.axis);
1141
+ ctx.save();
1142
+ ctx.beginPath();
1143
+ ctx.rect(0, 0, L.plotW, L.plotH);
1144
+ ctx.clip();
1145
+ const size = { width: L.plotW, height: L.plotH };
1146
+ const run = (o) => {
1147
+ ctx.save();
1148
+ o.draw(ctx, size);
1149
+ ctx.restore();
1150
+ };
1151
+ for (const o of st.overlays) if (o.zOrder === "bottom") run(o);
1152
+ const order = ["histogram", "candles", "line"];
1153
+ for (const k of order) for (const s of st.series) if (s.kind === k) paintSeries(ctx, s, L);
1154
+ for (const s of st.series) paintMarkers(ctx, s, L);
1155
+ for (const s of st.series) paintPriceLines(ctx, s, L);
1156
+ for (const o of st.overlays) if (o.zOrder !== "bottom") run(o);
1157
+ ctx.restore();
1158
+ paintPriceAxis(ctx, L, st.series, ticks, dec);
1159
+ paintTimeAxis(ctx, L, st.timeline, times, st.axis);
1160
+ if (st.hover) {
1161
+ const price = scale.hi - (st.hover.y - scale.top) / scale.inner * (scale.hi - scale.lo);
1162
+ paintCrosshair(ctx, L, st.timeline, st.hover, price, dec, st.axis);
1163
+ }
1164
+ return L;
1165
+ }
1166
+
1167
+ // src/series/gestures.ts
1168
+ var Gestures = class {
1169
+ constructor(el, t) {
1170
+ this.el = el;
1171
+ this.t = t;
1172
+ __publicField(this, "pointers", /* @__PURE__ */ new Map());
1173
+ __publicField(this, "drag", null);
1174
+ __publicField(this, "pinch", 0);
1175
+ __publicField(this, "off", []);
1176
+ this.on("wheel", (e) => this.wheel(e), { passive: false });
1177
+ this.on("pointerdown", (e) => this.down(e));
1178
+ this.on("pointermove", (e) => this.move(e));
1179
+ this.on("pointerup", (e) => this.up(e));
1180
+ this.on("pointercancel", (e) => this.end(e));
1181
+ this.on("pointerleave", (e) => {
1182
+ if (e.pointerType === "mouse") this.t.hover(null, 0);
1183
+ });
1184
+ }
1185
+ on(type, fn, opts) {
1186
+ this.el.addEventListener(type, fn, opts);
1187
+ this.off.push(() => this.el.removeEventListener(type, fn, opts));
1188
+ }
1189
+ pos(e) {
1190
+ const r = this.el.getBoundingClientRect();
1191
+ return { x: e.clientX - r.left, y: e.clientY - r.top };
1192
+ }
1193
+ wheel(e) {
1194
+ if (!this.t.enabled()) return;
1195
+ e.preventDefault();
1196
+ const { x } = this.pos(e);
1197
+ if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) this.t.pan(this.t.viewEnd(), -e.deltaX);
1198
+ else this.t.zoom(Math.exp(-e.deltaY * 2e-3), x);
1199
+ }
1200
+ down(e) {
1201
+ const p = this.pos(e);
1202
+ this.pointers.set(e.pointerId, p);
1203
+ this.el.setPointerCapture?.(e.pointerId);
1204
+ if (this.pointers.size === 2) {
1205
+ this.drag = null;
1206
+ this.pinch = this.spread();
1207
+ } else this.drag = { x: p.x, end: this.t.viewEnd(), moved: false };
1208
+ }
1209
+ move(e) {
1210
+ const p = this.pos(e);
1211
+ if (this.pointers.has(e.pointerId)) this.pointers.set(e.pointerId, p);
1212
+ if (this.pointers.size === 2 && this.pinch > 0) {
1213
+ const now = this.spread();
1214
+ if (this.t.enabled() && now > 0) {
1215
+ const mid = [...this.pointers.values()].reduce((a, q) => a + q.x, 0) / 2;
1216
+ this.t.zoom(now / this.pinch, mid);
1217
+ }
1218
+ this.pinch = now;
1219
+ return;
1220
+ }
1221
+ if (this.drag) {
1222
+ const dx = p.x - this.drag.x;
1223
+ if (Math.abs(dx) > 3) this.drag.moved = true;
1224
+ if (this.drag.moved && this.t.enabled()) this.t.pan(this.drag.end, dx);
1225
+ }
1226
+ this.t.hover(p.x, p.y);
1227
+ }
1228
+ up(e) {
1229
+ const p = this.pos(e);
1230
+ if (this.drag && !this.drag.moved && this.pointers.size === 1) this.t.click(p.x, p.y);
1231
+ this.end(e);
1232
+ }
1233
+ end(e) {
1234
+ this.pointers.delete(e.pointerId);
1235
+ this.drag = null;
1236
+ if (this.pointers.size < 2) this.pinch = 0;
1237
+ }
1238
+ spread() {
1239
+ const [a, b] = [...this.pointers.values()];
1240
+ return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
1241
+ }
1242
+ dispose() {
1243
+ for (const f of this.off) f();
1244
+ }
1245
+ };
1246
+
1247
+ // src/series/series.ts
1248
+ var PriceLine = class {
1249
+ constructor(host, opts, owner) {
1250
+ this.host = host;
1251
+ this.opts = opts;
1252
+ this.owner = owner;
1253
+ }
1254
+ update(opts) {
1255
+ this.opts = { ...this.opts, ...opts };
1256
+ this.host.redraw();
1257
+ }
1258
+ remove() {
1259
+ this.owner.removePriceLine(this);
1260
+ }
1261
+ };
1262
+ function upsert(list, p) {
1263
+ const last = list[list.length - 1];
1264
+ if (!last || p.time > last.time) {
1265
+ list.push(p);
1266
+ return;
1267
+ }
1268
+ let lo = 0;
1269
+ let hi = list.length;
1270
+ while (lo < hi) {
1271
+ const mid = lo + hi >> 1;
1272
+ if (list[mid].time < p.time) lo = mid + 1;
1273
+ else hi = mid;
1274
+ }
1275
+ if (list[lo]?.time === p.time) list[lo] = p;
1276
+ else list.splice(lo, 0, p);
1277
+ }
1278
+ var Series = class {
1279
+ constructor(host, opts) {
1280
+ this.host = host;
1281
+ this.opts = opts;
1282
+ __publicField(this, "points", []);
1283
+ __publicField(this, "lines", []);
1284
+ __publicField(this, "markers", []);
1285
+ }
1286
+ /** Replaces the data (any order; sorted by time here). */
1287
+ setData(points) {
1288
+ this.points = [...points].sort((a, b) => a.time - b.time);
1289
+ this.host.dataChanged();
1290
+ }
1291
+ /** Adds a point or replaces the one with the same time. */
1292
+ update(point) {
1293
+ upsert(this.points, point);
1294
+ this.host.dataChanged();
1295
+ }
1296
+ data() {
1297
+ return this.points;
1298
+ }
1299
+ times() {
1300
+ return this.points.map((p) => p.time);
1301
+ }
1302
+ setOptions(opts) {
1303
+ this.opts = { ...this.opts, ...opts };
1304
+ this.host.redraw();
1305
+ }
1306
+ get visible() {
1307
+ return this.opts.visible !== false;
1308
+ }
1309
+ addPriceLine(opts) {
1310
+ const l = new PriceLine(this.host, opts, this);
1311
+ this.lines.push(l);
1312
+ this.host.redraw();
1313
+ return l;
1314
+ }
1315
+ removePriceLine(l) {
1316
+ const i = this.lines.indexOf(l);
1317
+ if (i >= 0) this.lines.splice(i, 1);
1318
+ this.host.redraw();
1319
+ }
1320
+ /** Replaces the markers. */
1321
+ setMarkers(markers) {
1322
+ this.markers = [...markers].sort((a, b) => a.time - b.time);
1323
+ this.host.redraw();
1324
+ }
1325
+ priceToY(price) {
1326
+ return this.host.priceToY(price);
1327
+ }
1328
+ yToPrice(y) {
1329
+ return this.host.yToPrice(y);
1330
+ }
1331
+ };
1332
+ var CandleSeries = class extends Series {
1333
+ constructor() {
1334
+ super(...arguments);
1335
+ __publicField(this, "kind", "candles");
1336
+ }
1337
+ span(p) {
1338
+ return [p.low, p.high];
1339
+ }
1340
+ value(p) {
1341
+ return p.close;
1342
+ }
1343
+ };
1344
+ var LineSeriesApi = class extends Series {
1345
+ constructor() {
1346
+ super(...arguments);
1347
+ __publicField(this, "kind", "line");
1348
+ }
1349
+ span(p) {
1350
+ return [p.value, p.value];
1351
+ }
1352
+ value(p) {
1353
+ return p.value;
1354
+ }
1355
+ };
1356
+ var HistogramSeries = class extends Series {
1357
+ constructor() {
1358
+ super(...arguments);
1359
+ __publicField(this, "kind", "histogram");
1360
+ }
1361
+ span(p) {
1362
+ const base = this.opts.base ?? 0;
1363
+ return [Math.min(base, p.value), Math.max(base, p.value)];
1364
+ }
1365
+ value(p) {
1366
+ return p.value;
1367
+ }
1368
+ };
1369
+
1370
+ // src/series/timeline.ts
1371
+ var Timeline = class {
1372
+ constructor() {
1373
+ __publicField(this, "times", []);
1374
+ __publicField(this, "index", /* @__PURE__ */ new Map());
1375
+ }
1376
+ /** Rebuilds from the times of every series. */
1377
+ rebuild(lists) {
1378
+ const all = /* @__PURE__ */ new Set();
1379
+ for (const l of lists) for (const t of l) all.add(t);
1380
+ this.times = [...all].sort((a, b) => a - b);
1381
+ this.index = new Map(this.times.map((t, i) => [t, i]));
1382
+ }
1383
+ get length() {
1384
+ return this.times.length;
1385
+ }
1386
+ /** Index of an exact time, or undefined. */
1387
+ exact(t) {
1388
+ return this.index.get(t);
1389
+ }
1390
+ /** Typical bar interval: the last gap, or 60 s with fewer than two bars. */
1391
+ step() {
1392
+ const n = this.times.length;
1393
+ return n >= 2 ? this.times[n - 1] - this.times[n - 2] : 6e4;
1394
+ }
1395
+ /** Logical index of a time: exact, interpolated between bars, or extrapolated outside. */
1396
+ toIndex(t) {
1397
+ const ts = this.times;
1398
+ const n = ts.length;
1399
+ if (n === 0) return null;
1400
+ const hit = this.index.get(t);
1401
+ if (hit !== void 0) return hit;
1402
+ if (t < ts[0]) return n >= 2 ? (t - ts[0]) / (ts[1] - ts[0]) : -1;
1403
+ if (t > ts[n - 1]) return n - 1 + (t - ts[n - 1]) / this.step();
1404
+ let lo = 0;
1405
+ let hi = n - 1;
1406
+ while (hi - lo > 1) {
1407
+ const mid = lo + hi >> 1;
1408
+ if (ts[mid] <= t) lo = mid;
1409
+ else hi = mid;
1410
+ }
1411
+ return lo + (t - ts[lo]) / (ts[hi] - ts[lo]);
1412
+ }
1413
+ /** Time of a logical index (rounded), extrapolated past the ends. */
1414
+ toTime(i) {
1415
+ const ts = this.times;
1416
+ const n = ts.length;
1417
+ if (n === 0) return null;
1418
+ const k = Math.round(i);
1419
+ if (k >= 0 && k < n) return ts[k];
1420
+ if (k < 0) return ts[0] + k * (n >= 2 ? ts[1] - ts[0] : 6e4);
1421
+ return ts[n - 1] + (k - n + 1) * this.step();
1422
+ }
1423
+ };
1424
+
1425
+ // src/series/time-chart.ts
1426
+ var MIN_BW = 1;
1427
+ var MAX_BW = 60;
1428
+ var TimeChart = class {
1429
+ constructor(hostEl, opts = {}) {
1430
+ this.opts = opts;
1431
+ __publicField(this, "el");
1432
+ __publicField(this, "canvas");
1433
+ __publicField(this, "legendEl");
1434
+ __publicField(this, "series", []);
1435
+ __publicField(this, "overlays", []);
1436
+ __publicField(this, "timeline", new Timeline());
1437
+ __publicField(this, "view");
1438
+ __publicField(this, "scale", null);
1439
+ __publicField(this, "hover", null);
1440
+ __publicField(this, "clicks", /* @__PURE__ */ new Set());
1441
+ __publicField(this, "rangeSubs", /* @__PURE__ */ new Set());
1442
+ __publicField(this, "lastRange", "");
1443
+ __publicField(this, "raf", 0);
1444
+ __publicField(this, "resize");
1445
+ __publicField(this, "host");
1446
+ __publicField(this, "gestures");
1447
+ this.view = { end: 0, bw: opts.barSpacing ?? 8 };
1448
+ this.el = document.createElement("div");
1449
+ this.el.className = "glot-chart";
1450
+ this.el.style.cssText = "position:relative;width:100%;height:100%;overflow:hidden;touch-action:none";
1451
+ this.canvas = document.createElement("canvas");
1452
+ this.canvas.style.cssText = "position:absolute;inset:0;width:100%;height:100%;cursor:crosshair";
1453
+ this.canvas.setAttribute("role", "img");
1454
+ this.legendEl = document.createElement("div");
1455
+ this.legendEl.className = "glot-chart-legend";
1456
+ this.legendEl.hidden = opts.legend === false;
1457
+ this.el.append(this.canvas, this.legendEl);
1458
+ if (opts.attributionLogo !== false) this.el.append(attributionLink(opts));
1459
+ injectStyles(hostEl.ownerDocument);
1460
+ hostEl.append(this.el);
1461
+ this.host = {
1462
+ dataChanged: () => this.dataChanged(),
1463
+ redraw: () => this.invalidate(),
1464
+ priceToY: (p) => this.priceToY(p),
1465
+ yToPrice: (y) => this.yToPrice(y)
1466
+ };
1467
+ this.gestures = new Gestures(this.canvas, {
1468
+ enabled: () => this.opts.interactive !== false,
1469
+ pan: (start, dx) => this.panTo(start - dx / this.view.bw),
1470
+ viewEnd: () => this.view.end,
1471
+ zoom: (factor, x) => this.zoomAt(factor, x),
1472
+ hover: (x, y) => this.setHover(x, y),
1473
+ click: (x, y) => this.emitClick(x, y)
1474
+ });
1475
+ this.resize = new ResizeObserver(() => this.invalidate());
1476
+ this.resize.observe(this.el);
1477
+ }
1478
+ addCandles(opts = {}) {
1479
+ return this.add(new CandleSeries(this.host, { lastPriceLine: true, ...opts }));
1480
+ }
1481
+ addLine(opts = {}) {
1482
+ return this.add(new LineSeriesApi(this.host, opts));
1483
+ }
1484
+ addHistogram(opts = {}) {
1485
+ return this.add(new HistogramSeries(this.host, opts));
1486
+ }
1487
+ add(s) {
1488
+ this.series.push(s);
1489
+ this.dataChanged();
1490
+ return s;
1491
+ }
1492
+ removeSeries(s) {
1493
+ this.series = this.series.filter((x) => x !== s);
1494
+ this.dataChanged();
1495
+ }
1496
+ /** Adds a host drawing; returns a function that removes it. */
1497
+ addOverlay(o) {
1498
+ this.overlays.push(o);
1499
+ this.invalidate();
1500
+ return () => {
1501
+ this.overlays = this.overlays.filter((x) => x !== o);
1502
+ this.invalidate();
1503
+ };
1504
+ }
1505
+ setOptions(opts) {
1506
+ const n = this.timeline.length;
1507
+ if (opts.rightOffset !== void 0 && opts.rightOffset !== this.opts.rightOffset && n) {
1508
+ this.view.end = n - 1 + opts.rightOffset;
1509
+ }
1510
+ if (opts.barSpacing !== void 0) this.view.bw = clampBw(opts.barSpacing);
1511
+ if (opts.legend !== void 0) this.legendEl.hidden = opts.legend === false;
1512
+ this.opts = { ...this.opts, ...opts };
1513
+ this.invalidate();
1514
+ }
1515
+ /** Current options, with `barSpacing` and `rightOffset` as the view has them now. */
1516
+ options() {
1517
+ return { ...this.opts, barSpacing: this.view.bw, rightOffset: this.opts.rightOffset ?? 6 };
1518
+ }
1519
+ /** Width and height of the plot area (without the axes), in CSS pixels. */
1520
+ plotSize() {
1521
+ const w = this.el.clientWidth - (this.opts.priceAxisWidth ?? 72);
1522
+ const h = this.el.clientHeight - (this.opts.timeAxisHeight ?? 24);
1523
+ return { width: Math.max(0, w), height: Math.max(0, h) };
1524
+ }
1525
+ // Coordinates -------------------------------------------------------------------------------
1526
+ indexToX(i) {
1527
+ return this.plotSize().width - (this.view.end - i + 0.5) * this.view.bw;
1528
+ }
1529
+ xToIndex(x) {
1530
+ return this.view.end + 0.5 - (this.plotSize().width - x) / this.view.bw;
1531
+ }
1532
+ timeToX(t) {
1533
+ const i = this.timeline.toIndex(t);
1534
+ return i === null ? null : this.indexToX(i);
1535
+ }
1536
+ xToTime(x) {
1537
+ return this.timeline.toTime(this.xToIndex(x));
1538
+ }
1539
+ /** Index of an exact time on the shared time axis, or null. */
1540
+ timeToIndex(t) {
1541
+ return this.timeline.exact(t) ?? null;
1542
+ }
1543
+ priceToY(p) {
1544
+ const s = this.currentScale();
1545
+ if (!s) return null;
1546
+ return s.top + (s.hi - p) / (s.hi - s.lo) * s.inner;
1547
+ }
1548
+ yToPrice(y) {
1549
+ const s = this.currentScale();
1550
+ if (!s) return null;
1551
+ return s.hi - (y - s.top) / s.inner * (s.hi - s.lo);
1552
+ }
1553
+ // Visible range -----------------------------------------------------------------------------
1554
+ getVisibleIndexRange() {
1555
+ if (!this.timeline.length) return null;
1556
+ const w = this.plotSize().width;
1557
+ return { from: this.view.end - w / this.view.bw + 1, to: this.view.end };
1558
+ }
1559
+ setVisibleIndexRange(r) {
1560
+ const w = this.plotSize().width;
1561
+ const count = Math.max(1, r.to - r.from + 1);
1562
+ if (w > 0) this.view.bw = clampBw(w / count);
1563
+ this.view.end = r.to;
1564
+ this.invalidate();
1565
+ }
1566
+ /** First and last visible bar times inside the data, or null without data. */
1567
+ getVisibleRange() {
1568
+ const r = this.getVisibleIndexRange();
1569
+ const n = this.timeline.length;
1570
+ if (!r || !n) return null;
1571
+ const a = Math.min(n - 1, Math.max(0, Math.ceil(r.from)));
1572
+ const b = Math.min(n - 1, Math.max(0, Math.floor(r.to)));
1573
+ return { from: this.timeline.times[a], to: this.timeline.times[b] };
1574
+ }
1575
+ setVisibleRange(r) {
1576
+ const a = this.timeline.toIndex(r.from);
1577
+ const b = this.timeline.toIndex(r.to);
1578
+ if (a === null || b === null) return;
1579
+ this.setVisibleIndexRange({ from: a, to: b });
1580
+ }
1581
+ /** Shows the newest bar with the right offset. */
1582
+ scrollToEnd() {
1583
+ this.view.end = Math.max(0, this.timeline.length - 1) + (this.opts.rightOffset ?? 6);
1584
+ this.invalidate();
1585
+ }
1586
+ /** Fits every bar into the plot. */
1587
+ fitContent() {
1588
+ const n = this.timeline.length;
1589
+ if (n) this.setVisibleIndexRange({ from: 0, to: n - 1 });
1590
+ }
1591
+ /** Calls `cb` when the visible time range changes; returns an unsubscribe function. */
1592
+ onVisibleRangeChange(cb) {
1593
+ this.rangeSubs.add(cb);
1594
+ return () => this.rangeSubs.delete(cb);
1595
+ }
1596
+ /** Calls `cb` on a click (not a drag); returns an unsubscribe function. */
1597
+ onClick(cb) {
1598
+ this.clicks.add(cb);
1599
+ return () => this.clicks.delete(cb);
1600
+ }
1601
+ /** Redraws on the next frame (for example after an overlay's data changed). */
1602
+ invalidate() {
1603
+ this.scale = null;
1604
+ cancelAnimationFrame(this.raf);
1605
+ this.raf = requestAnimationFrame(() => this.draw());
1606
+ }
1607
+ dispose() {
1608
+ this.resize.disconnect();
1609
+ this.gestures.dispose();
1610
+ cancelAnimationFrame(this.raf);
1611
+ this.el.remove();
1612
+ }
1613
+ // Internals ---------------------------------------------------------------------------------
1614
+ dataChanged() {
1615
+ const before = this.timeline.length;
1616
+ const atEnd = this.view.end >= before - 1;
1617
+ this.timeline.rebuild(this.series.map((s) => s.times()));
1618
+ const n = this.timeline.length;
1619
+ if (before === 0 && n > 0) this.view.end = n - 1 + (this.opts.rightOffset ?? 6);
1620
+ else if (atEnd && n > before) this.view.end += n - before;
1621
+ this.canvas.setAttribute("aria-label", `${n} bars`);
1622
+ this.invalidate();
1623
+ }
1624
+ panTo(end) {
1625
+ const n = this.timeline.length;
1626
+ const w = this.plotSize().width / this.view.bw;
1627
+ this.view.end = Math.min(n - 1 + w * 0.8, Math.max(Math.min(n - 1, 2), end));
1628
+ this.invalidate();
1629
+ }
1630
+ zoomAt(factor, x) {
1631
+ const w = this.plotSize().width;
1632
+ const anchor = this.xToIndex(Math.min(x, w));
1633
+ const bw = clampBw(this.view.bw * factor);
1634
+ this.view.end = anchor - 0.5 + (w - Math.min(x, w)) / bw;
1635
+ this.view.bw = bw;
1636
+ this.invalidate();
1637
+ }
1638
+ setHover(x, y) {
1639
+ const n = this.timeline.length;
1640
+ if (x === null || !n || x > this.plotSize().width) this.hover = null;
1641
+ else this.hover = { index: Math.round(this.xToIndex(x) - 0.5), y };
1642
+ this.invalidate();
1643
+ }
1644
+ emitClick(x, y) {
1645
+ const i = Math.round(this.xToIndex(x) - 0.5);
1646
+ const inData = i >= 0 && i < this.timeline.length;
1647
+ const info = {
1648
+ x,
1649
+ y,
1650
+ index: inData ? i : null,
1651
+ time: inData ? this.timeline.times[i] : null,
1652
+ price: this.yToPrice(y)
1653
+ };
1654
+ for (const cb of this.clicks) cb(info);
1655
+ }
1656
+ state() {
1657
+ const o = this.opts;
1658
+ return {
1659
+ width: this.el.clientWidth,
1660
+ height: this.el.clientHeight,
1661
+ axisW: o.priceAxisWidth ?? 72,
1662
+ axisH: o.timeAxisHeight ?? 24,
1663
+ view: this.view,
1664
+ timeline: this.timeline,
1665
+ series: this.series,
1666
+ overlays: this.overlays,
1667
+ theme: readTheme(this.el, o.theme),
1668
+ axis: {
1669
+ grid: o.grid ?? "solid",
1670
+ timeVisible: o.timeVisible !== false,
1671
+ secondsVisible: o.secondsVisible === true,
1672
+ timeLabel: o.timeLabel ?? "UTC",
1673
+ priceDecimals: o.priceDecimals
1674
+ },
1675
+ hover: o.crosshair === false ? null : this.hover
1676
+ };
1677
+ }
1678
+ currentScale() {
1679
+ if (!this.timeline.length) return null;
1680
+ this.scale ?? (this.scale = makeScale(this.state(), null));
1681
+ return this.scale;
1682
+ }
1683
+ draw() {
1684
+ const dpr = window.devicePixelRatio || 1;
1685
+ const w = this.el.clientWidth;
1686
+ const h = this.el.clientHeight;
1687
+ if (w === 0 || h === 0) return;
1688
+ if (this.canvas.width !== Math.round(w * dpr) || this.canvas.height !== Math.round(h * dpr)) {
1689
+ this.canvas.width = Math.round(w * dpr);
1690
+ this.canvas.height = Math.round(h * dpr);
1691
+ }
1692
+ const ctx = this.canvas.getContext("2d");
1693
+ if (!ctx) return;
1694
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
1695
+ const st = this.state();
1696
+ applyThemeVars(this.el, st.theme);
1697
+ this.scale = makeScale(st, this.scale);
1698
+ paintFrame(ctx, st, this.scale);
1699
+ this.renderLegend();
1700
+ this.emitRange();
1701
+ }
1702
+ renderLegend() {
1703
+ if (this.legendEl.hidden) return;
1704
+ const n = this.timeline.length;
1705
+ const i = this.hover && this.hover.index < n ? this.hover.index : n - 1;
1706
+ const t = this.timeline.times[i];
1707
+ if (t === void 0) {
1708
+ this.legendEl.textContent = "";
1709
+ return;
1710
+ }
1711
+ const parts = [];
1712
+ for (const s of this.series) {
1713
+ if (!s.visible) continue;
1714
+ const p = s.data().find((q) => q.time === t);
1715
+ if (!p) continue;
1716
+ const d = s.opts.priceDecimals ?? this.opts.priceDecimals ?? 2;
1717
+ const f = (v) => formatNumber(v, d);
1718
+ if (s.kind === "candles") {
1719
+ const b = p;
1720
+ parts.push(`O ${f(b.open)} H ${f(b.high)} L ${f(b.low)} C ${f(b.close)}`);
1721
+ } else if (s.opts.title) parts.push(`${s.opts.title} ${f(p.value)}`);
1722
+ }
1723
+ this.legendEl.textContent = parts.join(" ");
1724
+ }
1725
+ emitRange() {
1726
+ const r = this.getVisibleRange();
1727
+ const key = r ? `${r.from}:${r.to}` : "";
1728
+ if (key === this.lastRange) return;
1729
+ this.lastRange = key;
1730
+ for (const cb of this.rangeSubs) cb(r);
1731
+ }
1732
+ };
1733
+ function clampBw(bw) {
1734
+ return Math.min(MAX_BW, Math.max(MIN_BW, bw));
1735
+ }
1736
+ function createTimeChart(host, options = {}) {
1737
+ return new TimeChart(host, options);
1738
+ }
1739
+ export {
1740
+ ATTRIBUTION_HREF,
1741
+ ATTRIBUTION_SRC,
1742
+ CandleSeries,
1743
+ GlotChart,
1744
+ HistogramSeries,
1745
+ LineSeriesApi,
1746
+ PriceLine,
1747
+ THEMES,
1748
+ TimeChart,
1749
+ VERSION,
1750
+ barAt,
1751
+ barsFromCsv,
1752
+ bisect,
1753
+ createChart,
1754
+ createTimeChart,
1755
+ decimalsFor,
1756
+ extent,
1757
+ formatNumber,
1758
+ niceStep,
1759
+ readTheme,
1760
+ resolveColor,
1761
+ visibleRange,
1762
+ xOf
1763
+ };