wick-charts 0.7.1 → 0.9.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
@@ -19,6 +19,8 @@ npm install wick-charts
19
19
  - [Candle data](#candle-data)
20
20
  - [Line charts](#line-charts)
21
21
  - [Styling](#styling)
22
+ - [Customizing the hover legend text](#customizing-the-hover-legend-text)
23
+ - [High-DPI displays (devicePixelRatio)](#high-dpi-displays-devicepixelratio)
22
24
  - [Inverting the value axis](#inverting-the-value-axis)
23
25
  - [Reading chart state](#reading-chart-state)
24
26
  - [Setting the visible range](#setting-the-visible-range)
@@ -229,6 +231,83 @@ type-checks `style` against
229
231
  `CandlestickStyle`; the more general `new WickChart(canvas, { type: 'candlestick', style })`
230
232
  also works but doesn't — see "Series types" below for why, if you're curious.
231
233
 
234
+ Every `px` value above (`font.axisSize`/`legendSize`, `axis.priceWidth`/`timeHeight`,
235
+ `crosshair.labelPaddingX`/`labelPaddingY`, `legend.paddingX`/`paddingY`/`cursorGap`, and
236
+ `LineStyle.lineWidth`) is authored in **CSS pixels** — the intuitive "how big should this look
237
+ on screen" unit — regardless of the canvas's actual backing-store resolution. See the next
238
+ section for what that means in practice.
239
+
240
+ ### Customizing the hover legend text
241
+
242
+ `legend` above only styles the tooltip's box (colors, padding, offset) — the *text* inside it
243
+ comes from the active series's `formatLegend`, which candlestick/line both ship with a fixed,
244
+ English, OHLC-shaped default. An app that needs different text — localized labels, or a value
245
+ computed from neighboring points, like percent change against the previous candle — overrides
246
+ it per chart instance via `formatLegend`:
247
+
248
+ ```ts
249
+ const chart = createCandlestickChart(canvas, {
250
+ formatLegend(candle, style, { index, allPoints }) {
251
+ const prev = allPoints[index - 1];
252
+ const change = prev ? (((candle.close - prev.close) / prev.close) * 100).toFixed(2) : null;
253
+ return [
254
+ `시가 ${candle.open.toLocaleString()}`,
255
+ `고가 ${candle.high.toLocaleString()}`,
256
+ `저가 ${candle.low.toLocaleString()}`,
257
+ `종가 ${candle.close.toLocaleString()}${change === null ? '' : ` (${change}%)`}`,
258
+ ];
259
+ },
260
+ });
261
+ ```
262
+
263
+ This replaces the series's `formatLegend` outright for this one chart instance — it doesn't
264
+ merge with the built-in OHLC lines, so return every line you want shown. `allPoints` is every
265
+ point currently loaded (not just visible), the same array a `ChartPlugin` reads through
266
+ `PluginRenderApi.allPoints`; `index` is `candle`'s position in it, so `allPoints[index - 1]` is
267
+ the previous point regardless of where the user has panned/zoomed to.
268
+
269
+ `SeriesDefinition.formatLegend` (what candlestick/line ship with) is a shared default for every
270
+ chart of that *type*; `WickChartOptions.formatLegend` is the per-*instance* override above it —
271
+ reach for the latter for anything that varies by app, session, or locale rather than by chart
272
+ type. `createCandlestickChart`/`createLineChart` type-check `formatLegend`'s `point`/`style`
273
+ against the concrete series, the same way they type-check `style` itself.
274
+
275
+ Return `[]` (or `undefined`) to suppress the built-in tooltip entirely — useful if you'd rather
276
+ draw a completely custom tooltip layout yourself via a [`ChartPlugin`](#extending-plugins),
277
+ using `chart.getHoveredPoint()` to know what's hovered.
278
+
279
+ ### High-DPI displays (devicePixelRatio)
280
+
281
+ The [Quick start](#quick-start) resize snippet sizes the canvas's backing store
282
+ (`canvas.width`/`height`) to `devicePixelRatio` times its CSS display size — the standard
283
+ recipe for a crisp, non-blurry `<canvas>` on a Retina/high-DPI screen. wick-charts detects this
284
+ itself, live, by comparing `canvas.width`/`height` against `canvas.getBoundingClientRect()` on
285
+ every frame — there's no `devicePixelRatio` option to set, and nothing to recompute yourself on
286
+ resize or on a browser zoom change; the chart just reads whatever the canvas's current backing
287
+ store vs. CSS size actually is.
288
+
289
+ Once detected, every CSS-pixel size option listed at the end of the previous section is scaled
290
+ by that ratio before it's used — so `axisSize: 10` always looks like a 10px font on screen,
291
+ whether the backing store is 1x or 3x the CSS size, and you never have to pre-multiply any
292
+ option by `window.devicePixelRatio` yourself. (Colors and tick counts — `priceTickCount`,
293
+ `timeMaxTicks` — aren't sizes and pass through unscaled.)
294
+
295
+ This only reaches what the engine itself draws. A `ChartPlugin` or a custom `SeriesDefinition`
296
+ sets its own canvas properties directly (`ctx.lineWidth`, a font size in `ctx.font`, a marker
297
+ radius), and the engine has no way to know which of those are meant to be sizes — so both
298
+ `PluginRenderApi` and `SeriesDrawContext` carry a `devicePixelRatio` field for exactly this:
299
+ multiply your own literal pixel sizes by it before setting them on `ctx`, the same way the
300
+ built-in line series scales `LineStyle.lineWidth`:
301
+
302
+ ```ts
303
+ // inside a ChartPlugin's draw(api), or a custom SeriesDefinition's draw(context, style)
304
+ ctx.lineWidth = 2 * api.devicePixelRatio; // always ~2 CSS px, not 2 backing-store px
305
+ ```
306
+
307
+ If you never resize the canvas to a scaled backing store at all (`canvas.width` already equals
308
+ its CSS display size, the default for an unstyled `<canvas>`), the ratio is exactly 1 and
309
+ nothing here changes anything.
310
+
232
311
  ### Inverting the value axis
233
312
 
234
313
  `invertValueAxis` mirrors the value axis top-to-bottom — every pane's higher values render
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Ratio between a canvas's backing-store size and its CSS display size —
3
+ * `canvas.width / rect.width` (or `.height`), the same signal
4
+ * `window.devicePixelRatio` gives once a canvas has actually been resized to
5
+ * match it (see the README's "High-DPI displays" section for the resize
6
+ * recipe this reads back). Read live off the canvas and its bounding rect
7
+ * rather than cached anywhere, so a change — a window dragged to a
8
+ * different-DPI monitor, a browser zoom level change, or simply an app
9
+ * resizing the canvas — is picked up on the very next call with no explicit
10
+ * resize notification needed, the same way `ChartRenderer.chartWidth`/
11
+ * `chartHeight` already track `canvas.width`/`height` live instead of
12
+ * caching them at construction.
13
+ *
14
+ * Returns 1 (no scaling) when the CSS size is 0 — an unattached or
15
+ * zero-size canvas — rather than dividing by zero.
16
+ */
17
+ export declare function devicePixelRatio(canvas: HTMLCanvasElement, axis?: 'width' | 'height'): number;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Ratio between a canvas's backing-store size and its CSS display size —
3
+ * `canvas.width / rect.width` (or `.height`), the same signal
4
+ * `window.devicePixelRatio` gives once a canvas has actually been resized to
5
+ * match it (see the README's "High-DPI displays" section for the resize
6
+ * recipe this reads back). Read live off the canvas and its bounding rect
7
+ * rather than cached anywhere, so a change — a window dragged to a
8
+ * different-DPI monitor, a browser zoom level change, or simply an app
9
+ * resizing the canvas — is picked up on the very next call with no explicit
10
+ * resize notification needed, the same way `ChartRenderer.chartWidth`/
11
+ * `chartHeight` already track `canvas.width`/`height` live instead of
12
+ * caching them at construction.
13
+ *
14
+ * Returns 1 (no scaling) when the CSS size is 0 — an unattached or
15
+ * zero-size canvas — rather than dividing by zero.
16
+ */
17
+ export function devicePixelRatio(canvas, axis = 'width') {
18
+ const rect = canvas.getBoundingClientRect();
19
+ const cssSize = axis === 'width' ? rect.width : rect.height;
20
+ const deviceSize = axis === 'width' ? canvas.width : canvas.height;
21
+ return cssSize === 0 ? 1 : deviceSize / cssSize;
22
+ }
package/dist/index.d.ts CHANGED
@@ -2,8 +2,8 @@ import type { DataLoader } from './dataSource.js';
2
2
  import type { ChartPlugin } from './plugins/types.js';
3
3
  import type { CandlestickStyle } from './series/candlestick.js';
4
4
  import type { LineStyle } from './series/line.js';
5
- import type { Candle, LinePoint, PaneOptions, WickChartOptions, SeriesPoint, ValueRange, WickTime } from './types.js';
6
- export type { BusinessDay, Candle, LinePoint, PaneOptions, WickChartOptions, WickTime, SeriesPoint, UnixMillis, ValueRange, } from './types.js';
5
+ import type { Candle, LegendFormatContext, LinePoint, PaneOptions, WickChartOptions, SeriesPoint, ValueRange, WickTime } from './types.js';
6
+ export type { BusinessDay, Candle, LegendFormatContext, LinePoint, PaneOptions, WickChartOptions, WickTime, SeriesPoint, UnixMillis, ValueRange, } from './types.js';
7
7
  export type { DataLoader, DataRequest } from './dataSource.js';
8
8
  export type { ChartPlugin, ChartPointerEvent, PluginRenderApi } from './plugins/types.js';
9
9
  export { distanceToSegment, hitTestPoint, hitTestSegment } from './hitTest.js';
@@ -326,8 +326,13 @@ export declare class WickChart<TPoint extends SeriesPoint = Candle> {
326
326
  * one) rather than widening `WickChartOptions` itself — that keeps every
327
327
  * series's style shape independent of every other's.
328
328
  */
329
- export declare function createCandlestickChart(canvas: HTMLCanvasElement, options?: Omit<WickChartOptions, 'type' | 'style'> & {
329
+ export declare function createCandlestickChart(canvas: HTMLCanvasElement, options?: Omit<WickChartOptions, 'type' | 'style' | 'formatLegend'> & {
330
330
  style?: Partial<CandlestickStyle>;
331
+ /** Same override as `WickChartOptions.formatLegend`, with `point`/`style`/
332
+ * `context` narrowed to this series's own types instead of the general
333
+ * (unchecked) `SeriesPoint`/`unknown` shape `WickChartOptions` itself
334
+ * allows — see its doc comment for what this is for. */
335
+ formatLegend?(point: Candle, style: CandlestickStyle, context: LegendFormatContext<Candle>): string[];
331
336
  }): WickChart<Candle>;
332
337
  /**
333
338
  * The second series type's equivalent of `createCandlestickChart` above —
@@ -336,6 +341,9 @@ export declare function createCandlestickChart(canvas: HTMLCanvasElement, option
336
341
  * `Record<string, unknown>` `WickChartOptions.style` allows for `new
337
342
  * WickChart(canvas, { type: 'line', style })`.
338
343
  */
339
- export declare function createLineChart(canvas: HTMLCanvasElement, options?: Omit<WickChartOptions, 'type' | 'style'> & {
344
+ export declare function createLineChart(canvas: HTMLCanvasElement, options?: Omit<WickChartOptions, 'type' | 'style' | 'formatLegend'> & {
340
345
  style?: Partial<LineStyle>;
346
+ /** Same override as `WickChartOptions.formatLegend`, narrowed to this
347
+ * series's own types — see `createCandlestickChart`'s equivalent. */
348
+ formatLegend?(point: LinePoint, style: LineStyle, context: LegendFormatContext<LinePoint>): string[];
341
349
  }): WickChart<LinePoint>;
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { lowerBound, upperBound } from './binarySearch.js';
2
+ import { devicePixelRatio } from './devicePixelRatio.js';
2
3
  import { mergeSeriesPoints } from './mergeSeries.js';
3
4
  import { computePaneLayout } from './paneLayout.js';
4
5
  import { ChartRenderer } from './renderer.js';
@@ -841,12 +842,10 @@ export class WickChart {
841
842
  * conversion `cursorPosition` applies to absolute coordinates, extracted
842
843
  * so pixel *deltas* (drag distance, wheel deltaX) can be converted too. */
843
844
  devicePixelScaleX() {
844
- const rect = this.canvas.getBoundingClientRect();
845
- return rect.width === 0 ? 1 : this.canvas.width / rect.width;
845
+ return devicePixelRatio(this.canvas, 'width');
846
846
  }
847
847
  devicePixelScaleY() {
848
- const rect = this.canvas.getBoundingClientRect();
849
- return rect.height === 0 ? 1 : this.canvas.height / rect.height;
848
+ return devicePixelRatio(this.canvas, 'height');
850
849
  }
851
850
  }
852
851
  /**
@@ -17,6 +17,15 @@ export interface PluginRenderApi<TPoint extends SeriesPoint = SeriesPoint> {
17
17
  ctx: CanvasRenderingContext2D;
18
18
  chartWidth: number;
19
19
  chartHeight: number;
20
+ /** Ratio between the canvas's backing-store size and its CSS display
21
+ * size — 1 on a standard-DPI display, 2 on a typical Retina one.
22
+ * `chartWidth`/`chartHeight` and everything `xForIndex`/`yForValue`
23
+ * return are already in backing-store pixels, but a plugin choosing its
24
+ * *own* literal pixel sizes (`ctx.lineWidth`, a font size in
25
+ * `ctx.font`, a marker radius) should multiply them by this first, the
26
+ * same way the built-in line series scales `LineStyle.lineWidth` — see
27
+ * "High-DPI displays" in the README. */
28
+ devicePixelRatio: number;
20
29
  /** Global (full sorted-array) index -> x pixel, same convention the
21
30
  * active series draws with. Valid only for the duration of this `draw()`
22
31
  * call — see the interface-level note on `PluginRenderApi`. */
@@ -43,7 +43,13 @@ export interface RenderInput<TPoint extends SeriesPoint> {
43
43
  * coloring/padding, legend color) is resolved once at construction from
44
44
  * `WickChartOptions.font`/`axis`/`crosshair`/`legend`, each merged field
45
45
  * by field over its own defaults — nothing here is a hardcoded module
46
- * constant a caller can't reach.
46
+ * constant a caller can't reach. Every *size* among them (font sizes, axis
47
+ * strip widths, padding, gaps) is specified in CSS pixels and scaled by the
48
+ * canvas's live devicePixelRatio (see `deviceRatio`) at the top of every
49
+ * `render()` call before use — colors and tick counts pass through
50
+ * unscaled. `AxisRenderer`/`CrosshairRenderer` themselves stay unaware of
51
+ * this: they're handed already-scaled options each frame, the same as they
52
+ * were handed unscaled ones before this existed.
47
53
  */
48
54
  export declare class ChartRenderer<TPoint extends SeriesPoint> {
49
55
  private canvas;
@@ -51,24 +57,40 @@ export declare class ChartRenderer<TPoint extends SeriesPoint> {
51
57
  private ctx;
52
58
  private background;
53
59
  private style;
54
- /** Kept as its own field (unlike font/crosshair/legend, which only
55
- * `AxisRenderer`/`CrosshairRenderer` need after construction) because
56
- * `chartWidth`/`chartHeight`/`priceAxisWidth` below read it directly on
57
- * every call, not just once at construction. */
60
+ /** Author-facing (CSS-pixel) style groups, resolved once at construction
61
+ * from `WickChartOptions.font`/`axis`/`crosshair`/`legend` — kept as
62
+ * fields so `render()` can rescale them fresh every frame against the
63
+ * canvas's current devicePixelRatio, which (a window dragged to a
64
+ * different-DPI monitor, a browser zoom change, or the app simply
65
+ * resizing the canvas) can change between frames. `axis` is additionally
66
+ * read directly by `chartWidth`/`chartHeight`/`priceAxisWidth` below. */
58
67
  private axis;
59
- private axisRenderer;
60
- private crosshairRenderer;
68
+ private font;
69
+ private crosshair;
70
+ private legend;
61
71
  /** Unlike the style groups above, mutable after construction — see
62
72
  * `setInvertValueAxis`. A live toggle, not a one-time style choice, is
63
73
  * the whole point of this option (a "what if this series moved the
64
74
  * opposite way" view a user flips on and off), so it doesn't get the
65
75
  * "resolved once in the constructor" treatment those get. */
66
76
  private invertValueAxis;
77
+ /** Per-instance override of `seriesDefinition.formatLegend` — see
78
+ * `WickChartOptions.formatLegend`'s own doc comment for why this exists
79
+ * as a chart-instance option rather than only a series-type one. */
80
+ private formatLegendOverride?;
67
81
  constructor(canvas: HTMLCanvasElement, seriesDefinition: SeriesDefinition<TPoint, unknown>, options?: WickChartOptions);
68
82
  setInvertValueAxis(inverted: boolean): void;
83
+ /** Ratio between the canvas's backing-store size and its CSS display
84
+ * size — read live, not cached, for the same reason `chartWidth`/
85
+ * `chartHeight` below read `canvas.width`/`height` live: whatever it is
86
+ * *right now* is what this frame draws at. See `src/devicePixelRatio.ts`. */
87
+ private get deviceRatio();
69
88
  /** Pixel width of the point-plotting area — excludes the price-axis
70
89
  * strip on the right. Exposed so `WickChart` can convert cursor pixel
71
- * positions to point indices / values for hit-testing and dragging. */
90
+ * positions to point indices / values for hit-testing and dragging.
91
+ * `priceAxisWidth` below is already devicePixelRatio-scaled, so this
92
+ * (and `chartHeight`) stay correct on a high-DPI canvas without
93
+ * `WickChart` having to know anything about DPR itself. */
72
94
  get chartWidth(): number;
73
95
  get chartHeight(): number;
74
96
  get priceAxisWidth(): number;
package/dist/renderer.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AxisRenderer } from './axisRenderer.js';
2
2
  import { CrosshairRenderer } from './crosshairRenderer.js';
3
+ import { devicePixelRatio } from './devicePixelRatio.js';
3
4
  import { createScale } from './hybridScale.js';
4
5
  import { computePaneLayout } from './paneLayout.js';
5
6
  import { pixelToValue, valueAxisPixelRange } from './valueAxis.js';
@@ -53,7 +54,13 @@ const DEFAULT_LEGEND = {
53
54
  * coloring/padding, legend color) is resolved once at construction from
54
55
  * `WickChartOptions.font`/`axis`/`crosshair`/`legend`, each merged field
55
56
  * by field over its own defaults — nothing here is a hardcoded module
56
- * constant a caller can't reach.
57
+ * constant a caller can't reach. Every *size* among them (font sizes, axis
58
+ * strip widths, padding, gaps) is specified in CSS pixels and scaled by the
59
+ * canvas's live devicePixelRatio (see `deviceRatio`) at the top of every
60
+ * `render()` call before use — colors and tick counts pass through
61
+ * unscaled. `AxisRenderer`/`CrosshairRenderer` themselves stay unaware of
62
+ * this: they're handed already-scaled options each frame, the same as they
63
+ * were handed unscaled ones before this existed.
57
64
  */
58
65
  export class ChartRenderer {
59
66
  constructor(canvas, seriesDefinition, options = {}) {
@@ -67,39 +74,85 @@ export class ChartRenderer {
67
74
  this.style = { ...seriesDefinition.defaultStyle, ...(options.style ?? {}) };
68
75
  this.axis = { ...DEFAULT_AXIS, ...options.axis };
69
76
  this.invertValueAxis = options.invertValueAxis ?? false;
70
- const font = { ...DEFAULT_FONT, ...options.font };
71
- const crosshair = { ...DEFAULT_CROSSHAIR, ...options.crosshair };
72
- const legend = { ...DEFAULT_LEGEND, ...options.legend };
73
- this.axisRenderer = new AxisRenderer(ctx, this.axis, font);
74
- this.crosshairRenderer = new CrosshairRenderer(ctx, crosshair, legend, font, this.axis.priceWidth);
77
+ this.formatLegendOverride = options.formatLegend;
78
+ this.font = { ...DEFAULT_FONT, ...options.font };
79
+ this.crosshair = { ...DEFAULT_CROSSHAIR, ...options.crosshair };
80
+ this.legend = { ...DEFAULT_LEGEND, ...options.legend };
75
81
  }
76
82
  setInvertValueAxis(inverted) {
77
83
  this.invertValueAxis = inverted;
78
84
  }
85
+ /** Ratio between the canvas's backing-store size and its CSS display
86
+ * size — read live, not cached, for the same reason `chartWidth`/
87
+ * `chartHeight` below read `canvas.width`/`height` live: whatever it is
88
+ * *right now* is what this frame draws at. See `src/devicePixelRatio.ts`. */
89
+ get deviceRatio() {
90
+ return devicePixelRatio(this.canvas, 'width');
91
+ }
79
92
  /** Pixel width of the point-plotting area — excludes the price-axis
80
93
  * strip on the right. Exposed so `WickChart` can convert cursor pixel
81
- * positions to point indices / values for hit-testing and dragging. */
94
+ * positions to point indices / values for hit-testing and dragging.
95
+ * `priceAxisWidth` below is already devicePixelRatio-scaled, so this
96
+ * (and `chartHeight`) stay correct on a high-DPI canvas without
97
+ * `WickChart` having to know anything about DPR itself. */
82
98
  get chartWidth() {
83
- return Math.max(0, this.canvas.width - this.axis.priceWidth);
99
+ return Math.max(0, this.canvas.width - this.priceAxisWidth);
84
100
  }
85
101
  get chartHeight() {
86
- return Math.max(0, this.canvas.height - this.axis.timeHeight);
102
+ return Math.max(0, this.canvas.height - this.axis.timeHeight * this.deviceRatio);
87
103
  }
88
104
  get priceAxisWidth() {
89
- return this.axis.priceWidth;
105
+ return this.axis.priceWidth * this.deviceRatio;
90
106
  }
91
107
  render(input) {
92
108
  const { ctx, canvas, background, seriesDefinition, style } = this;
93
109
  const { sorted, times, viewport, hoverIndex, hoverY, plugins, panes } = input;
110
+ const ratio = this.deviceRatio;
111
+ // Scaled fresh every frame (see `deviceRatio`'s own doc comment for
112
+ // why this isn't done once at construction) — every *size* field gets
113
+ // multiplied by `ratio`, every color/count field passes through as-is.
114
+ // `AxisRenderer`/`CrosshairRenderer` are cheap POJO-ish collaborators
115
+ // with no state beyond these options, so rebuilding them here each
116
+ // frame is simpler than threading `ratio` through every one of their
117
+ // methods for what's otherwise the same "resolved options" shape they
118
+ // were built to take in the first place.
119
+ const scaledAxis = {
120
+ ...this.axis,
121
+ priceWidth: this.axis.priceWidth * ratio,
122
+ timeHeight: this.axis.timeHeight * ratio,
123
+ };
124
+ const scaledFont = {
125
+ ...this.font,
126
+ axisSize: this.font.axisSize * ratio,
127
+ legendSize: this.font.legendSize * ratio,
128
+ };
129
+ const scaledCrosshair = {
130
+ ...this.crosshair,
131
+ labelPaddingX: this.crosshair.labelPaddingX * ratio,
132
+ labelPaddingY: this.crosshair.labelPaddingY * ratio,
133
+ };
134
+ const scaledLegend = {
135
+ ...this.legend,
136
+ paddingX: this.legend.paddingX * ratio,
137
+ paddingY: this.legend.paddingY * ratio,
138
+ cursorGap: this.legend.cursorGap * ratio,
139
+ };
140
+ const axisRenderer = new AxisRenderer(ctx, scaledAxis, scaledFont);
141
+ const crosshairRenderer = new CrosshairRenderer(ctx, scaledCrosshair, scaledLegend, scaledFont, scaledAxis.priceWidth);
94
142
  const width = canvas.width;
95
143
  const height = canvas.height;
96
- const chartWidth = this.chartWidth;
144
+ // Computed from `scaledAxis` (already built from `ratio` above) rather
145
+ // than by re-reading `this.chartWidth`/`chartHeight` — those getters
146
+ // recompute `deviceRatio`, which reads `getBoundingClientRect()` (a
147
+ // potential layout reflow in a real browser); doing that three times
148
+ // per frame instead of once matters at 60fps.
149
+ const chartWidth = Math.max(0, width - scaledAxis.priceWidth);
97
150
  // Full stack height: the main price pane plus every declared indicator
98
151
  // pane below it. `this.chartHeight` predates panes and named what's
99
152
  // now only true with zero of them — kept as the property name (public
100
153
  // API reads it through) but renamed locally here since most of this
101
154
  // method cares about one pane's height, not the stack's.
102
- const stackHeight = this.chartHeight;
155
+ const stackHeight = Math.max(0, height - scaledAxis.timeHeight);
103
156
  ctx.clearRect(0, 0, width, height);
104
157
  if (background !== 'transparent') {
105
158
  ctx.fillStyle = background;
@@ -164,26 +217,31 @@ export class ChartRenderer {
164
217
  // grid lines, and the crosshair.
165
218
  ctx.save();
166
219
  try {
167
- seriesDefinition.draw({ ctx, visible, startIndex: startIdx, xForIndex, slotWidth, yScale, chartHeight }, style);
220
+ seriesDefinition.draw({ ctx, visible, startIndex: startIdx, xForIndex, slotWidth, yScale, chartHeight, devicePixelRatio: ratio }, style);
168
221
  }
169
222
  finally {
170
223
  ctx.restore();
171
224
  }
172
- const priceStep = this.axisRenderer.priceStep(valueMin, valueMax);
173
- this.axisRenderer.renderPriceAxis(valueMin, valueMax, priceStep, yScale, chartWidth, chartHeight, mainRect.top);
225
+ const priceStep = axisRenderer.priceStep(valueMin, valueMax);
226
+ axisRenderer.renderPriceAxis(valueMin, valueMax, priceStep, yScale, chartWidth, chartHeight, mainRect.top);
174
227
  for (const { rect, min, max, scale } of paneScales) {
175
- this.axisRenderer.renderPaneSeparator(rect.top, chartWidth);
176
- const step = this.axisRenderer.priceStep(min, max);
177
- this.axisRenderer.renderPriceAxis(min, max, step, scale, chartWidth, rect.height, rect.top);
228
+ axisRenderer.renderPaneSeparator(rect.top, chartWidth);
229
+ const step = axisRenderer.priceStep(min, max);
230
+ axisRenderer.renderPriceAxis(min, max, step, scale, chartWidth, rect.height, rect.top);
178
231
  }
179
- this.axisRenderer.renderTimeAxis(times, startIdx, visible.length, stackHeight, chartWidth, xForIndex);
232
+ axisRenderer.renderTimeAxis(times, startIdx, visible.length, stackHeight, chartWidth, xForIndex);
180
233
  if (hoverIndex !== null && hoverIndex >= startIdx && hoverIndex < endIdx) {
181
234
  // The dashed vertical line spans the whole stack (every pane); the
182
235
  // horizontal line, price-label chip, and OHLC legend stay scoped
183
236
  // to the main pane only — an indicator pane's own hover readout,
184
237
  // if it wants one, is the job of whatever plugin draws into it.
185
- const legendParts = seriesDefinition.formatLegend?.(sorted[hoverIndex], style) ?? [];
186
- this.crosshairRenderer.render({
238
+ // `formatLegendOverride`, when set, replaces the series's own
239
+ // formatLegend entirely for this chart instance rather than
240
+ // merging with it — see `WickChartOptions.formatLegend`.
241
+ const formatLegend = this.formatLegendOverride ?? seriesDefinition.formatLegend;
242
+ const legendContext = { index: hoverIndex, allPoints: sorted };
243
+ const legendParts = formatLegend?.(sorted[hoverIndex], style, legendContext) ?? [];
244
+ crosshairRenderer.render({
187
245
  x: xForIndex(hoverIndex),
188
246
  timeSeconds: times[hoverIndex],
189
247
  hoverY,
@@ -213,10 +271,10 @@ export class ChartRenderer {
213
271
  allPoints: sorted,
214
272
  frameState,
215
273
  };
216
- const mainApi = this.buildPluginApi(mainRect, valueMin, valueMax, yScale, frameGeometry);
274
+ const mainApi = this.buildPluginApi(mainRect, valueMin, valueMax, yScale, frameGeometry, ratio);
217
275
  const paneApiById = new Map();
218
276
  for (const { pane, rect, min, max, scale } of paneScales) {
219
- paneApiById.set(pane.id, this.buildPluginApi(rect, min, max, scale, frameGeometry));
277
+ paneApiById.set(pane.id, this.buildPluginApi(rect, min, max, scale, frameGeometry, ratio));
220
278
  }
221
279
  for (const plugin of plugins) {
222
280
  if (plugin.visible === false)
@@ -257,12 +315,13 @@ export class ChartRenderer {
257
315
  * for this frame (shared because there is only one time axis, and one
258
316
  * frame-ended flag, for the whole stack; see `FrameGeometry`).
259
317
  */
260
- buildPluginApi(rect, valueMin, valueMax, scale, geometry) {
318
+ buildPluginApi(rect, valueMin, valueMax, scale, geometry, devicePixelRatio) {
261
319
  const { chartWidth, xForIndex, indexForX, visibleStartIndex, visibleEndIndex, allPoints, frameState } = geometry;
262
320
  return {
263
321
  ctx: this.ctx,
264
322
  chartWidth,
265
323
  chartHeight: rect.height,
324
+ devicePixelRatio,
266
325
  xForIndex,
267
326
  yForValue: (value) => {
268
327
  if (frameState.ended) {
@@ -16,7 +16,7 @@ function getValueRange(visible, scaleFactor) {
16
16
  return fitRange(Math.min(...values), Math.max(...values), scaleFactor);
17
17
  }
18
18
  function draw(context, style) {
19
- const { ctx, visible, startIndex, xForIndex, yScale } = context;
19
+ const { ctx, visible, startIndex, xForIndex, yScale, devicePixelRatio } = context;
20
20
  if (visible.length === 0)
21
21
  return;
22
22
  // Batched through mapMany (one call per array) rather than once per
@@ -26,7 +26,11 @@ function draw(context, style) {
26
26
  // filtered out first, so `ys[i]` still lines up with `visible[i]`.
27
27
  const ys = yScale.mapMany(visible.map((p) => p.value));
28
28
  ctx.strokeStyle = style.lineColor;
29
- ctx.lineWidth = style.lineWidth;
29
+ // `lineWidth` is authored in CSS pixels, like every other size in
30
+ // `WickChartOptions` — scaled to backing-store pixels here so the stroke
31
+ // renders at its intended visual thickness on a high-DPI canvas instead
32
+ // of half that. See `SeriesDrawContext.devicePixelRatio`.
33
+ ctx.lineWidth = style.lineWidth * devicePixelRatio;
30
34
  ctx.beginPath();
31
35
  // `drawing` tracks whether the path is mid-segment — a non-finite value
32
36
  // (a gap in the data) breaks it, and the line resumes fresh at the next
@@ -1,5 +1,5 @@
1
1
  import type { Scale } from '../hybridScale.js';
2
- import type { SeriesPoint, ValueRange } from '../types.js';
2
+ import type { LegendFormatContext, SeriesPoint, ValueRange } from '../types.js';
3
3
  export type { ValueRange } from '../types.js';
4
4
  /**
5
5
  * Everything a series's `draw` needs to turn its visible points into
@@ -23,6 +23,17 @@ export interface SeriesDrawContext<TPoint extends SeriesPoint> {
23
23
  /** Value (price) -> y pixel for the current frame's domain. */
24
24
  yScale: Scale;
25
25
  chartHeight: number;
26
+ /** Ratio between the canvas's backing-store size and its CSS display
27
+ * size — 1 on a standard-DPI display, 2 on a typical Retina one. Every
28
+ * geometric field above (`slotWidth`, `chartHeight`, the pixels `yScale`
29
+ * maps to) is already in backing-store pixels, but a *literal* pixel
30
+ * size in `style` (a stroke width, say — `LineStyle.lineWidth` is the
31
+ * built-in example) is normally authored in CSS pixels, the same
32
+ * intuitive unit `WickChartOptions.font`/`axis`/`crosshair`/`legend` use;
33
+ * multiply such a field by this before setting it on `ctx` so it renders
34
+ * at its intended visual size rather than half that on a 2x display. See
35
+ * "High-DPI displays" in the README. */
36
+ devicePixelRatio: number;
26
37
  }
27
38
  /**
28
39
  * The single seam a new chart type has to implement. `WickChart` and
@@ -51,6 +62,11 @@ export interface SeriesDefinition<TPoint extends SeriesPoint, TStyle> {
51
62
  draw(context: SeriesDrawContext<TPoint>, style: TStyle): void;
52
63
  /** Builds the hover/crosshair legend text for one point, one string per
53
64
  * segment (joined with spacing by the renderer). Omit to draw the
54
- * crosshair line with no legend text. */
55
- formatLegend?(point: TPoint, style: TStyle): string[];
65
+ * crosshair line with no legend text. `context` gives access to
66
+ * neighboring points (see `LegendFormatContext`) for anything the
67
+ * hovered point alone can't express, like a value compared against the
68
+ * previous point — this built-in series doesn't need it, but a custom
69
+ * one can. `WickChartOptions.formatLegend`, when set, overrides this per
70
+ * chart instance rather than per series type — see its own doc comment. */
71
+ formatLegend?(point: TPoint, style: TStyle, context: LegendFormatContext<TPoint>): string[];
56
72
  }
package/dist/types.d.ts CHANGED
@@ -169,6 +169,22 @@ export interface ResolvedPaneOptions {
169
169
  heightRatio: number;
170
170
  getValueRange: () => ValueRange;
171
171
  }
172
+ /**
173
+ * Context `SeriesDefinition.formatLegend` and `WickChartOptions.formatLegend`
174
+ * get alongside the hovered point and its style — everything needed to
175
+ * compute something derived from *neighboring* points (a percent change
176
+ * vs. the previous point, say), which the hovered point alone can't
177
+ * express. The same `allPoints`/index-into-it shape `SeriesDrawContext`
178
+ * already gives a series's own `draw()`, reused here so both call sites
179
+ * answer "what else is near this point" the same way.
180
+ */
181
+ export interface LegendFormatContext<TPoint extends SeriesPoint = SeriesPoint> {
182
+ /** Global index of the hovered point in `allPoints`. */
183
+ index: number;
184
+ /** Every point currently loaded (not just visible), sorted ascending by
185
+ * time — the same array `SeriesDrawContext.allPoints` is. */
186
+ allPoints: readonly TPoint[];
187
+ }
172
188
  export interface WickChartOptions {
173
189
  /**
174
190
  * Which registered series type to render this chart as (see
@@ -199,6 +215,30 @@ export interface WickChartOptions {
199
215
  crosshair?: ChartCrosshairOptions;
200
216
  /** Hover legend coloring. Merged over the built-in defaults field by field. */
201
217
  legend?: ChartLegendOptions;
218
+ /**
219
+ * Overrides the active series's own `formatLegend` (see
220
+ * `SeriesDefinition.formatLegend`) for this chart instance specifically —
221
+ * the hover legend's text, one string per line. `SeriesDefinition.formatLegend`
222
+ * is a shared default for every chart of that series *type* (registered
223
+ * once via `registerSeries`); this is a per-*instance* override for
224
+ * whatever varies by app/session instead of by chart type — localized
225
+ * labels, or a value derived from neighboring points via
226
+ * `context.allPoints`/`context.index` (a percent change vs. the previous
227
+ * point, say). Returning an empty array suppresses the built-in tooltip
228
+ * entirely, the same as a series with no `formatLegend` at all — draw
229
+ * your own via a `ChartPlugin` instead if you need a different layout,
230
+ * not just different text.
231
+ *
232
+ * Declared as a method (not an arrow-typed property) so, like
233
+ * `SeriesDefinition.formatLegend`, it type-checks bivariantly rather than
234
+ * contravariantly — the same tradeoff `style`'s untyped
235
+ * `Record<string, unknown>` already makes here: `new WickChart(canvas, {
236
+ * type, formatLegend })` doesn't verify `point`/`style` actually match
237
+ * `type`'s series, but `createCandlestickChart`/`createLineChart` narrow
238
+ * both to the concrete series's own types, the same way they narrow
239
+ * `style` — see their own doc comments.
240
+ */
241
+ formatLegend?(point: SeriesPoint, style: unknown, context: LegendFormatContext<SeriesPoint>): string[];
202
242
  /**
203
243
  * Mirrors the value axis top-to-bottom — every pane's higher values
204
244
  * render lower on screen instead of higher, with no change to the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wick-charts",
3
- "version": "0.7.1",
3
+ "version": "0.9.0",
4
4
  "description": "An open-source financial charting library — WASM (Rust) for compute, Canvas2D for rendering.",
5
5
  "license": "MIT",
6
6
  "author": "eatnows",