@keneth80/k-chart 1.2.0 → 1.4.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.
@@ -0,0 +1,487 @@
1
+ # KChart Functional API
2
+
3
+ ## Goal
4
+
5
+ KChart의 새 public API는 class adapter가 아니라 class-free runtime입니다. UI에서는 `new BasicChart(...)` 같은 인스턴스를 직접 만들지 않고 `createKChart(...)`로 controller를 생성합니다.
6
+
7
+ 차트 코어는 축, scale, layout, SVG/Canvas/WebGL layer를 준비합니다. Series는 `render(context)` 함수만 제공하고, 같은 scale 정보를 받아 SVG, Canvas, WebGL 중 원하는 방식으로 그립니다.
8
+
9
+ ## Import Surface
10
+
11
+ ```ts
12
+ import {
13
+ createKChart,
14
+ createCursorLineOption,
15
+ createGuideLineOption,
16
+ createLineSeries,
17
+ createCanvasCandlestickSeries,
18
+ createCanvasLineSeries,
19
+ createCanvasPointSeries,
20
+ createSpecAreaOption,
21
+ createWebglPointSeries,
22
+ createCustomSeries,
23
+ KChartController,
24
+ KChartSeries
25
+ } from '@keneth80/k-chart';
26
+ ```
27
+
28
+ 새 저장소 기준 public export는 `src/kchart.ts`입니다. 기존 class 기반 구현은 마이그레이션 참고용 source로 남아 있어도 패키지 API로는 내보내지 않습니다.
29
+
30
+ ## Controller
31
+
32
+ ```ts
33
+ const chart = createKChart({
34
+ selector: '#chart',
35
+ data,
36
+ axes,
37
+ series
38
+ });
39
+
40
+ chart.render();
41
+ chart.updateData(nextData);
42
+ chart.updateAxes(nextAxes);
43
+ chart.updateSeries(nextSeries);
44
+ chart.resize({ width: 960, height: 420 });
45
+ chart.destroy();
46
+ ```
47
+
48
+ ### Controller Contract
49
+
50
+ ```ts
51
+ type KChartController<T> = {
52
+ render(): KChartController<T>;
53
+ updateData(data: T[]): KChartController<T>;
54
+ updateAxes(axes: KChartAxis<T>[]): KChartController<T>;
55
+ updateSeries(series: KChartSeries<T>[]): KChartController<T>;
56
+ resize(size?: Partial<KChartSize>): KChartController<T>;
57
+ destroy(): void;
58
+ getState(): KChartState<T>;
59
+ };
60
+ ```
61
+
62
+ 반환값이 다시 controller이기 때문에 `render().updateData(...)`처럼 chaining할 수 있습니다.
63
+
64
+ ## Built-In Line Series
65
+
66
+ ```ts
67
+ const chart = createKChart<TrafficPoint>({
68
+ selector: '#chart',
69
+ data,
70
+ axes: [
71
+ { field: 'time', type: 'string', placement: 'bottom' },
72
+ { field: 'value', type: 'number', placement: 'left' }
73
+ ],
74
+ series: [
75
+ createLineSeries({
76
+ selector: 'traffic',
77
+ displayName: 'Traffic',
78
+ xField: 'time',
79
+ yField: 'value',
80
+ curve: true,
81
+ dot: true
82
+ })
83
+ ]
84
+ });
85
+
86
+ chart.render();
87
+ ```
88
+
89
+ ## Built-In Canvas Series
90
+
91
+ Canvas 2D line/point renderer는 별도 class 없이 factory로 생성합니다.
92
+
93
+ ```ts
94
+ const chart = createKChart<Point>({
95
+ selector: '#chart',
96
+ data,
97
+ axes: [
98
+ { field: 'x', type: 'number', placement: 'bottom' },
99
+ { field: 'y', type: 'number', placement: 'left' }
100
+ ],
101
+ series: [
102
+ createCanvasLineSeries({
103
+ selector: 'canvas-line',
104
+ xField: 'x',
105
+ yField: 'y',
106
+ color: '#56d08f',
107
+ lineWidth: 3
108
+ }),
109
+ createCanvasPointSeries({
110
+ selector: 'canvas-points',
111
+ xField: 'x',
112
+ yField: 'y',
113
+ radius: 4,
114
+ color: '#5db8ff'
115
+ })
116
+ ]
117
+ });
118
+ ```
119
+
120
+ ## Built-In Canvas Candlestick Series
121
+
122
+ OHLC 주식 데이터는 `createCanvasCandlestickSeries`로 렌더링합니다. Y축은 보통 `close`를 기본 field로 두고, `domainFields`에 `low`와 `high`를 넣어 전체 캔들 범위가 축 domain에 포함되게 합니다.
123
+
124
+ ```ts
125
+ interface StockPoint {
126
+ date: string;
127
+ open: number;
128
+ high: number;
129
+ low: number;
130
+ close: number;
131
+ previousClose: number;
132
+ }
133
+
134
+ const chart = createKChart<StockPoint>({
135
+ selector: '#chart',
136
+ data: [
137
+ { date: '2026-06-01', open: 101, high: 108, low: 98, close: 106, previousClose: 100 },
138
+ { date: '2026-06-02', open: 106, high: 110, low: 102, close: 103, previousClose: 106 },
139
+ { date: '2026-06-03', open: 103, high: 112, low: 101, close: 111, previousClose: 103 }
140
+ ],
141
+ axes: [
142
+ { field: 'date', type: 'time', placement: 'bottom', tickCount: 5, domain: ['2026-05-31', '2026-06-04'] },
143
+ {
144
+ field: 'close',
145
+ type: 'number',
146
+ placement: 'left',
147
+ domainFields: ['low', 'high'],
148
+ title: 'Price'
149
+ }
150
+ ],
151
+ tooltip: { visible: true },
152
+ series: [
153
+ createCanvasCandlestickSeries({
154
+ selector: 'price',
155
+ displayName: 'Price',
156
+ xField: 'date',
157
+ openField: 'open',
158
+ highField: 'high',
159
+ lowField: 'low',
160
+ closeField: 'close',
161
+ colorMode: 'previous-close',
162
+ previousCloseField: 'previousClose',
163
+ upColor: '#22c55e',
164
+ downColor: '#ef4444'
165
+ })
166
+ ]
167
+ });
168
+ ```
169
+
170
+ 캔들 색상은 기본적으로 `colorMode: 'open-close'`로 동작하며 `close`와 `open`을 비교합니다. `colorMode: 'previous-close'`를 사용하면 현재 `close`와 전일 종가를 비교합니다. `previousCloseField`가 있으면 그 필드를 우선 사용하고, 없으면 렌더링 데이터에서 바로 앞 항목의 `closeField` 값을 전일 종가로 사용합니다.
171
+
172
+ ## Built-In WebGL Series
173
+
174
+ ```ts
175
+ const chart = createKChart<Point>({
176
+ selector: '#chart',
177
+ data,
178
+ axes: [
179
+ { field: 'x', type: 'number', placement: 'bottom' },
180
+ { field: 'y', type: 'number', placement: 'left' }
181
+ ],
182
+ series: [
183
+ createWebglLineSeries({
184
+ selector: 'webgl-large-line',
185
+ displayName: '120k WebGL Line',
186
+ xField: 'x',
187
+ yField: 'y',
188
+ color: '#5db8ff',
189
+ lineWidth: 1,
190
+ downsample: {
191
+ enabled: true,
192
+ threshold: ({ plotSize }) => Math.floor(plotSize.width)
193
+ }
194
+ }),
195
+ createWebglPointSeries({
196
+ selector: 'webgl-points',
197
+ xField: 'x',
198
+ yField: 'y',
199
+ pointSize: 8,
200
+ color: '#f3b45b'
201
+ })
202
+ ]
203
+ });
204
+ ```
205
+
206
+ ### Downsampling
207
+
208
+ `createLineSeries`, `createCanvasLineSeries`, `createWebglLineSeries`는 `downsample` 옵션을 지원합니다. `true`를 넘기면 현재 plot width를 기준으로 LTTB가 적용되고, 객체를 넘기면 threshold와 x/y accessor를 직접 지정할 수 있습니다.
209
+
210
+ ```ts
211
+ createWebglLineSeries<Point>({
212
+ selector: 'trace',
213
+ xField: 'x',
214
+ yField: 'signal',
215
+ downsample: {
216
+ enabled: true,
217
+ threshold: ({ plotSize }) => Math.floor(plotSize.width * 1.5)
218
+ }
219
+ });
220
+ ```
221
+
222
+ 알고리즘 자체도 export됩니다.
223
+
224
+ ```ts
225
+ import { downsampleLTTB } from '@keneth80/k-chart';
226
+
227
+ const sampled = downsampleLTTB(data, 1000, (point) => point.x, (point) => point.signal);
228
+ ```
229
+
230
+ ### Zoom
231
+
232
+ 차트 레벨의 `zoom` 옵션은 number/time 축의 domain을 갱신하고 기존 렌더 파이프라인을 다시 실행합니다. 별도 series API 없이 SVG, Canvas, WebGL renderer가 같은 확대 상태를 공유합니다.
233
+
234
+ ```ts
235
+ createKChart<Point>({
236
+ selector: '#chart',
237
+ data,
238
+ axes: [
239
+ { field: 'x', type: 'number', placement: 'bottom' },
240
+ { field: 'signal', type: 'number', placement: 'left' }
241
+ ],
242
+ series: [
243
+ createWebglLineSeries({
244
+ selector: 'trace',
245
+ xField: 'x',
246
+ yField: 'signal'
247
+ })
248
+ ],
249
+ zoom: {
250
+ enabled: true,
251
+ mode: 'both',
252
+ direction: 'x',
253
+ scaleExtent: [1, 80],
254
+ wheelZoom: { enabled: true, devices: 'pc', sensitivity: 0.85 },
255
+ gestureZoom: { enabled: true, devices: 'mobile', minTouches: 1 },
256
+ resetOnDoubleClick: true
257
+ }
258
+ });
259
+ ```
260
+
261
+ `mode`는 `'wheel'`, `'select'`, `'both'`를 지원합니다. `'wheel'`은 wheel/trackpad zoom과 drag pan, `'select'`는 드래그 영역 선택 zoom, `'both'`는 wheel/trackpad zoom과 드래그 영역 선택 zoom을 함께 사용합니다. `wheelZoom`은 PC wheel/trackpad 입력을, `gestureZoom`은 모바일 touch gesture 입력을 분리해서 제어합니다. `direction`은 `'x'`, `'y'`, `'xy'`를 지원합니다. string/point 축은 순서형 축이라 현재 zoom 대상에서 제외됩니다.
262
+
263
+ ### OffscreenCanvas Worker Rendering
264
+
265
+ `createCanvasLineSeries`와 `createWebglLineSeries`는 `asyncRender` 옵션을 지원합니다. worker 파일에서는 `startKChartRenderWorker()`를 호출하고, series에는 worker를 만드는 factory를 넘깁니다.
266
+
267
+ ```ts
268
+ // kchart-render.worker.ts
269
+ import { startKChartRenderWorker } from '@keneth80/k-chart';
270
+
271
+ startKChartRenderWorker();
272
+ ```
273
+
274
+ ```ts
275
+ createWebglLineSeries<Point>({
276
+ selector: 'trace',
277
+ xField: 'x',
278
+ yField: 'signal',
279
+ asyncRender: {
280
+ enabled: true,
281
+ workerFactory: () => new Worker(
282
+ new URL('./kchart-render.worker.ts', import.meta.url),
283
+ { type: 'module' }
284
+ )
285
+ }
286
+ });
287
+ ```
288
+
289
+ OffscreenCanvas를 지원하지 않거나 worker 생성에 실패하면 기존 메인 스레드 렌더러로 fallback됩니다.
290
+
291
+ ## Display Options
292
+
293
+ ```ts
294
+ createKChart({
295
+ selector: '#chart',
296
+ data,
297
+ title: { text: 'Hybrid Revenue And Volume', align: 'left' },
298
+ grid: { visible: true, y: true, x: false, dasharray: '2 6' },
299
+ legend: { visible: true, placement: 'top' },
300
+ tooltip: { visible: true },
301
+ axes: [
302
+ { field: 'x', type: 'number', placement: 'bottom', title: 'Month Index' },
303
+ { field: 'value', type: 'number', placement: 'left', title: 'Value' },
304
+ { field: 'volume', type: 'number', placement: 'right', title: 'Volume' }
305
+ ],
306
+ series: [
307
+ createLineSeries({ selector: 'value', xField: 'x', yField: 'value' }),
308
+ createCanvasPointSeries({ selector: 'volume', xField: 'x', yField: 'volume' })
309
+ ]
310
+ });
311
+ ```
312
+
313
+ The default tooltip shows the active series name and nearest x/y values. Provide `tooltip.formatter` for custom HTML/text.
314
+
315
+ ## Option Factories
316
+
317
+ Series는 `series: [...]`로 받고, chart 부가 기능은 `options: [...]`로 받습니다.
318
+
319
+ ```ts
320
+ createKChart({
321
+ selector: '#chart',
322
+ data,
323
+ axes,
324
+ series,
325
+ options: [
326
+ createSpecAreaOption([
327
+ { start: 2, end: 3.5, label: 'STEP 02' }
328
+ ]),
329
+ createGuideLineOption({
330
+ x: [{ value: 4, label: 'A' }],
331
+ y: [{ value: 58, label: 'HIGH' }]
332
+ }),
333
+ createCursorLineOption({
334
+ valueFormat: (value: number) => Number(value).toFixed(1)
335
+ })
336
+ ]
337
+ });
338
+ ```
339
+
340
+ 기존 `specAreas`, `guideLines`, `cursorGuide`, `guideLine` 직접 필드도 호환됩니다. 새 코드에서는 option factory 사용을 권장합니다.
341
+
342
+ ## Custom Series
343
+
344
+ 기본 series가 부족하면 `createCustomSeries(...)`에 renderer 함수를 넘깁니다. Class 상속이나 interface 구현 없이 같은 확장 지점을 사용할 수 있습니다.
345
+
346
+ Renderer context 주요 필드:
347
+
348
+ - `group`: 이 series 전용 SVG group
349
+ - `data`: 현재 차트 데이터
350
+ - `scales`, `xScale`, `yScale`: 코어가 계산한 scale
351
+ - `size`, `plotSize`, `margin`: 전체 크기와 plot 영역
352
+ - `color`: series 기본 색상
353
+ - `getCanvas(name)`: Canvas 2D layer
354
+ - `getWebglCanvas(name)`: WebGL canvas layer
355
+
356
+ ```ts
357
+ const circleSeries = createCustomSeries<CirclePoint>({
358
+ selector: 'custom-circle',
359
+ displayName: 'Custom Circle',
360
+ xField: 'x',
361
+ yField: 'y',
362
+ render({ group, data, xScale, yScale, color }) {
363
+ if (!xScale || !yScale) {
364
+ return;
365
+ }
366
+
367
+ group.selectAll('.custom-circle')
368
+ .data(data)
369
+ .join('circle')
370
+ .attr('class', 'custom-circle')
371
+ .attr('cx', (point) => xScale.scale(point.x))
372
+ .attr('cy', (point) => yScale.scale(point.y))
373
+ .attr('r', (point) => point.radius)
374
+ .style('fill', color);
375
+ }
376
+ });
377
+ ```
378
+
379
+ 간단한 SVG 원 series 예제는 [examples/custom-circle-series.ts](../examples/custom-circle-series.ts)를 참고하세요.
380
+
381
+ ## Canvas/WebGL Pattern
382
+
383
+ ```ts
384
+ const canvasSeries = createCustomSeries<Point>({
385
+ selector: 'canvas-points',
386
+ xField: 'x',
387
+ yField: 'y',
388
+ render({ getCanvas, data, xScale, yScale, color }) {
389
+ if (!xScale || !yScale) {
390
+ return;
391
+ }
392
+
393
+ const canvas = getCanvas('points');
394
+ const context = canvas.getContext('2d');
395
+ if (!context) {
396
+ return;
397
+ }
398
+
399
+ context.clearRect(0, 0, canvas.width, canvas.height);
400
+ context.fillStyle = color;
401
+
402
+ data.forEach((point) => {
403
+ context.beginPath();
404
+ context.arc(xScale.scale(point.x), yScale.scale(point.y), 3, 0, Math.PI * 2);
405
+ context.fill();
406
+ });
407
+ }
408
+ });
409
+ ```
410
+
411
+ ## React / Next.js Pattern
412
+
413
+ DOM을 직접 사용하므로 Client Component에서 mount 이후 생성합니다. 자세한 wrapper 예제와 Next.js 설정은 [React And Next.js Guide](react-nextjs.md)를 참고합니다.
414
+
415
+ ```tsx
416
+ 'use client';
417
+
418
+ import { useEffect, useRef } from 'react';
419
+ import { createKChart, createLineSeries, KChartController } from '@keneth80/k-chart';
420
+
421
+ export function TrafficChart({ data }) {
422
+ const rootRef = useRef<HTMLDivElement | null>(null);
423
+ const chartRef = useRef<KChartController | null>(null);
424
+
425
+ useEffect(() => {
426
+ if (!rootRef.current) {
427
+ return;
428
+ }
429
+
430
+ const chart = createKChart({
431
+ selector: rootRef.current,
432
+ data,
433
+ axes: [
434
+ { field: 'time', type: 'string', placement: 'bottom' },
435
+ { field: 'value', type: 'number', placement: 'left' }
436
+ ],
437
+ series: [
438
+ createLineSeries({
439
+ selector: 'traffic',
440
+ xField: 'time',
441
+ yField: 'value'
442
+ })
443
+ ]
444
+ });
445
+
446
+ chart.render();
447
+ chartRef.current = chart;
448
+
449
+ return () => {
450
+ chart.destroy();
451
+ chartRef.current = null;
452
+ };
453
+ }, []);
454
+
455
+ useEffect(() => {
456
+ chartRef.current?.updateData(data);
457
+ }, [data]);
458
+
459
+ return <div ref={rootRef} style={{ width: '100%', height: 420 }} />;
460
+ }
461
+ ```
462
+
463
+ ## Migration Checklist
464
+
465
+ 1. `new BasicChart(...)` 호출을 `createKChart(...)`로 교체합니다.
466
+ 2. class 상속 series를 `createCustomSeries({ render(context) { ... } })`로 옮깁니다.
467
+ 3. 축/scale 계산은 runtime에 맡기고, renderer는 전달받은 `xScale`, `yScale`, `getCanvas`, `getWebglCanvas`만 사용합니다.
468
+ 4. UI unmount 시 `chart.destroy()`를 호출합니다.
469
+ 5. 새 패키지 public import는 `@keneth80/k-chart`의 함수형 API만 사용합니다.
470
+
471
+ ## Refactor Status
472
+
473
+ 완료:
474
+
475
+ - `src/kchart.ts` class-free runtime 추가
476
+ - SVG line series renderer 함수화
477
+ - Canvas line/point series renderer 함수화
478
+ - WebGL point series renderer 함수화
479
+ - title/grid/legend/axis title 옵션 추가
480
+ - 기본 nearest-point tooltip 옵션 추가
481
+ - Custom series renderer API 추가
482
+ - 새 public entry를 KChart runtime으로 축소
483
+
484
+ 다음 단계:
485
+
486
+ - zoom을 runtime plugin 형태로 분리
487
+ - legacy demo를 새 runtime 예제로 교체