Skip to content

Commit dfddb47

Browse files
committed
refactor(polar): move radialLabels to its own module
Charts that do not use radialLabels should keep their exact polar bundle. Passing the chart text measurer through the polar container and adding the mark to polar.ts both changed every polar bundle. The mark now lives in polar-labels.ts and uses the built-in text estimate, polar.ts only re-exports it, and the shared option types move to a types-only module.
1 parent 54e922a commit dfddb47

7 files changed

Lines changed: 376 additions & 338 deletions

File tree

‎docs/reference/marks/polar.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -408,9 +408,10 @@ A label is hidden when its side runs out of height, when its text would cross
408408
the left or right chart edge, or when it would move more than `maxShift`
409409
pixels. Lower-priority labels hide first; on equal priority, the later row
410410
hides first, except that the width check hides the outermost-elbow label
411-
first because it sets the column. Hidden labels emit no nodes or interaction
412-
points, so pair the mark with a tooltip or legend when every slice name must
413-
stay available.
411+
first because it sets the column. Text widths come from the built-in text
412+
estimate used by static SVG, so unusual fonts can differ by a few pixels.
413+
Hidden labels emit no nodes or interaction points, so pair the mark with a
414+
tooltip or legend when every slice name must stay available.
414415

415416
The mark emits label and polyline scene nodes, so SVG, Canvas, and React
416417
Native paint it the same way. Connector keys add `:connector` to the label

‎packages/charts-core/docs/reference/marks/polar.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -408,9 +408,10 @@ A label is hidden when its side runs out of height, when its text would cross
408408
the left or right chart edge, or when it would move more than `maxShift`
409409
pixels. Lower-priority labels hide first; on equal priority, the later row
410410
hides first, except that the width check hides the outermost-elbow label
411-
first because it sets the column. Hidden labels emit no nodes or interaction
412-
points, so pair the mark with a tooltip or legend when every slice name must
413-
stay available.
411+
first because it sets the column. Text widths come from the built-in text
412+
estimate used by static SVG, so unusual fonts can differ by a few pixels.
413+
Hidden labels emit no nodes or interaction points, so pair the mark with a
414+
tooltip or legend when every slice name must stay available.
414415

