Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(quill-charts): monotone curve and axis-flush line strokes (#67989)

Sam Pennington5c0c696c591b
diff --git a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx
index 90e76975d988..8eeaa04828d8 100644
--- a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx
+++ b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx
@@ -5,6 +5,7 @@ import { bandCenter, buildBarLayers, computeBarAtIndex, groupedBarCenter } from
import {
BAR_HIGHLIGHT_DARKEN,
DEFAULT_BAR_CORNER_RADIUS,
+ LINE_STROKE_WIDTH,
drawAxes,
drawBarHighlight,
drawBars,
@@ -89,7 +90,9 @@ function ComboChartInner<Meta = unknown>({
defaultSeriesType = DEFAULT_SERIES_TYPE,
xTickFormatter,
valueDomain,
+ curve,
} = config ?? {}
+ const smooth = curve === 'monotone'
const seriesTypeOf = useCallback(
(s: Pick<Series, 'type'>): SeriesType => resolveSeriesType(s, defaultSeriesType),
@@ -221,6 +224,13 @@ function ComboChartInner<Meta = unknown>({
shouldFill: (s) => seriesTypeOf(s) === 'area' || !!s.fill,
bottomFor: (s) => s.fill?.lowerData,
zOrder: 'areas-first',
+ smooth,
+ // Rest baseline-hugging strokes on the axis line, and trim the first point's
+ // stroke at the y-axis, instead of straddling either axis line.
+ yFloor: showAxisLines
+ ? dimensions.plotTop + dimensions.plotHeight - LINE_STROKE_WIDTH / 2
+ : undefined,
+ clipLeftEdge: showAxisLines,
})
},
[
@@ -232,6 +242,7 @@ function ComboChartInner<Meta = unknown>({
barStackedData,
topStackedKeyByAxis,
barCornerRadius,
+ smooth,
]
)
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
index 040c0e29e058..88b17ba7db1d 100644
--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
@@ -2,7 +2,13 @@ import React, { useCallback, useMemo } from 'react'
import { ChartLegend } from '../../components/Legend/ChartLegend'
import { useChartLegend } from '../../components/Legend/useChartLegend'
-import { drawAxes, drawGrid, drawLineHoverPoints, drawLineSeriesLayer } from '../../core/canvas-renderer'
+import {
+ LINE_STROKE_WIDTH,
+ drawAxes,
+ drawGrid,
+ drawLineHoverPoints,
+ drawLineSeriesLayer,
+} from '../../core/canvas-renderer'
import type { DrawContext } from '../../core/canvas-renderer'
import { Chart } from '../../core/Chart'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
@@ -82,7 +88,9 @@ function LineChartInner<Meta = unknown>({
valueDomain,
floatBaseline = false,
yAxes,
+ curve,
} = config ?? {}
+ const smooth = curve === 'monotone'
const { visibleSeries, legendProps } = useChartLegend(series, theme, config?.legend)
@@ -196,9 +204,16 @@ function LineChartInner<Meta = unknown>({
bottomFor: (s) => s.fill?.lowerData ?? stackedData?.get(s.key)?.bottom,
shouldFill: (s) => !!s.fill,
zOrder: 'per-series',
+ smooth,
+ // Rest baseline-hugging strokes on the axis line, and trim the first point's
+ // stroke at the y-axis, instead of straddling either axis line.
+ yFloor: showAxisLines
+ ? dimensions.plotTop + dimensions.plotHeight - LINE_STROKE_WIDTH / 2
+ : undefined,
+ clipLeftEdge: showAxisLines,
})
},
- [showGrid, showAxisLines, stackedData]
+ [showGrid, showAxisLines, stackedData, smooth]
)
const drawHover = useCallback(
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
index 08eb34a7e08a..e4df2160ed89 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
@@ -38,6 +38,8 @@ export interface TimeSeriesComboChartConfig {
showCrosshair?: boolean
/** Draw L-shaped axis baselines without grid lines (ignored when `yAxis.showGrid` is true). */
showAxisLines?: boolean
+ /** Line interpolation for line/area series: `linear` (default) or `monotone` (smooth curve). */
+ curve?: 'linear' | 'monotone'
/** Tooltip behaviour (pinning, placement). Tooltip *content* is the `tooltip` render prop. */
tooltip?: TooltipConfig
/** Built-in legend with click-to-toggle series visibility. Hidden by default. */
@@ -84,6 +86,7 @@ export function TimeSeriesComboChart<Meta = unknown>({
barCornerRadius,
showCrosshair,
showAxisLines,
+ curve,
tooltip: tooltipConfig,
legend,
trendLines,
@@ -114,6 +117,7 @@ export function TimeSeriesComboChart<Meta = unknown>({
yAxisLabel: primaryYAxis?.label,
showGrid: primaryYAxis?.showGrid,
showAxisLines,
+ curve,
showCrosshair,
defaultSeriesType,
barLayout,
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index 1859809a2f9d..d5cc121f7d22 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -47,6 +47,8 @@ export interface TimeSeriesLineChartConfig {
showCrosshair?: boolean
/** Draw L-shaped axis baselines without grid lines (ignored when `yAxis.showGrid` is true). */
showAxisLines?: boolean
+ /** Line interpolation: `linear` (default) or `monotone` (smooth curve through every point). */
+ curve?: 'linear' | 'monotone'
/** Tooltip behaviour (pinning, placement). Tooltip *content* is the `tooltip` render prop. */
tooltip?: TooltipConfig
/** Built-in legend with click-to-toggle series visibility. Hidden by default. */
@@ -92,6 +94,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
percentStackView,
showCrosshair,
showAxisLines,
+ curve,
tooltip: tooltipConfig,
legend,
} = config ?? {}
@@ -130,6 +133,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
yAxisLabel: primaryYAxis?.label,
showGrid: primaryYAxis?.showGrid,
showAxisLines,
+ curve,
percentStackView,
showCrosshair,
tooltip: tooltipConfig,
diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts b/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
index 5ca6c4ec7012..5c65abf6ca9b 100644
--- a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
+++ b/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
@@ -1,4 +1,4 @@
-import { scaleLinear, scalePoint } from 'd3-scale'
+import { type ScaleLinear, scaleLinear, scalePoint } from 'd3-scale'
import { dimensions, makeSeries } from '../testing'
import {
@@ -8,6 +8,7 @@ import {
drawArea,
drawGrid,
drawLine,
+ drawLineSeriesLayer,
drawSelectionRect,
} from './canvas-renderer'
import type { ChartDrawArgs, ChartTheme } from './types'
@@ -20,9 +21,14 @@ function mockCanvasContext(): jest.Mocked<CanvasRenderingContext2D> {
stroke: jest.fn(),
fill: jest.fn(),
closePath: jest.fn(),
+ bezierCurveTo: jest.fn(),
arc: jest.fn(),
fillRect: jest.fn(),
strokeRect: jest.fn(),
+ rect: jest.fn(),
+ save: jest.fn(),
+ clip: jest.fn(),
+ restore: jest.fn(),
setLineDash: jest.fn(),
createPattern: jest.fn(() => ({}) as CanvasPattern),
strokeStyle: '',
@@ -130,6 +136,68 @@ describe('hog-charts canvas-renderer', () => {
})
})
+ describe('drawLine — monotone smoothing and yFloor', () => {
+ it('emits one bezier segment per point pair and no interior lineTo when smooth', () => {
+ const ctx = mockCanvasContext()
+ const labels = ['a', 'b', 'c', 'd']
+ const series = makeSeries({ key: 's1', data: [10, 90, 30, 60] })
+ drawLine({ ...makeDrawContext(ctx, labels), smooth: true }, series)
+ expect(ctx.moveTo).toHaveBeenCalledTimes(1)
+ expect(ctx.bezierCurveTo).toHaveBeenCalledTimes(3)
+ expect(ctx.lineTo).not.toHaveBeenCalled()
+ })
+
+ it('keeps every bezier control point within the data extremes (no overshoot past a peak)', () => {
+ const ctx = mockCanvasContext()
+ const labels = ['a', 'b', 'c']
+ const series = makeSeries({ key: 's1', data: [10, 90, 10] })
+ const drawCtx = { ...makeDrawContext(ctx, labels), smooth: true }
+ drawLine(drawCtx, series)
+ const pointYs = [10, 90, 10].map((v) => drawCtx.yScale(v))
+ const [minY, maxY] = [Math.min(...pointYs), Math.max(...pointYs)]
+ const cpYs = ctx.bezierCurveTo.mock.calls.flatMap(([, cp1y, , cp2y, , endY]) => [cp1y, cp2y, endY])
+ expect(Math.min(...cpYs)).toBeGreaterThanOrEqual(minY)
+ expect(Math.max(...cpYs)).toBeLessThanOrEqual(maxY)
+ })
+
+ it('splits the smooth curve into separate subpaths at gaps', () => {
+ const ctx = mockCanvasContext()
+ const labels = ['a', 'b', 'c', 'd', 'e']
+ const series = makeSeries({ key: 's1', data: [10, 20, 50, 70, 90] })
+ drawLine({ ...makeDrawContextWithGaps(ctx, labels, new Set([50])), smooth: true }, series)
+ expect(ctx.moveTo).toHaveBeenCalledTimes(2)
+ expect(ctx.bezierCurveTo).toHaveBeenCalledTimes(2)
+ })
+
+ it.each([{ smooth: false }, { smooth: true }])(
+ 'clamps drawn y coordinates to yFloor (smooth: $smooth)',
+ ({ smooth }) => {
+ const ctx = mockCanvasContext()
+ const labels = ['a', 'b', 'c']
+ const series = makeSeries({ key: 's1', data: [0, 80, 0] })
+ const drawCtx = makeDrawContext(ctx, labels)
+ const yFloor = drawCtx.yScale(0) - 1
+ drawLine({ ...drawCtx, smooth, yFloor }, series)
+ const drawnYs = [
+ ...ctx.moveTo.mock.calls.map(([, y]) => y),
+ ...ctx.lineTo.mock.calls.map(([, y]) => y),
+ ...ctx.bezierCurveTo.mock.calls.flatMap(([, cp1y, , cp2y, , endY]) => [cp1y, cp2y, endY]),
+ ]
+ expect(drawnYs.length).toBeGreaterThan(0)
+ expect(Math.max(...drawnYs)).toBeLessThanOrEqual(yFloor)
+ }
+ )
+
+ it('smooths both area edges with bezier segments so stacked bottoms match the curve below', () => {
+ const ctx = mockCanvasContext()
+ const labels = ['a', 'b', 'c']
+ const series = makeSeries({ key: 's1', data: [10, 90, 30], fill: { opacity: 0.5 } })
+ drawArea({ ...makeDrawContext(ctx, labels), smooth: true }, series)
+ expect(ctx.bezierCurveTo).toHaveBeenCalledTimes(4)
+ expect(ctx.fill).toHaveBeenCalled()
+ })
+ })
+
describe('drawLine — partial dashing (stroke.partial)', () => {
it.each([
// Fast path — neither index set
@@ -367,6 +435,21 @@ describe('hog-charts canvas-renderer', () => {
expect(ctx.beginPath).toHaveBeenCalledTimes(2)
expect(dashCalls(ctx)).toEqual([[], [10, 10], []])
})
+
+ it.each([
+ { name: 'two points', data: [10, 90], labels: ['a', 'b'] },
+ { name: 'three points (leading segment stays curved)', data: [10, 40, 90], labels: ['a', 'b', 'c'] },
+ ])('$name, smooth → tail follows the curve as a bezier, never a straight chord', ({ data, labels }) => {
+ const ctx = mockCanvasContext()
+ const series = makeSeries({ key: 's1', data, stroke: { partial: { fromFraction: 0.5 } } })
+ drawLine({ ...makeDrawContext(ctx, labels), smooth: true }, series)
+ // The straight-line branch would emit lineTo for the split bridge and the tail; the smooth
+ // split draws both the solid body and the dashed tail as bezier segments instead.
+ expect(ctx.lineTo).not.toHaveBeenCalled()
+ expect(ctx.bezierCurveTo).toHaveBeenCalled()
+ expect(ctx.beginPath).toHaveBeenCalledTimes(2)
+ expect(dashCalls(ctx)).toEqual([[], [10, 10], []])
+ })
})
describe('drawArea — stacked bands', () => {
@@ -905,4 +988,26 @@ describe('hog-charts canvas-renderer', () => {
expect(ctx.fillRect).not.toHaveBeenCalled()
})
})
+
+ describe('drawLineSeriesLayer — clipLeftEdge', () => {
+ const labels = ['a', 'b', 'c']
+ const series = [makeSeries({ key: 's1', data: [10, 50, 90] })]
+ const xScale = scalePoint<string>().domain(labels).range([48, 784]).padding(0)
+ const yScale = scaleLinear().domain([0, 100]).range([368, 16])
+ const resolveYScale = (): ScaleLinear<number, number> => yScale
+
+ it.each([
+ { clipLeftEdge: true, expectedLeft: Math.round(dimensions.plotLeft), expectedWidth: dimensions.width - Math.round(dimensions.plotLeft) },
+ { clipLeftEdge: false, expectedLeft: 0, expectedWidth: dimensions.width },
+ ])(
+ 'passes left=$expectedLeft width=$expectedWidth to ctx.rect when clipLeftEdge=$clipLeftEdge',
+ ({ clipLeftEdge, expectedLeft, expectedWidth }) => {
+ const ctx = mockCanvasContext()
+ drawLineSeriesLayer({ ctx, dimensions, labels, series, xScale, resolveYScale, clipLeftEdge })
+ const rectCall = ctx.rect.mock.calls[0]
+ expect(rectCall[0]).toBe(expectedLeft)
+ expect(rectCall[2]).toBe(expectedWidth)
+ }
+ )
+ })
})
diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.ts
index 6b28dfcc66bc..5018ba785e03 100644
--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts
+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts
@@ -10,8 +10,18 @@ export interface DrawContext {
xScale: (label: string) => number | undefined
yScale: ScaleLinear<number, number> | ScaleLogarithmic<number, number>
labels: string[]
+ /** Smooth the line/area with monotone-cubic interpolation instead of straight segments. */
+ smooth?: boolean
+ /** Largest drawable y (px) for line/area strokes. Charts drawing an x-axis line pass the
+ * baseline minus half their stroke width, so a baseline-hugging stroke rests exactly on the
+ * axis line instead of straddling it. Pure draw-time clamp — scales and ticks are untouched. */
+ yFloor?: number
}
+/** Stroke width of series lines. Half of it is the stroke's overhang past a point, which the
+ * `yFloor`/left-clip callers use to keep strokes flush against drawn axis lines. */
+export const LINE_STROKE_WIDTH = 2
+
export function drawLine(drawCtx: DrawContext, series: ResolvedSeries, yValues?: number[]): void {
const data = yValues ?? series.data
if (data.length === 0) {
@@ -20,7 +30,7 @@ export function drawLine(drawCtx: DrawContext, series: ResolvedSeries, yValues?:
const { ctx } = drawCtx
ctx.strokeStyle = series.color
- ctx.lineWidth = 2
+ ctx.lineWidth = LINE_STROKE_WIDTH
ctx.lineJoin = 'round'
ctx.lineCap = 'round'
@@ -47,17 +57,25 @@ function drawFractionalTailDash(drawCtx: DrawContext, series: ResolvedSeries, da
if (fraction == null || data.length < 2) {
return false
}
- const { ctx, xScale, yScale, labels } = drawCtx
+ const { ctx, xScale, yScale, labels, yFloor, smooth } = drawCtx
const last = data.length - 1
const x0 = xScale(labels[last - 1])
- const y0 = yScale(data[last - 1])
+ const rawY0 = yScale(data[last - 1])
const x1 = xScale(labels[last])
- const y1 = yScale(data[last])
- if (x0 == null || x1 == null || !isFinite(y0) || !isFinite(y1)) {
+ const rawY1 = yScale(data[last])
+ if (x0 == null || x1 == null || !isFinite(rawY0) || !isFinite(rawY1)) {
return false
}
+ const y0 = yFloor != null ? Math.min(rawY0, yFloor) : rawY0
+ const y1 = yFloor != null ? Math.min(rawY1, yFloor) : rawY1
const f = Math.max(0, Math.min(1, fraction))
+
+ if (smooth) {
+ drawSmoothFractionalTail(drawCtx, series, data, f)
+ return true
+ }
+
const splitX = x0 + (x1 - x0) * f
const splitY = y0 + (y1 - y0) * f
@@ -77,6 +95,88 @@ function drawFractionalTailDash(drawCtx: DrawContext, series: ResolvedSeries, da
return true
}
+/** Two cubic bezier halves from splitting one segment at parameter `t` (de Casteljau). */
+interface SplitCubic {
+ /** Split point — end of the first half, start of the second. */
+ x: number
+ y: number
+ firstCp1x: number
+ firstCp1y: number
+ firstCp2x: number
+ firstCp2y: number
+ secondCp1x: number
+ secondCp1y: number
+ secondCp2x: number
+ secondCp2y: number
+}
+
+/** Split the cubic bezier `p0 → (seg.cp1, seg.cp2) → p3` at parameter `t` into two halves that
+ * together trace the identical curve (de Casteljau subdivision). */
+function splitCubicBezier(p0: Point, seg: CurveSegment, p3: Point, t: number): SplitCubic {
+ const lerp = (a: number, b: number): number => a + (b - a) * t
+ const p01x = lerp(p0.x, seg.cp1x)
+ const p01y = lerp(p0.y, seg.cp1y)
+ const p12x = lerp(seg.cp1x, seg.cp2x)
+ const p12y = lerp(seg.cp1y, seg.cp2y)
+ const p23x = lerp(seg.cp2x, p3.x)
+ const p23y = lerp(seg.cp2y, p3.y)
+ const p012x = lerp(p01x, p12x)
+ const p012y = lerp(p01y, p12y)
+ const p123x = lerp(p12x, p23x)
+ const p123y = lerp(p12y, p23y)
+ return {
+ x: lerp(p012x, p123x),
+ y: lerp(p012y, p123y),
+ firstCp1x: p01x,
+ firstCp1y: p01y,
+ firstCp2x: p012x,
+ firstCp2y: p012y,
+ secondCp1x: p123x,
+ secondCp1y: p123y,
+ secondCp2x: p23x,
+ secondCp2y: p23y,
+ }
+}
+
+/** The `smooth` branch of {@link drawFractionalTailDash}: draws the monotone curve solid up to the
+ * split point and dashed from there to the last point. `f` is taken as the bezier parameter of the
+ * final segment (splitting the same curve the rest of the line follows), so the dashed tail stays
+ * on the curve instead of reverting to a straight chord. Leading gap-separated runs draw solid. */
+function drawSmoothFractionalTail(drawCtx: DrawContext, series: ResolvedSeries, data: number[], f: number): void {
+ const { ctx } = drawCtx
+ const runs = collectSmoothRuns(drawCtx, data, 0, data.length - 1)
+ // The caller's guard ensures the last two indices are finite and adjacent, so the final run
+ // ends at the last point with at least two points — a splittable final segment.
+ const tail = runs[runs.length - 1]
+ const segs = monotoneSegments(tail)
+ const lastSeg = segs[segs.length - 1]
+ const split = splitCubicBezier(tail[tail.length - 2], lastSeg, tail[tail.length - 1], f)
+
+ // Solid: every leading run in full, then the final run up to the split point on its last segment.
+ ctx.beginPath()
+ ctx.setLineDash(series.stroke?.pattern ?? [])
+ for (let r = 0; r < runs.length - 1; r++) {
+ ctx.moveTo(runs[r][0].x, runs[r][0].y)
+ if (runs[r].length > 1) {
+ curveForward(ctx, runs[r])
+ }
+ }
+ ctx.moveTo(tail[0].x, tail[0].y)
+ for (let i = 0; i < segs.length - 1; i++) {
+ ctx.bezierCurveTo(segs[i].cp1x, segs[i].cp1y, segs[i].cp2x, segs[i].cp2y, tail[i + 1].x, tail[i + 1].y)
+ }
+ ctx.bezierCurveTo(split.firstCp1x, split.firstCp1y, split.firstCp2x, split.firstCp2y, split.x, split.y)
+ ctx.stroke()
+
+ // Dashed: the split point out to the final point, along the same curve.
+ ctx.beginPath()
+ ctx.setLineDash(series.stroke?.partial?.pattern ?? [10, 10])
+ ctx.moveTo(split.x, split.y)
+ const end = tail[tail.length - 1]
+ ctx.bezierCurveTo(split.secondCp1x, split.secondCp1y, split.secondCp2x, split.secondCp2y, end.x, end.y)
+ ctx.stroke()
+}
+
/** One contiguous stroke: indices [start, end] inclusive, rendered with `pattern`. */
interface Stroke {
start: number
@@ -122,19 +222,27 @@ function planLineStrokes(series: ResolvedSeries, length: number): Stroke[] {
return strokes
}
-/** Walks data from [start, end] inclusive, emitting moveTo/lineTo. Caller owns beginPath/stroke. */
+/** Walks data from [start, end] inclusive. Emits straight segments streamed point by point, or
+ * monotone-cubic curves when `drawCtx.smooth` is set (the smooth branch buffers each subpath's
+ * points since the tangents need the whole run). NaN/out-of-domain points break the line into
+ * separate subpaths. Caller owns beginPath/stroke. */
function tracePath(drawCtx: DrawContext, data: number[], start: number, end: number): void {
- const { ctx, xScale, yScale, labels } = drawCtx
+ const { ctx, xScale, yScale, labels, smooth, yFloor } = drawCtx
+ if (smooth) {
+ traceSmoothPath(drawCtx, data, start, end)
+ return
+ }
let started = false
for (let i = start; i <= end; i++) {
const x = xScale(labels[i])
- const y = yScale(data[i])
- if (x == null || !isFinite(y)) {
+ const rawY = yScale(data[i])
+ if (x == null || !isFinite(rawY)) {
// Reset so the next valid point starts a fresh subpath rather than
// connecting straight across the NaN gap.
started = false
continue
}
+ const y = yFloor != null ? Math.min(rawY, yFloor) : rawY
if (!started) {
ctx.moveTo(x, y)
started = true
@@ -144,6 +252,126 @@ function tracePath(drawCtx: DrawContext, data: number[], start: number, end: num
}
}
+interface Point {
+ x: number
+ y: number
+}
+
+/** Collects the drawable points of [start, end] into gap-delimited runs — a new run starts after
+ * every NaN/out-of-domain point, so each run is a contiguous subpath. `yFloor` clamps each point. */
+function collectSmoothRuns(drawCtx: DrawContext, data: number[], start: number, end: number): Point[][] {
+ const { xScale, yScale, labels, yFloor } = drawCtx
+ const runs: Point[][] = []
+ let run: Point[] = []
+ for (let i = start; i <= end; i++) {
+ const x = xScale(labels[i])
+ const y = yScale(data[i])
+ if (x == null || !isFinite(y)) {
+ if (run.length > 0) {
+ runs.push(run)
+ run = []
+ }
+ continue
+ }
+ run.push({ x, y: yFloor != null ? Math.min(y, yFloor) : y })
+ }
+ if (run.length > 0) {
+ runs.push(run)
+ }
+ return runs
+}
+
+/** The `smooth` branch of {@link tracePath}: emits monotone-cubic bezier segments through each
+ * gap-delimited subpath. */
+function traceSmoothPath(drawCtx: DrawContext, data: number[], start: number, end: number): void {
+ const { ctx } = drawCtx
+ for (const run of collectSmoothRuns(drawCtx, data, start, end)) {
+ ctx.moveTo(run[0].x, run[0].y)
+ if (run.length > 1) {
+ curveForward(ctx, run)
+ }
+ }
+}
+
+/** Monotone-cubic (Fritsch–Carlson) tangents for points with strictly increasing x. Matches d3's
+ * `curveMonotoneX`: preserves monotonicity between points, so the curve never overshoots the data
+ * (no spurious wiggles or dips past a peak/trough). Hand-rolled rather than d3-shape because the
+ * shortened `SMOOTH_ARM` below isn't expressible with d3's fixed 1/3 arm. */
+function monotoneTangents(pts: Point[]): number[] {
+ const n = pts.length
+ const h: number[] = new Array(n - 1)
+ const s: number[] = new Array(n - 1)
+ for (let i = 0; i < n - 1; i++) {
+ h[i] = pts[i + 1].x - pts[i].x
+ s[i] = h[i] !== 0 ? (pts[i + 1].y - pts[i].y) / h[i] : 0
+ }
+ const m: number[] = new Array(n)
+ if (n === 2) {
+ m[0] = s[0]
+ m[1] = s[0]
+ return m
+ }
+ for (let i = 1; i < n - 1; i++) {
+ const s0 = s[i - 1]
+ const s1 = s[i]
+ if (s0 * s1 <= 0) {
+ m[i] = 0
+ } else {
+ const p = (s0 * h[i] + s1 * h[i - 1]) / (h[i - 1] + h[i])
+ m[i] = (Math.sign(s0) + Math.sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p))
+ }
+ }
+ m[0] = (3 * s[0] - m[1]) / 2
+ m[n - 1] = (3 * s[n - 2] - m[n - 2]) / 2
+ return m
+}
+
+interface CurveSegment {
+ cp1x: number
+ cp1y: number
+ cp2x: number
+ cp2y: number
+}
+
+// Control-arm length as a fraction of the segment width. 1/3 is the standard monotone-cubic arm
+// (full curve); shortening it pulls the curve closer to the straight chord between points for a
+// gentler bend. Crucially this keeps the *same* tangent direction at each point, so adjacent
+// segments still meet smoothly there — the data points stay rounded, only the mid-segment bow shrinks.
+const SMOOTH_ARM = 1 / 4
+
+function monotoneSegments(pts: Point[]): CurveSegment[] {
+ const m = monotoneTangents(pts)
+ const segs: CurveSegment[] = []
+ for (let i = 0; i < pts.length - 1; i++) {
+ const arm = (pts[i + 1].x - pts[i].x) * SMOOTH_ARM
+ segs.push({
+ cp1x: pts[i].x + arm,
+ cp1y: pts[i].y + m[i] * arm,
+ cp2x: pts[i + 1].x - arm,
+ cp2y: pts[i + 1].y - m[i + 1] * arm,
+ })
+ }
+ return segs
+}
+
+/** Emit monotone bezier segments from the first point forward. Assumes the current path point is
+ * already at `pts[0]`. */
+function curveForward(ctx: CanvasRenderingContext2D, pts: Point[]): void {
+ const segs = monotoneSegments(pts)
+ for (let i = 0; i < segs.length; i++) {
+ ctx.bezierCurveTo(segs[i].cp1x, segs[i].cp1y, segs[i].cp2x, segs[i].cp2y, pts[i + 1].x, pts[i + 1].y)
+ }
+}
+
+/** Emit the same monotone curve traversed last→first (control points swapped). Assumes the current
+ * path point is already at `pts[n-1]`. Used for an area's bottom edge. */
+function curveReverse(ctx: CanvasRenderingContext2D, pts: Point[]): void {
+ const segs = monotoneSegments(pts)
+ for (let i = segs.length - 1; i >= 0; i--) {
+ ctx.bezierCurveTo(segs[i].cp2x, segs[i].cp2y, segs[i].cp1x, segs[i].cp1y, pts[i].x, pts[i].y)
+ }
+}
+
/** Returns null when unset; otherwise rounds and clamps into [0, length-1]. */
function resolvePartialIndex(idx: number | undefined, length: number): number | null {
if (idx == null || length === 0) {
@@ -202,7 +430,7 @@ export function drawArea(
yValues?: number[],
bottomValues?: number[]
): void {
- const { ctx, xScale, yScale, labels, dimensions } = drawCtx
+ const { ctx, xScale, yScale, labels, dimensions, smooth, yFloor } = drawCtx
const data = yValues ?? series.data
const opacity = series.fill?.opacity ?? 0.5
const baseline = dimensions.plotTop + dimensions.plotHeight
@@ -221,11 +449,14 @@ export function drawArea(
}
for (let i = 0; i < data.length; i++) {
const x = xScale(labels[i])
- const yTop = yScale(data[i])
- if (x == null || !isFinite(yTop)) {
+ const rawTop = yScale(data[i])
+ if (x == null || !isFinite(rawTop)) {
breakSegment()
continue
}
+ // Clamped like the line stroke so the area's top edge stays under it; the bottom edge
+ // still fills down to the baseline, keeping the area anchored to the axis.
+ const yTop = yFloor != null ? Math.min(rawTop, yFloor) : rawTop
if (bottomValues) {
const rawBottom = bottomValues[i]
const yBot = rawBottom == null ? NaN : yScale(rawBottom)
@@ -262,7 +493,7 @@ export function drawArea(
if (useGradient || (dashedFrom === null && dashedTo === null)) {
ctx.fillStyle = gradient ?? series.color
- fillAreaPath(ctx, top, bottom)
+ fillAreaPath(ctx, top, bottom, smooth)
continue
}
@@ -276,14 +507,14 @@ export function drawArea(
if (wholeSegmentLeading || wholeSegmentTrailing) {
ctx.fillStyle = hatch
- fillAreaPath(ctx, top, bottom)
+ fillAreaPath(ctx, top, bottom, smooth)
continue
}
if (dashedTo !== null && toSplit > 0) {
const leadingEnd = Math.min(top.length, toSplit + 1)
ctx.fillStyle = hatch
- fillAreaPath(ctx, top.slice(0, leadingEnd), bottom.slice(0, leadingEnd))
+ fillAreaPath(ctx, top.slice(0, leadingEnd), bottom.slice(0, leadingEnd), smooth)
}
const solidStart = toSplit === -1 ? 0 : toSplit
@@ -294,31 +525,36 @@ export function drawArea(
// segment and the shaded region stops a step past where the line turns dashed.
if (solidEnd - solidStart >= 2) {
ctx.fillStyle = series.color
- fillAreaPath(ctx, top.slice(solidStart, solidEnd), bottom.slice(solidStart, solidEnd))
+ fillAreaPath(ctx, top.slice(solidStart, solidEnd), bottom.slice(solidStart, solidEnd), smooth)
}
if (dashedFrom !== null && fromSplit > 0) {
const hatchStart = Math.max(0, fromSplit - 1)
ctx.fillStyle = hatch
- fillAreaPath(ctx, top.slice(hatchStart), bottom.slice(hatchStart))
+ fillAreaPath(ctx, top.slice(hatchStart), bottom.slice(hatchStart), smooth)
}
}
ctx.globalAlpha = 1
}
-function fillAreaPath(
- ctx: CanvasRenderingContext2D,
- top: { x: number; y: number }[],
- bottom: { x: number; y: number }[]
-): void {
+function fillAreaPath(ctx: CanvasRenderingContext2D, top: Point[], bottom: Point[], smooth?: boolean): void {
ctx.beginPath()
ctx.moveTo(top[0].x, top[0].y)
- for (let i = 1; i < top.length; i++) {
- ctx.lineTo(top[i].x, top[i].y)
+ if (smooth && top.length > 1) {
+ curveForward(ctx, top)
+ } else {
+ for (let i = 1; i < top.length; i++) {
+ ctx.lineTo(top[i].x, top[i].y)
+ }
}
- for (let i = bottom.length - 1; i >= 0; i--) {
- ctx.lineTo(bottom[i].x, bottom[i].y)
+ ctx.lineTo(bottom[bottom.length - 1].x, bottom[bottom.length - 1].y)
+ if (smooth && bottom.length > 1) {
+ curveReverse(ctx, bottom)
+ } else {
+ for (let i = bottom.length - 2; i >= 0; i--) {
+ ctx.lineTo(bottom[i].x, bottom[i].y)
+ }
}
ctx.closePath()
ctx.fill()
@@ -557,17 +793,23 @@ export const BAR_HIGHLIGHT_DARKEN = 0.6
/** Run `draw` with the canvas clipped to the plot area vertically (full width, padded `pad` px top
* and bottom). Keeps out-of-domain values (e.g. a trendline below 0) out of the axis gutters while
- * leaving the left/right edges unclipped so line caps and edge point markers render whole. Shared
- * by LineChart and ComboChart. `restore` always runs, even if `draw` throws. */
+ * leaving the left/right edges unclipped so line caps and edge point markers render whole.
+ * `clipLeft` additionally trims at the plot's left edge — for charts drawing a y-axis line, so the
+ * first point's stroke ends at the axis instead of bulging past it into the gutter. Shared by
+ * LineChart and ComboChart. `restore` always runs, even if `draw` throws. */
export function withVerticalClip(
ctx: CanvasRenderingContext2D,
dimensions: ChartDimensions,
draw: () => void,
- pad = 8
+ pad = 8,
+ clipLeft = false
): void {
+ // Matches drawAxes' snapping: the axis line's 1px column starts at round(plotLeft), so trimming
+ // there leaves the stroke flush against the axis line.
+ const left = clipLeft ? Math.round(dimensions.plotLeft) : 0
ctx.save()
ctx.beginPath()
- ctx.rect(0, dimensions.plotTop - pad, dimensions.width, dimensions.plotHeight + pad * 2)
+ ctx.rect(left, dimensions.plotTop - pad, dimensions.width - left, dimensions.plotHeight + pad * 2)
ctx.clip()
try {
draw()
@@ -593,13 +835,21 @@ export interface LineSeriesLayerOptions {
/** `per-series`: area then line+points per series (LineChart). `areas-first`: every area, then
* every line+points (ComboChart) so a later area can't paint over an earlier line. */
zOrder?: 'per-series' | 'areas-first'
+ /** Smooth lines/areas with monotone-cubic interpolation instead of straight segments. */
+ smooth?: boolean
+ /** See {@link DrawContext.yFloor} — rest baseline-hugging strokes on the axis line. */
+ yFloor?: number
+ /** Trim strokes at the plot's left edge so they end at a drawn y-axis line instead of bulging
+ * past it. Pass the chart's `showAxisLines` — without an axis line the overhang is invisible
+ * and edge line caps are left whole. */
+ clipLeftEdge?: boolean
}
/** Draw a line/area layer (clipped vertically) — the per-series area/line/points orchestration shared
* by LineChart and ComboChart. Callers supply the y-value source (raw vs stacked tops), the fill
* predicate, and the z-order; the loop, clip, and primitive calls live here. */
export function drawLineSeriesLayer(options: LineSeriesLayerOptions): void {
- const { ctx, dimensions, labels, series, xScale, resolveYScale } = options
+ const { ctx, dimensions, labels, series, xScale, resolveYScale, smooth, yFloor, clipLeftEdge } = options
const yValuesFor = options.yValuesFor ?? (() => undefined)
const bottomFor = options.bottomFor ?? ((s: ResolvedSeries) => s.fill?.lowerData)
const shouldFill = options.shouldFill ?? ((s: ResolvedSeries) => !!s.fill)
@@ -610,32 +860,43 @@ export function drawLineSeriesLayer(options: LineSeriesLayerOptions): void {
if (!shouldFill(s)) {
return
}
- drawArea({ ctx, dimensions, labels, xScale, yScale: resolveYScale(s) }, s, yValuesFor(s), bottomFor(s))
+ drawArea(
+ { ctx, dimensions, labels, xScale, yScale: resolveYScale(s), smooth, yFloor },
+ s,
+ yValuesFor(s),
+ bottomFor(s)
+ )
}
const paintLine = (s: ResolvedSeries): void => {
if (s.fill?.lowerData) {
return
}
- const drawCtx: DrawContext = { ctx, dimensions, labels, xScale, yScale: resolveYScale(s) }
+ const drawCtx: DrawContext = { ctx, dimensions, labels, xScale, yScale: resolveYScale(s), smooth, yFloor }
drawLine(drawCtx, s, yValuesFor(s))
drawPoints(drawCtx, s, yValuesFor(s))
}
- withVerticalClip(ctx, dimensions, () => {
- if (zOrder === 'areas-first') {
- for (const s of visible) {
- paintArea(s)
+ withVerticalClip(
+ ctx,
+ dimensions,
+ () => {
+ if (zOrder === 'areas-first') {
+ for (const s of visible) {
+ paintArea(s)
+ }
+ for (const s of visible) {
+ paintLine(s)
+ }
+ return
}
for (const s of visible) {
+ paintArea(s)
paintLine(s)
}
- return
- }
- for (const s of visible) {
- paintArea(s)
- paintLine(s)
- }
- })
+ },
+ undefined,
+ clipLeftEdge
+ )
}
/** Draw hover highlight rings for line/area series at the hovered index. Skips excluded,
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index ca87c35f7de9..e3706a78a342 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -229,6 +229,9 @@ export interface ChartConfig {
/** Draw only the L-shaped axis baselines (left + bottom) without interior grid lines. Ignored
* when `showGrid` is true, since the grid already frames the plot. */
showAxisLines?: boolean
+ /** Line/area interpolation. `linear` (default) draws straight segments; `monotone` smooths the
+ * line with monotone-cubic curves that pass through every point without overshooting. */
+ curve?: 'linear' | 'monotone'
/** Tooltip behaviour. Defaults to enabled with no pinning and `follow-data` placement. */
tooltip?: TooltipConfig
/** Show a vertical crosshair line that follows the cursor. */