415416
The mark emits label and polyline scene nodes, so SVG, Canvas, and React
416417
Native paint it the same way. Connector keys add `:connector` to the label
Lines changed: 323 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,323 @@
1+
import {
2+
channelValues,
3+
inferredKeyValues,
4+
isChartKey,
5+
isChartValue,
6+
isFiniteNumber,
7+
markStates,
8+
visualValue,
9+
} from './mark'
10+
import {
11+
estimateSceneText,
12+
measureSceneLabelBounds,
13+
physicalTextAnchor,
14+
} from './guide-layout'
15+
import { withPolarFocusGeometry } from './polar-focus-internal'
16+
import { layoutRadialLabels } from './polar-label-layout-internal'
17+
import { createPolarMark } from './polar-mark-internal'
18+
import { valueKey } from './scales'
19+
import { toArray } from './transform-internal'
20+
import type { PolarMark } from './polar'
21+
import type {
22+
InitializedPolarMark,
23+
PolarResolvedScale,
24+
} from './polar-mark-internal'
25+
import type {
26+
InferredPolarChannelOutput,
27+
InferredPolarScaleId,
28+
RadialPathOptions,
29+
} from './polar-types-internal'
30+
import type {
31+
Channel,
32+
ChartPoint,
33+
ChartValue,
34+
SceneNode,
35+
VisualChannel,
36+
} from './types'
37+
38+
// Connector and text spacing in pixels.
39+
const radialLabelSpacing = { offset: 16, elbow: 12, padding: 4 }
40+
41+
export interface RadialLabelsOptions<TDatum> extends RadialPathOptions<TDatum> {
42+
text?: Channel<TDatum, string | number | null | undefined>
43+
/**
44+
* Labels with lower priority hide first when labels do not fit. Defaults to
45+
* datum `value`, so `pie()` rows keep their largest slices.
46+
*/
47+
priority?: Channel<TDatum, number | null | undefined>
48+
fill?: VisualChannel<TDatum, string>
49+
fontSize?: number
50+
fontWeight?: number
51+
opacity?: number
52+
/** Hides a label that would move more pixels than this from its slice. */
53+
maxShift?: number
54+
/** Connector color. Defaults to the label fill. */
55+
stroke?: VisualChannel<TDatum, string>
56+
strokeOpacity?: number
57+
strokeWidth?: number
58+
}
59+
60+
type RadialLabelsCallOptions<
61+
TDatum,
62+
TAngle extends RadialLabelsOptions<TDatum>['angle'],
63+
TRadius extends RadialLabelsOptions<TDatum>['radius'],
64+
TAngleScaleId extends string | undefined,
65+
TRadiusScaleId extends string | undefined,
66+
> = Omit<
67+
RadialLabelsOptions<TDatum>,
68+
'angle' | 'radius' | 'angleScale' | 'radiusScale'
69+
> & {
70+
angle?: TAngle | NoInfer<RadialLabelsOptions<TDatum>['angle']>
71+
radius?: TRadius | NoInfer<RadialLabelsOptions<TDatum>['radius']>
72+
angleScale?: TAngleScaleId | NoInfer<string>
73+
radiusScale?: TRadiusScaleId | NoInfer<string>
74+
}
75+
76+
/**
77+
* Outside labels with connectors. Crowded labels are pushed apart vertically,
78+
* and the lowest-priority labels are hidden when they still do not fit.
79+
*/
80+
export function radialLabels<TDatum>(
81+
source: Iterable<TDatum>,
82+
): PolarMark<TDatum, number, number>
83+
export function radialLabels<
84+
TDatum,
85+
const TAngle extends RadialLabelsOptions<NoInfer<TDatum>>['angle'] = never,
86+
const TRadius extends RadialLabelsOptions<NoInfer<TDatum>>['radius'] = never,
87+
const TAngleScaleId extends string | undefined = undefined,
88+
const TRadiusScaleId extends string | undefined = undefined,
89+
>(
90+
source: Iterable<TDatum>,
91+
options:
92+
| RadialLabelsCallOptions<
93+
NoInfer<TDatum>,
94+
TAngle,
95+
TRadius,
96+
TAngleScaleId,
97+
TRadiusScaleId
98+
>
99+
| undefined,
100+
): PolarMark<
101+
TDatum,
102+
InferredPolarChannelOutput<TDatum, TAngle>,
103+
InferredPolarChannelOutput<TDatum, TRadius>,
104+
InferredPolarScaleId<TAngleScaleId, 'angle'>,
105+
InferredPolarScaleId<TRadiusScaleId, 'radius'>
106+
>
107+
export function radialLabels<TDatum>(
108+
source: Iterable<TDatum>,
109+
options: RadialLabelsOptions<NoInfer<TDatum>> = {},
110+
): PolarMark<TDatum, any, any> {
111+
const data = toArray(source)
112+
const fontSize = options.fontSize ?? 12
113+
if (!isFiniteNumber(fontSize) || fontSize <= 0) {
114+
throw new TypeError('radialLabels: fontSize must be positive and finite')
115+
}
116+
const mark = createPolarMark(
117+
({ markIndex, parentId, states: defaultStates }) => {
118+
const id = options.id ?? `${parentId}:radial-labels-${markIndex}`
119+
const angleScale = options.angleScale ?? 'angle'
120+
const radiusScale = options.radiusScale ?? 'radius'
121+
const angleValues =
122+
typeof options.angle === 'number'
123+
? data.map(() => options.angle as number)
124+
: channelValues(data, options.angle, (datum) =>
125+
numberProperty(datum, 'angle'),
126+
)
127+
const radiusValues =
128+
typeof options.radius === 'number'
129+
? data.map(() => options.radius as number)
130+
: channelValues(data, options.radius, () => 1)
131+
const textValues = channelValues(data, options.text, (datum) =>
132+
datum == null ? '' : String(datum),
133+
)
134+
const priorityValues = channelValues(data, options.priority, (datum) =>
135+
numberProperty(datum, 'value'),
136+
)
137+
const groups = channelValues(data, options.z, () => null)
138+
const colorValues =
139+
options.color === undefined
140+
? groups
141+
: channelValues(data, options.color, () => null)
142+
const keys = inferredKeyValues(data, options.key, { groups })
143+
144+
// Scale IDs let the polar container validate them before render.
145+
const initialized: InitializedPolarMark<
146+
TDatum,
147+
ChartValue,
148+
ChartValue
149+
> & {
150+
angleScale: string
151+
radiusScale: string
152+
} = {
153+
id,
154+
states: markStates(data, defaultStates),
155+
angleScale,
156+
radiusScale,
157+
colorValues: colorValues.filter(isChartKey),
158+
angleValues: angleValues.filter(isChartValue),
159+
radiusValues: radiusValues.filter(isChartValue),
160+
includeZeroRadius: false,
161+
requiresAngleScale: true,
162+
requiresRadiusScale: true,
163+
render: ({ layout, color: resolveColor, theme }) => {
164+
const angle = layout.scales[angleScale]!
165+
const radius = layout.scales[radiusScale]!
166+
const candidates = data.flatMap((_datum, datumIndex) => {
167+
const anglePosition = position(angle, angleValues[datumIndex])
168+
const radiusPosition = position(radius, radiusValues[datumIndex])
169+
const text = textValues[datumIndex]
170+
if (
171+
text == null ||
172+
text === '' ||
173+
!isFiniteNumber(anglePosition) ||
174+
!isFiniteNumber(radiusPosition)
175+
) {
176+
return []
177+
}
178+
const priority = priorityValues[datumIndex]
179+
return [
180+
{
181+
datumIndex,
182+
angle: anglePosition,
183+
radius: radiusPosition,
184+
priority: isFiniteNumber(priority) ? priority : 0,
185+
width: measureSceneLabelBounds(
186+
{
187+
kind: 'label',
188+
key: '',
189+
x: 0,
190+
y: 0,
191+
text: String(text),
192+
anchor: 'start',
193+
baseline: 'middle',
194+
fontSize,
195+
fontWeight: options.fontWeight,
196+
},
197+
estimateSceneText,
198+
).width,
199+
},
200+
]
201+
})
202+
const placements = layoutRadialLabels(candidates, {
203+
radius: Math.max(0, ...candidates.map(({ radius }) => radius)),
204+
...radialLabelSpacing,
205+
lineHeight: fontSize * 1.4,
206+
top: layout.chart.y - layout.centerY,
207+
bottom: layout.chart.y + layout.chart.height - layout.centerY,
208+
left: layout.chart.x - layout.centerX,
209+
right: layout.chart.x + layout.chart.width - layout.centerX,
210+
maxShift: options.maxShift ?? Infinity,
211+
})
212+
const connectors: SceneNode[] = []
213+
const labels: SceneNode[] = []
214+
const points: ChartPoint<TDatum>[] = []
215+
candidates.forEach((candidate, candidateIndex) => {
216+
const placement = placements[candidateIndex]
217+
if (!placement?.visible) return
218+
const { datumIndex } = candidate
219+
const datum = data[datumIndex] as TDatum
220+
const group = groups[datumIndex] ?? null
221+
const colorValue = colorValues[datumIndex] ?? null
222+
const fill = visualValue(
223+
options.fill,
224+
datum,
225+
datumIndex,
226+
data,
227+
colorValue == null ? theme.foreground : resolveColor(colorValue),
228+
)
229+
const stroke = visualValue(
230+
options.stroke,
231+
datum,
232+
datumIndex,
233+
data,
234+
fill,
235+
)
236+
const key = `${id}:${valueKey(group)}:${valueKey(keys[datumIndex])}`
237+
const [start, ...rest] = placement.connector
238+
connectors.push({
239+
kind: 'polyline',
240+
key: `${key}:connector`,
241+
points: [],
242+
path: `M${start!.join(',')}${rest.map((point) => `L${point.join(',')}`).join('')}`,
243+
style: {
244+
fill: 'none',
245+
stroke,
246+
strokeOpacity: options.strokeOpacity,
247+
strokeWidth: options.strokeWidth ?? 1,
248+
opacity: options.opacity,
249+
lineCap: 'round',
250+
lineJoin: 'round',
251+
},
252+
})
253+
labels.push({
254+
kind: 'label',
255+
key,
256+
x: placement.x,
257+
y: placement.y,
258+
text: String(textValues[datumIndex]),
259+
anchor: physicalTextAnchor(
260+
placement.side === 'left' ? 'right' : 'left',
261+
layout.direction,
262+
),
263+
baseline: 'middle',
264+
fontSize,
265+
fontWeight: options.fontWeight,
266+
style: { fill, opacity: options.opacity },
267+
})
268+
points.push(
269+
withPolarFocusGeometry(
270+
{
271+
key,
272+
markId: id,
273+
group,
274+
groupLabel: group == null ? id : String(group),
275+
datum,
276+
datumIndex,
277+
xValue: angleValues[datumIndex] as ChartValue,
278+
yValue: radiusValues[datumIndex] as ChartValue,
279+
x: layout.centerX + placement.x,
280+
y: layout.centerY + placement.y,
281+
color: fill,
282+
},
283+
layout,
284+
candidate.angle,
285+
candidate.radius,
286+
placement.x,
287+
placement.y,
288+
),
289+
)
290+
})
291+
return {
292+
nodes: [
293+
{
294+
kind: 'group',
295+
key: id,
296+
className: options.className
297+
? `ts-chart__radial-labels ts-chart__text ${options.className}`
298+
: 'ts-chart__radial-labels ts-chart__text',
299+
ariaHidden: true,
300+
children: [...connectors, ...labels],
301+
},
302+
],
303+
points,
304+
}
305+
},
306+
}
307+
return initialized
308+
},
309+
options.motion,
310+
options.renderer,
311+
)
312+
return mark as unknown as PolarMark<TDatum, any, any>
313+
}
314+
315+
function position(scale: PolarResolvedScale, value: unknown): number {
316+
return isChartValue(value) ? scale.map(value) : Number.NaN
317+
}
318+
319+
function numberProperty(value: unknown, key: string): number | undefined {
320+
if (!value || typeof value !== 'object') return undefined
321+
const property = (value as Record<string, unknown>)[key]
322+
return isFiniteNumber(property) ? property : undefined
323+
}

‎packages/charts-core/src/polar-mark-internal.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import type {
66
ChartMarkState,
77
InitializedMark,
88
ChartTheme,
9-
ChartTextMeasurer,
109
ChartTextTypography,
1110
ChartValue,
1211
MarkScene,
@@ -63,8 +62,6 @@ export interface PolarMarkRenderContext {
6362
layout: PolarLayoutContext
6463
color: (value: ChartKey | null | undefined) => string
6564
theme: ChartTheme
66-
/** Typography-aware text measurer from the chart layout. */
67-
measureText?: ChartTextMeasurer
6865
}
6966

7067
export interface PolarMark<

0 commit comments

Comments
 (0)