@orbcharts/plugins-basic 3.0.8 → 3.0.10

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.
Files changed (120) hide show
  1. package/LICENSE +200 -200
  2. package/dist/orbcharts-plugins-basic.es.js +6182 -6004
  3. package/dist/orbcharts-plugins-basic.umd.js +44 -44
  4. package/dist/src/series/defaults.d.ts +2 -1
  5. package/dist/src/series/index.d.ts +1 -0
  6. package/dist/src/series/plugins/Indicator.d.ts +3 -0
  7. package/lib/core-types.ts +7 -7
  8. package/lib/core.ts +6 -6
  9. package/lib/gridObservables.ts +6 -6
  10. package/lib/plugins-basic-types.ts +6 -6
  11. package/package.json +48 -48
  12. package/src/base/BaseBars.ts +765 -765
  13. package/src/base/BaseBarsTriangle.ts +676 -676
  14. package/src/base/BaseDots.ts +464 -464
  15. package/src/base/BaseGroupAxis.ts +691 -691
  16. package/src/base/BaseLegend.ts +684 -684
  17. package/src/base/BaseLineAreas.ts +629 -629
  18. package/src/base/BaseLines.ts +706 -706
  19. package/src/base/BaseOrdinalBubbles.ts +729 -729
  20. package/src/base/BaseRacingBars.ts +582 -582
  21. package/src/base/BaseRacingLabels.ts +404 -404
  22. package/src/base/BaseRacingValueLabels.ts +403 -403
  23. package/src/base/BaseStackedBars.ts +793 -793
  24. package/src/base/BaseTooltip.ts +408 -408
  25. package/src/base/BaseValueAxis.ts +600 -600
  26. package/src/base/BaseXAxis.ts +427 -427
  27. package/src/base/BaseXZoom.ts +241 -241
  28. package/src/base/BaseYAxis.ts +389 -389
  29. package/src/base/types.ts +2 -2
  30. package/src/const.ts +30 -30
  31. package/src/grid/defaults.ts +213 -213
  32. package/src/grid/gridObservables.ts +635 -635
  33. package/src/grid/index.ts +16 -16
  34. package/src/grid/plugins/Bars.ts +69 -69
  35. package/src/grid/plugins/BarsPN.ts +66 -66
  36. package/src/grid/plugins/BarsTriangle.ts +73 -73
  37. package/src/grid/plugins/Dots.ts +68 -68
  38. package/src/grid/plugins/GridLegend.ts +107 -107
  39. package/src/grid/plugins/GridTooltip.ts +66 -66
  40. package/src/grid/plugins/GroupAux.ts +1095 -1095
  41. package/src/grid/plugins/GroupAxis.ts +73 -73
  42. package/src/grid/plugins/GroupZoom.ts +218 -218
  43. package/src/grid/plugins/LineAreas.ts +65 -65
  44. package/src/grid/plugins/Lines.ts +59 -59
  45. package/src/grid/plugins/StackedBars.ts +66 -66
  46. package/src/grid/plugins/StackedValueAxis.ts +97 -97
  47. package/src/grid/plugins/ValueAxis.ts +94 -94
  48. package/src/index.ts +6 -6
  49. package/src/multiGrid/defaults.ts +244 -244
  50. package/src/multiGrid/index.ts +14 -14
  51. package/src/multiGrid/multiGridObservables.ts +50 -50
  52. package/src/multiGrid/plugins/MultiBars.ts +108 -108
  53. package/src/multiGrid/plugins/MultiBarsTriangle.ts +114 -114
  54. package/src/multiGrid/plugins/MultiDots.ts +102 -102
  55. package/src/multiGrid/plugins/MultiGridLegend.ts +169 -169
  56. package/src/multiGrid/plugins/MultiGridTooltip.ts +66 -66
  57. package/src/multiGrid/plugins/MultiGroupAxis.ts +137 -137
  58. package/src/multiGrid/plugins/MultiLineAreas.ts +107 -107
  59. package/src/multiGrid/plugins/MultiLines.ts +101 -101
  60. package/src/multiGrid/plugins/MultiStackedBars.ts +109 -109
  61. package/src/multiGrid/plugins/MultiStackedValueAxis.ts +135 -135
  62. package/src/multiGrid/plugins/MultiValueAxis.ts +134 -134
  63. package/src/multiGrid/plugins/OverlappingStackedValueAxes.ts +300 -300
  64. package/src/multiGrid/plugins/OverlappingValueAxes.ts +300 -300
  65. package/src/multiValue/defaults.ts +523 -523
  66. package/src/multiValue/index.ts +16 -16
  67. package/src/multiValue/multiValueObservables.ts +781 -781
  68. package/src/multiValue/plugins/MultiValueLegend.ts +107 -107
  69. package/src/multiValue/plugins/MultiValueTooltip.ts +66 -66
  70. package/src/multiValue/plugins/OrdinalAux.ts +660 -660
  71. package/src/multiValue/plugins/OrdinalAxis.ts +524 -524
  72. package/src/multiValue/plugins/OrdinalBubbles.ts +226 -226
  73. package/src/multiValue/plugins/OrdinalZoom.ts +57 -57
  74. package/src/multiValue/plugins/RacingBars.ts +375 -375
  75. package/src/multiValue/plugins/RacingCounterTexts.ts +300 -300
  76. package/src/multiValue/plugins/RacingValueAxis.ts +114 -114
  77. package/src/multiValue/plugins/Scatter.ts +486 -486
  78. package/src/multiValue/plugins/ScatterBubbles.ts +635 -635
  79. package/src/multiValue/plugins/XAxis.ts +107 -107
  80. package/src/multiValue/plugins/XYAux.ts +683 -683
  81. package/src/multiValue/plugins/XYAxes.ts +194 -194
  82. package/src/multiValue/plugins/XYAxes_legacy.ts +683 -683
  83. package/src/multiValue/plugins/XZoom.ts +40 -40
  84. package/src/noneData/defaults.ts +102 -102
  85. package/src/noneData/index.ts +3 -3
  86. package/src/noneData/plugins/Container.ts +27 -27
  87. package/src/noneData/plugins/Tooltip.ts +373 -373
  88. package/src/relationship/defaults.ts +221 -221
  89. package/src/relationship/index.ts +5 -5
  90. package/src/relationship/plugins/ForceDirected.ts +1056 -1056
  91. package/src/relationship/plugins/ForceDirectedBubbles.ts +1294 -1294
  92. package/src/relationship/plugins/RelationshipLegend.ts +100 -100
  93. package/src/relationship/plugins/RelationshipTooltip.ts +66 -66
  94. package/src/relationship/relationshipObservables.ts +49 -49
  95. package/src/series/defaults.ts +236 -224
  96. package/src/series/index.ts +10 -9
  97. package/src/series/plugins/Bubbles.ts +784 -784
  98. package/src/series/plugins/Indicator.ts +298 -0
  99. package/src/series/plugins/Pie.ts +622 -622
  100. package/src/series/plugins/PieEventTexts.ts +283 -283
  101. package/src/series/plugins/PieLabels.ts +639 -639
  102. package/src/series/plugins/Rose.ts +515 -515
  103. package/src/series/plugins/RoseLabels.ts +599 -599
  104. package/src/series/plugins/SeriesLegend.ts +107 -107
  105. package/src/series/plugins/SeriesTooltip.ts +66 -66
  106. package/src/series/seriesObservables.ts +168 -168
  107. package/src/series/seriesUtils.ts +51 -51
  108. package/src/tree/defaults.ts +102 -102
  109. package/src/tree/index.ts +4 -4
  110. package/src/tree/plugins/TreeLegend.ts +100 -100
  111. package/src/tree/plugins/TreeMap.ts +341 -341
  112. package/src/tree/plugins/TreeTooltip.ts +66 -66
  113. package/src/utils/commonUtils.ts +31 -31
  114. package/src/utils/d3Graphics.ts +176 -176
  115. package/src/utils/d3Utils.ts +92 -92
  116. package/src/utils/observables.ts +14 -14
  117. package/src/utils/orbchartsUtils.ts +129 -129
  118. package/tsconfig.base.json +13 -13
  119. package/tsconfig.json +2 -2
  120. package/vite.config.js +22 -22
@@ -1,639 +1,639 @@
1
- import * as d3 from 'd3'
2
- import {
3
- combineLatest,
4
- switchMap,
5
- first,
6
- map,
7
- takeUntil,
8
- Observable,
9
- distinctUntilChanged,
10
- Subject,
11
- BehaviorSubject } from 'rxjs'
12
- import type { DefinePluginConfig } from '../../../lib/core-types'
13
- import {
14
- defineSeriesPlugin } from '../../../lib/core'
15
- import type {
16
- ComputedDatumSeries,
17
- ContainerPosition,
18
- EventSeries,
19
- ChartParams } from '../../../lib/core-types'
20
- import type { PieLabelsParams } from '../../../lib/plugins-basic-types'
21
- import type { PieDatum } from '../seriesUtils'
22
- import { DEFAULT_PIE_LABELS_PARAMS } from '../defaults'
23
- import { makePieData } from '../seriesUtils'
24
- import { makeD3Arc } from '../../utils/d3Utils'
25
- import { getDatumColor, getClassName } from '../../utils/orbchartsUtils'
26
- import { seriesCenterSelectionObservable } from '../seriesObservables'
27
- import { renderTspansOnQuadrant } from '../../utils/d3Graphics'
28
- import { LAYER_INDEX_OF_LABEL } from '../../const'
29
- import {} from '../../../lib/core'
30
-
31
- interface RenderDatum {
32
- pieDatum: PieDatum
33
- arcIndex: number
34
- arcLabels: string[]
35
- lineStartX: number
36
- lineStartY: number
37
- lineStartMouseoverX: number
38
- lineStartMouseoverY: number
39
- x: number
40
- y: number
41
- mouseoverX: number
42
- mouseoverY: number
43
- textWidth: number, // 文字寬度
44
- collisionShiftX: number // 避免碰撞的位移
45
- collisionShiftY: number
46
- quadrant: number // 第幾象限
47
- }
48
-
49
- const pluginName = 'PieLabels'
50
- const labelGClassName = getClassName(pluginName, 'label-g')
51
- const lineGClassName = getClassName(pluginName, 'line-g')
52
- const textClassName = getClassName(pluginName, 'text')
53
-
54
- const pieOuterCentroid = 2
55
-
56
- const pluginConfig: DefinePluginConfig<typeof pluginName, typeof DEFAULT_PIE_LABELS_PARAMS> = {
57
- name: pluginName,
58
- defaultParams: DEFAULT_PIE_LABELS_PARAMS,
59
- layerIndex: LAYER_INDEX_OF_LABEL,
60
- validator: (params, { validateColumns }) => {
61
- const result = validateColumns(params, {
62
- outerRadius: {
63
- toBeTypes: ['number'],
64
- },
65
- outerRadiusWhileHighlight: {
66
- toBeTypes: ['number'],
67
- },
68
- startAngle: {
69
- toBeTypes: ['number'],
70
- },
71
- endAngle: {
72
- toBeTypes: ['number'],
73
- },
74
- labelCentroid: {
75
- toBeTypes: ['number'],
76
- },
77
- labelFn: {
78
- toBeTypes: ['Function'],
79
- },
80
- labelColorType: {
81
- toBeOption: 'ColorType'
82
- }
83
- })
84
- return result
85
- }
86
- }
87
-
88
-
89
- function makeRenderData ({ pieData, arc, arcMouseover, labelCentroid, lineStartCentroid, fullParams }: {
90
- pieData: PieDatum[]
91
- arc: d3.Arc<any, d3.DefaultArcObject>
92
- arcMouseover: d3.Arc<any, d3.DefaultArcObject>
93
- labelCentroid: number
94
- lineStartCentroid: number
95
- fullParams: PieLabelsParams
96
- }): RenderDatum[] {
97
- return pieData
98
- .map((d, i) => {
99
- const [_x, _y] = arc!.centroid(d as any)
100
- const [_mouseoverX, _mouseoverY] = arcMouseover!.centroid(d as any)
101
- const arcLabel = fullParams.labelFn(d.data)
102
- return {
103
- pieDatum: d,
104
- arcIndex: i,
105
- arcLabels: arcLabel.split('\n'),
106
- lineStartX: _x * lineStartCentroid,
107
- lineStartY: _y * lineStartCentroid,
108
- lineStartMouseoverX: _mouseoverX * lineStartCentroid,
109
- lineStartMouseoverY: _mouseoverY * lineStartCentroid,
110
- x: _x * labelCentroid!,
111
- y: _y * labelCentroid!,
112
- mouseoverX: _mouseoverX * labelCentroid!,
113
- mouseoverY: _mouseoverY * labelCentroid!,
114
- textWidth: 0, // 後面再做計算
115
- collisionShiftX: 0, // 後面再做計算
116
- collisionShiftY: 0, // 後面再做計算
117
- quadrant: _x >= 0 && _y <= 0
118
- ? 1
119
- : _x < 0 && _y <= 0
120
- ? 2
121
- : _x < 0 && _y > 0
122
- ? 3
123
- : 4
124
- }
125
- })
126
- .filter(d => d.pieDatum.data.visible)
127
- }
128
-
129
- // 繪製圓餅圖
130
- function renderLabel ({ labelGSelection, data, fullParams, fullChartParams, textSizePx }: {
131
- labelGSelection: d3.Selection<SVGGElement, undefined, any, any>
132
- data: RenderDatum[]
133
- fullParams: PieLabelsParams
134
- fullChartParams: ChartParams
135
- textSizePx: number
136
- }) {
137
- // console.log(data)
138
- // let update = this.gSelection.selectAll('g').data(pieData)
139
- const textSelection = labelGSelection
140
- .selectAll<SVGTextElement, RenderDatum>('text')
141
- .data(data, d => d.pieDatum.id)
142
- .join('text')
143
- .classed(textClassName, true)
144
- .attr('font-weight', 'bold')
145
- .attr('text-anchor', d => d.quadrant == 1 || d.quadrant == 4 ? 'start' : 'end')
146
- .style('dominant-baseline', d => d.quadrant == 1 || d.quadrant == 2 ? 'auto' : 'hanging')
147
- // .style('pointer-events', 'none')
148
- .style('cursor', d => fullChartParams.highlightTarget && fullChartParams.highlightTarget != 'none'
149
- ? 'pointer'
150
- : 'none')
151
- // .text(d => fullParams.labelFn(d.pieDatum.data))
152
- .attr('font-size', fullChartParams.styles.textSize)
153
- .attr('x', 0)
154
- .attr('y', 0)
155
- .attr('fill', (d, i) => getDatumColor({ datum: d.pieDatum.data, colorType: fullParams.labelColorType, fullChartParams }))
156
- .each((d, i, n) => {
157
- // const textNode = d3.select<SVGTextElement, RenderDatum>(n[i])
158
- // .selectAll('tspan')
159
- // .data(d.arcLabels)
160
- // .join('tspan')
161
- // .attr('x', 0)
162
- // .attr('y', (_d, _i) => d.quadrant == 1 || d.quadrant == 2
163
- // ? - (d.arcLabels.length - 1 - _i) * textSizePx
164
- // : _i * textSizePx)
165
- // .text(d => d)
166
- renderTspansOnQuadrant(d3.select<SVGTextElement, RenderDatum>(n[i]), {
167
- textArr: d.arcLabels,
168
- textSizePx,
169
- quadrant: d.quadrant
170
- })
171
- })
172
- textSelection
173
- .transition()
174
- .attr('transform', (d) => {
175
- // console.log('transform', d)
176
- return 'translate(' + d.x + ',' + d.y + ')'
177
- })
178
- // .on('end', () => initHighlight({ labelSelection, data, fullChartParams }))
179
-
180
- // 如無新增資料則不用等動畫
181
- // if (enter.size() == 0) {
182
- // this.initHighlight()
183
- // }
184
-
185
- return textSelection
186
- }
187
-
188
- // // 獲取每個文字元素的邊界框並檢查是否重疊
189
- // function resolveCollisions(labelSelection: d3.Selection<SVGPathElement, RenderDatum, any, any>, data: RenderDatum[]) {
190
- // const textArray = labelSelection.nodes();
191
- // const padding = 10; // 調整文字間的間距
192
-
193
- // // 存儲每個標籤的當前位置
194
- // const positions = textArray.map((textNode, i) => {
195
- // const bbox = textNode.getBBox();
196
- // // const arcCentroid = arc.centroid(data[i]);
197
- // const arcCentroid = [data[i].x, data[i].y];
198
- // return {
199
- // node: textNode,
200
- // x: arcCentroid[0],
201
- // y: arcCentroid[1],
202
- // width: bbox.width,
203
- // height: bbox.height
204
- // };
205
- // });
206
- // // console.log('positions', positions)
207
-
208
- // for (let i = 0; i < positions.length; i++) {
209
- // const a = positions[i];
210
-
211
- // for (let j = i + 1; j < positions.length; j++) {
212
- // const b = positions[j];
213
-
214
- // // 檢查是否重疊
215
- // if (!(a.x + a.width / 2 < b.x - b.width / 2 ||
216
- // a.x - a.width / 2 > b.x + b.width / 2 ||
217
- // a.y + a.height / 2 < b.y - b.height / 2 ||
218
- // a.y - a.height / 2 > b.y + b.height / 2)) {
219
-
220
- // // 如果有重疊,則位移其中一個文字,這裡我們進行上下位移
221
- // const moveDown = (b.y > a.y) ? padding : -padding; // 決定方向
222
- // b.y += moveDown; // 更新 b 的 y 座標
223
-
224
- // // 更新 b 的 x 座標,根據與 a 的位置差異進行微調
225
- // const moveRight = (b.x > a.x) ? padding : -padding;
226
- // b.x += moveRight;
227
-
228
- // // // 重新設置 b 的 transform 來移動
229
- // d3.select(b.node)
230
- // .transition()
231
- // .attr("transform", `translate(${b.x},${b.y})`);
232
-
233
- // data[j].collisionShiftX = moveRight
234
- // data[j].collisionShiftY = moveDown
235
- // }
236
- // }
237
- // }
238
- // }
239
-
240
- // 獲取每個文字元素的邊界框並檢查是否重疊
241
- function resolveCollisions(textSelection: d3.Selection<SVGTextElement, RenderDatum, any, any>, data: RenderDatum[], textSizePx: number) {
242
- const textArray = textSelection.nodes();
243
- const padding = textSizePx // 調整文字間的間距
244
-
245
- // 存儲每個標籤的當前位置
246
- const positions = textArray.map((textNode, i) => {
247
- const bbox = textNode.getBBox();
248
- // const arcCentroid = arc.centroid(data[i]);
249
- const arcCentroid = [data[i].x, data[i].y];
250
- return {
251
- node: textNode,
252
- x: arcCentroid[0],
253
- y: arcCentroid[1],
254
- width: bbox.width,
255
- height: bbox.height
256
- }
257
- })
258
-
259
- // 順時針碰撞檢測(只處理 2、4 象限,將較後面的文字碰撞時往外偏移)
260
- for (let i = 0; i < positions.length; i++) {
261
- const a = positions[i]
262
-
263
- for (let j = i + 1; j < positions.length; j++) {
264
- const b = positions[j]
265
-
266
- // 記錄文字寬度
267
- data[i].textWidth = a.width
268
-
269
- const ax = a.x + data[i].collisionShiftX
270
- const ay = a.y + data[i].collisionShiftY
271
- const bx = b.x + data[j].collisionShiftX
272
- const by = b.y + data[j].collisionShiftY
273
-
274
- // 檢查是否重疊
275
- if (!(ax + a.width / 2 < bx - b.width / 2 ||
276
- ax - a.width / 2 > bx + b.width / 2 ||
277
- ay + a.height / 2 < by - b.height / 2 ||
278
- ay - a.height / 2 > by + b.height / 2)) {
279
-
280
- if (data[j].quadrant == 2) {
281
- const moveDown = (by > ay)
282
- ? -padding * 2
283
- : -padding
284
- data[j].collisionShiftY += moveDown // 由後一個累加高度
285
- } else if (data[j].quadrant == 4) {
286
- const moveDown = (by > ay)
287
- ? padding
288
- : padding * 2
289
- data[j].collisionShiftY += moveDown // 由後一個累加高度
290
- }
291
- }
292
- }
293
- }
294
-
295
- // 逆時針碰撞檢測(只處理 1、3 象限,將較前面的文字碰撞時往外偏移)
296
- for (let i = positions.length - 1; i >= 0; i--) {
297
- const a = positions[i]
298
-
299
- for (let j = i - 1; j >= 0; j--) {
300
- const b = positions[j]
301
-
302
- // 記錄文字寬度
303
- data[i].textWidth = a.width
304
-
305
- const ax = a.x + data[i].collisionShiftX
306
- const ay = a.y + data[i].collisionShiftY
307
- const bx = b.x + data[j].collisionShiftX
308
- const by = b.y + data[j].collisionShiftY
309
-
310
- // 檢查是否重疊
311
- if (!(ax + a.width / 2 < bx - b.width / 2 ||
312
- ax - a.width / 2 > bx + b.width / 2 ||
313
- ay + a.height / 2 < by - b.height / 2 ||
314
- ay - a.height / 2 > by + b.height / 2)) {
315
-
316
- if (data[j].quadrant == 1) {
317
- const moveDown = (by > ay)
318
- ? -padding * 2
319
- : -padding
320
- data[j].collisionShiftY += moveDown // 由前一個累加高度
321
- } else if (data[j].quadrant == 3) {
322
- const moveDown = (by > ay)
323
- ? padding
324
- : padding * 2
325
- data[j].collisionShiftY += moveDown // 由前一個累加高度
326
- }
327
- }
328
- }
329
- }
330
-
331
- // 全部算完再來 render
332
- textSelection
333
- .data(data)
334
- .transition()
335
- .attr('transform', (d) => {
336
- return `translate(${d.x + d.collisionShiftX},${d.y + d.collisionShiftY})`
337
- })
338
- }
339
-
340
- function renderLine ({ lineGSelection, data, fullParams, fullChartParams }: {
341
- lineGSelection: d3.Selection<SVGGElement, undefined, any, any>
342
- data: RenderDatum[]
343
- fullParams: PieLabelsParams
344
- fullChartParams: ChartParams
345
- }) {
346
-
347
- // 只顯示在有偏移的標籤
348
- const filteredData = data.filter(d => d.collisionShiftX || d.collisionShiftY)
349
-
350
- // 添加標籤的連接線
351
- const lines = lineGSelection.selectAll<SVGPolylineElement, RenderDatum>("polyline")
352
- .data(filteredData, d => d.pieDatum.id)
353
- .join("polyline")
354
- .attr("stroke", d => getDatumColor({ datum: d.pieDatum.data, colorType: fullParams.labelColorType, fullChartParams }))
355
- .attr("stroke-width", 1)
356
- .attr("fill", "none")
357
- .attr("points", (d) => {
358
- return [[d.lineStartX, d.lineStartY], [d.lineStartX, d.lineStartY]] as any // 畫出從弧線中心到延伸點的線
359
- })
360
- lines
361
- .transition()
362
- .attr("points", (d) => {
363
- // const pos = arc.centroid(d) // 起點:弧線的中心點
364
- // const outerPos = [pos[0] * 2.5, pos[1] * 2.5] // 外部延伸的點(乘以倍率來延長線段)
365
-
366
- let lineEndX = d.x + d.collisionShiftX
367
- let lineEndY = d.y + d.collisionShiftY
368
- // if (d.lineStartX >= Math.abs(d.lineStartY)) {
369
- // lineEndX -= d.textWidth / 2
370
- // } else if (d.lineStartX <= - Math.abs(d.lineStartY)) {
371
- // lineEndX += d.textWidth / 2
372
- // }
373
-
374
- return [[lineEndX, lineEndY], [d.lineStartX, d.lineStartY]] as any // 畫出從弧線中心到延伸點的線
375
- })
376
-
377
- return lines
378
- }
379
-
380
- function highlight ({ textSelection, lineSelection, ids, fullChartParams }: {
381
- textSelection: d3.Selection<SVGTextElement, RenderDatum, any, any>
382
- lineSelection: d3.Selection<SVGPolylineElement, RenderDatum, any, any>
383
- ids: string[]
384
- fullChartParams: ChartParams
385
- }) {
386
- textSelection.interrupt('highlight')
387
- lineSelection.interrupt('highlight')
388
-
389
- if (!ids.length) {
390
- textSelection
391
- .transition('highlight')
392
- .duration(200)
393
- .attr('transform', (d) => {
394
- return `translate(${d.x + d.collisionShiftX},${d.y + d.collisionShiftY})`
395
- })
396
- .style('opacity', 1)
397
- lineSelection
398
- .transition('highlight')
399
- .duration(200)
400
- .style('opacity', 1)
401
- return
402
- }
403
-
404
- textSelection.each((d, i, n) => {
405
- const segment = d3.select<SVGTextElement, RenderDatum>(n[i])
406
-
407
- if (ids.includes(d.pieDatum.id)) {
408
- segment
409
- .style('opacity', 1)
410
- .transition('highlight')
411
- .duration(200)
412
- .attr('transform', (d) => {
413
- // 如果已經有偏移過,則使用偏移後的位置(如果再改變的話很容易造成文字重疊)
414
- if (d.collisionShiftX || d.collisionShiftY) {
415
- return `translate(${d.x + d.collisionShiftX},${d.y + d.collisionShiftY})`
416
- }
417
- return `translate(${d.mouseoverX + d.collisionShiftX},${d.mouseoverY + d.collisionShiftY})`
418
- })
419
- } else {
420
- segment
421
- .style('opacity', fullChartParams.styles.unhighlightedOpacity)
422
- .transition('highlight')
423
- .duration(200)
424
- .attr('transform', (d) => {
425
- return `translate(${d.x + d.collisionShiftX},${d.y + d.collisionShiftY})`
426
- })
427
- }
428
- })
429
- lineSelection.each((d, i, n) => {
430
- const segment = d3.select<SVGPolylineElement, RenderDatum>(n[i])
431
-
432
- if (ids.includes(d.pieDatum.data.id)) {
433
- segment
434
- .style('opacity', 1)
435
- .transition('highlight')
436
- .duration(200)
437
- } else {
438
- segment
439
- .style('opacity', fullChartParams.styles.unhighlightedOpacity)
440
- .transition('highlight')
441
- .duration(200)
442
- }
443
- })
444
- }
445
-
446
-
447
- function createEachPieLabel (pluginName: string, context: {
448
- containerSelection: d3.Selection<SVGGElement, any, any, unknown>
449
- // computedData$: Observable<ComputedDatumSeries[][]>
450
- containerVisibleComputedSortedData$: Observable<ComputedDatumSeries[]>
451
- // SeriesDataMap$: Observable<Map<string, ComputedDatumSeries[]>>
452
- fullParams$: Observable<PieLabelsParams>
453
- fullChartParams$: Observable<ChartParams>
454
- textSizePx$: Observable<number>
455
- seriesHighlight$: Observable<ComputedDatumSeries[]>
456
- seriesContainerPosition$: Observable<ContainerPosition>
457
- event$: Subject<EventSeries>
458
- }) {
459
- const destroy$ = new Subject()
460
-
461
- context.containerSelection.selectAll('g').remove()
462
-
463
- const lineGSelection: d3.Selection<SVGGElement, any, any, unknown> = context.containerSelection.append('g')
464
- lineGSelection.classed(lineGClassName, true)
465
- const labelGSelection: d3.Selection<SVGGElement, any, any, unknown> = context.containerSelection.append('g')
466
- labelGSelection.classed(labelGClassName, true)
467
-
468
- // const graphicSelection: d3.Selection<SVGGElement, any, any, any> = selection.append('g')
469
- const textSelection$: Subject<d3.Selection<SVGTextElement, RenderDatum, any, any>> = new Subject()
470
- const lineSelection$: Subject<d3.Selection<SVGPolylineElement, RenderDatum, any, any>> = new Subject()
471
- let renderData: RenderDatum[] = []
472
-
473
- const shorterSideWith$ = context.seriesContainerPosition$.pipe(
474
- takeUntil(destroy$),
475
- map(d => d.width < d.height ? d.width : d.height),
476
- distinctUntilChanged()
477
- )
478
-
479
- const lineStartCentroid$ = context.fullParams$.pipe(
480
- takeUntil(destroy$),
481
- map(d => {
482
- return d.labelCentroid >= pieOuterCentroid
483
- ? pieOuterCentroid // 當 label在 pie的外側時,線條從 pie的邊緣開始
484
- : d.labelCentroid // 當 label在 pie的內側時,線條從 label未偏移前的位置開始
485
-
486
- })
487
- )
488
-
489
- combineLatest({
490
- shorterSideWith: shorterSideWith$,
491
- containerVisibleComputedSortedData: context.containerVisibleComputedSortedData$,
492
- fullParams: context.fullParams$,
493
- fullChartParams: context.fullChartParams$,
494
- textSizePx: context.textSizePx$,
495
- lineStartCentroid: lineStartCentroid$
496
- }).pipe(
497
- takeUntil(destroy$),
498
- switchMap(async (d) => d),
499
- ).subscribe(data => {
500
-
501
- // 弧產生器 (d3.arc())
502
- const arc = makeD3Arc({
503
- axisWidth: data.shorterSideWith,
504
- innerRadius: 0,
505
- outerRadius: data.fullParams.outerRadius,
506
- padAngle: 0,
507
- cornerRadius: 0
508
- })
509
-
510
- const arcMouseover = makeD3Arc({
511
- axisWidth: data.shorterSideWith,
512
- innerRadius: 0,
513
- outerRadius: data.fullParams.outerRadiusWhileHighlight, // 外半徑變化
514
- padAngle: 0,
515
- cornerRadius: 0
516
- })
517
-
518
- const pieData = makePieData({
519
- data: data.containerVisibleComputedSortedData,
520
- startAngle: data.fullParams.startAngle,
521
- endAngle: data.fullParams.endAngle
522
- })
523
-
524
- renderData = makeRenderData({
525
- pieData,
526
- arc,
527
- arcMouseover,
528
- labelCentroid: data.fullParams.labelCentroid,
529
- lineStartCentroid: data.lineStartCentroid,
530
- fullParams: data.fullParams
531
- })
532
-
533
- // 先移除線條,等偏移後再重新繪製
534
- lineGSelection.selectAll('polyline').remove()
535
-
536
- const textSelection = renderLabel({
537
- labelGSelection,
538
- data: renderData,
539
- fullParams: data.fullParams,
540
- fullChartParams: data.fullChartParams,
541
- textSizePx: data.textSizePx
542
- })
543
-
544
- // 等 label 本身的 transition 結束後再進行碰撞檢測
545
- setTimeout(() => {
546
- // resolveCollisions(labelSelection, renderData)
547
- // 偏移 label
548
- resolveCollisions(textSelection, renderData, data.textSizePx)
549
-
550
- const lineSelection = renderLine({ lineGSelection, data: renderData, fullParams: data.fullParams, fullChartParams: data.fullChartParams })
551
-
552
- lineSelection$.next(lineSelection)
553
-
554
- }, 1000)
555
-
556
- textSelection$.next(textSelection)
557
-
558
- })
559
-
560
- combineLatest({
561
- textSelection: textSelection$,
562
- lineSelection: lineSelection$,
563
- highlight: context.seriesHighlight$.pipe(
564
- map(data => data.map(d => d.id))
565
- ),
566
- fullChartParams: context.fullChartParams$,
567
- }).pipe(
568
- takeUntil(destroy$),
569
- switchMap(async d => d)
570
- ).subscribe(data => {
571
- highlight({
572
- textSelection: data.textSelection,
573
- lineSelection: data.lineSelection,
574
- ids: data.highlight,
575
- fullChartParams: data.fullChartParams,
576
- })
577
- })
578
-
579
- return () => {
580
- destroy$.next(undefined)
581
- }
582
- }
583
-
584
-
585
- export const PieLabels = defineSeriesPlugin(pluginConfig)(({ selection, observer, subject }) => {
586
-
587
- const destroy$ = new Subject()
588
-
589
- const { seriesCenterSelection$ } = seriesCenterSelectionObservable({
590
- selection: selection,
591
- pluginName,
592
- visibleComputedSortedData$: observer.visibleComputedSortedData$,
593
- seriesContainerPosition$: observer.seriesContainerPosition$
594
- })
595
-
596
- const unsubscribeFnArr: (() => void)[] = []
597
-
598
- seriesCenterSelection$
599
- .pipe(
600
- takeUntil(destroy$)
601
- )
602
- .subscribe(seriesCenterSelection => {
603
- // 每次重新計算時,清除之前的訂閱
604
- unsubscribeFnArr.forEach(fn => fn())
605
-
606
- seriesCenterSelection.each((d, containerIndex, g) => {
607
-
608
- const containerSelection = d3.select(g[containerIndex])
609
-
610
- const containerVisibleComputedSortedData$ = observer.visibleComputedSortedData$.pipe(
611
- takeUntil(destroy$),
612
- map(data => data[containerIndex] ?? data[0])
613
- )
614
-
615
- const containerPosition$ = observer.seriesContainerPosition$.pipe(
616
- takeUntil(destroy$),
617
- map(data => data[containerIndex] ?? data[0])
618
- )
619
-
620
- unsubscribeFnArr[containerIndex] = createEachPieLabel(pluginName, {
621
- containerSelection: containerSelection,
622
- // computedData$: observer.computedData$,
623
- containerVisibleComputedSortedData$: containerVisibleComputedSortedData$,
624
- // SeriesDataMap$: observer.SeriesDataMap$,
625
- fullParams$: observer.fullParams$,
626
- fullChartParams$: observer.fullChartParams$,
627
- textSizePx$: observer.textSizePx$,
628
- seriesHighlight$: observer.seriesHighlight$,
629
- seriesContainerPosition$: containerPosition$,
630
- event$: subject.event$,
631
- })
632
-
633
- })
634
- })
635
-
636
- return () => {
637
- destroy$.next(undefined)
638
- }
639
- })
1
+ import * as d3 from 'd3'
2
+ import {
3
+ combineLatest,
4
+ switchMap,
5
+ first,
6
+ map,
7
+ takeUntil,
8
+ Observable,
9
+ distinctUntilChanged,
10
+ Subject,
11
+ BehaviorSubject } from 'rxjs'
12
+ import type { DefinePluginConfig } from '../../../lib/core-types'
13
+ import {
14
+ defineSeriesPlugin } from '../../../lib/core'
15
+ import type {
16
+ ComputedDatumSeries,
17
+ ContainerPosition,
18
+ EventSeries,
19
+ ChartParams } from '../../../lib/core-types'
20
+ import type { PieLabelsParams } from '../../../lib/plugins-basic-types'
21
+ import type { PieDatum } from '../seriesUtils'
22
+ import { DEFAULT_PIE_LABELS_PARAMS } from '../defaults'
23
+ import { makePieData } from '../seriesUtils'
24
+ import { makeD3Arc } from '../../utils/d3Utils'
25
+ import { getDatumColor, getClassName } from '../../utils/orbchartsUtils'
26
+ import { seriesCenterSelectionObservable } from '../seriesObservables'
27
+ import { renderTspansOnQuadrant } from '../../utils/d3Graphics'
28
+ import { LAYER_INDEX_OF_LABEL } from '../../const'
29
+ import {} from '../../../lib/core'
30
+
31
+ interface RenderDatum {
32
+ pieDatum: PieDatum
33
+ arcIndex: number
34
+ arcLabels: string[]
35
+ lineStartX: number
36
+ lineStartY: number
37
+ lineStartMouseoverX: number
38
+ lineStartMouseoverY: number
39
+ x: number
40
+ y: number
41
+ mouseoverX: number
42
+ mouseoverY: number
43
+ textWidth: number, // 文字寬度
44
+ collisionShiftX: number // 避免碰撞的位移
45
+ collisionShiftY: number
46
+ quadrant: number // 第幾象限
47
+ }
48
+
49
+ const pluginName = 'PieLabels'
50
+ const labelGClassName = getClassName(pluginName, 'label-g')
51
+ const lineGClassName = getClassName(pluginName, 'line-g')
52
+ const textClassName = getClassName(pluginName, 'text')
53
+
54
+ const pieOuterCentroid = 2
55
+
56
+ const pluginConfig: DefinePluginConfig<typeof pluginName, typeof DEFAULT_PIE_LABELS_PARAMS> = {
57
+ name: pluginName,
58
+ defaultParams: DEFAULT_PIE_LABELS_PARAMS,
59
+ layerIndex: LAYER_INDEX_OF_LABEL,
60
+ validator: (params, { validateColumns }) => {
61
+ const result = validateColumns(params, {
62
+ outerRadius: {
63
+ toBeTypes: ['number'],
64
+ },
65
+ outerRadiusWhileHighlight: {
66
+ toBeTypes: ['number'],
67
+ },
68
+ startAngle: {
69
+ toBeTypes: ['number'],
70
+ },
71
+ endAngle: {
72
+ toBeTypes: ['number'],
73
+ },
74
+ labelCentroid: {
75
+ toBeTypes: ['number'],
76
+ },
77
+ labelFn: {
78
+ toBeTypes: ['Function'],
79
+ },
80
+ labelColorType: {
81
+ toBeOption: 'ColorType'
82
+ }
83
+ })
84
+ return result
85
+ }
86
+ }
87
+
88
+
89
+ function makeRenderData ({ pieData, arc, arcMouseover, labelCentroid, lineStartCentroid, fullParams }: {
90
+ pieData: PieDatum[]
91
+ arc: d3.Arc<any, d3.DefaultArcObject>
92
+ arcMouseover: d3.Arc<any, d3.DefaultArcObject>
93
+ labelCentroid: number
94
+ lineStartCentroid: number
95
+ fullParams: PieLabelsParams
96
+ }): RenderDatum[] {
97
+ return pieData
98
+ .map((d, i) => {
99
+ const [_x, _y] = arc!.centroid(d as any)
100
+ const [_mouseoverX, _mouseoverY] = arcMouseover!.centroid(d as any)
101
+ const arcLabel = fullParams.labelFn(d.data)
102
+ return {
103
+ pieDatum: d,
104
+ arcIndex: i,
105
+ arcLabels: arcLabel.split('\n'),
106
+ lineStartX: _x * lineStartCentroid,
107
+ lineStartY: _y * lineStartCentroid,
108
+ lineStartMouseoverX: _mouseoverX * lineStartCentroid,
109
+ lineStartMouseoverY: _mouseoverY * lineStartCentroid,
110
+ x: _x * labelCentroid!,
111
+ y: _y * labelCentroid!,
112
+ mouseoverX: _mouseoverX * labelCentroid!,
113
+ mouseoverY: _mouseoverY * labelCentroid!,
114
+ textWidth: 0, // 後面再做計算
115
+ collisionShiftX: 0, // 後面再做計算
116
+ collisionShiftY: 0, // 後面再做計算
117
+ quadrant: _x >= 0 && _y <= 0
118
+ ? 1
119
+ : _x < 0 && _y <= 0
120
+ ? 2
121
+ : _x < 0 && _y > 0
122
+ ? 3
123
+ : 4
124
+ }
125
+ })
126
+ .filter(d => d.pieDatum.data.visible)
127
+ }
128
+
129
+ // 繪製圓餅圖
130
+ function renderLabel ({ labelGSelection, data, fullParams, fullChartParams, textSizePx }: {
131
+ labelGSelection: d3.Selection<SVGGElement, undefined, any, any>
132
+ data: RenderDatum[]
133
+ fullParams: PieLabelsParams
134
+ fullChartParams: ChartParams
135
+ textSizePx: number
136
+ }) {
137
+ // console.log(data)
138
+ // let update = this.gSelection.selectAll('g').data(pieData)
139
+ const textSelection = labelGSelection
140
+ .selectAll<SVGTextElement, RenderDatum>('text')
141
+ .data(data, d => d.pieDatum.id)
142
+ .join('text')
143
+ .classed(textClassName, true)
144
+ .attr('font-weight', 'bold')
145
+ .attr('text-anchor', d => d.quadrant == 1 || d.quadrant == 4 ? 'start' : 'end')
146
+ .style('dominant-baseline', d => d.quadrant == 1 || d.quadrant == 2 ? 'auto' : 'hanging')
147
+ // .style('pointer-events', 'none')
148
+ .style('cursor', d => fullChartParams.highlightTarget && fullChartParams.highlightTarget != 'none'
149
+ ? 'pointer'
150
+ : 'none')
151
+ // .text(d => fullParams.labelFn(d.pieDatum.data))
152
+ .attr('font-size', fullChartParams.styles.textSize)
153
+ .attr('x', 0)
154
+ .attr('y', 0)
155
+ .attr('fill', (d, i) => getDatumColor({ datum: d.pieDatum.data, colorType: fullParams.labelColorType, fullChartParams }))
156
+ .each((d, i, n) => {
157
+ // const textNode = d3.select<SVGTextElement, RenderDatum>(n[i])
158
+ // .selectAll('tspan')
159
+ // .data(d.arcLabels)
160
+ // .join('tspan')
161
+ // .attr('x', 0)
162
+ // .attr('y', (_d, _i) => d.quadrant == 1 || d.quadrant == 2
163
+ // ? - (d.arcLabels.length - 1 - _i) * textSizePx
164
+ // : _i * textSizePx)
165
+ // .text(d => d)
166
+ renderTspansOnQuadrant(d3.select<SVGTextElement, RenderDatum>(n[i]), {
167
+ textArr: d.arcLabels,
168
+ textSizePx,
169
+ quadrant: d.quadrant
170
+ })
171
+ })
172
+ textSelection
173
+ .transition()
174
+ .attr('transform', (d) => {
175
+ // console.log('transform', d)
176
+ return 'translate(' + d.x + ',' + d.y + ')'
177
+ })
178
+ // .on('end', () => initHighlight({ labelSelection, data, fullChartParams }))
179
+
180
+ // 如無新增資料則不用等動畫
181
+ // if (enter.size() == 0) {
182
+ // this.initHighlight()
183
+ // }
184
+
185
+ return textSelection
186
+ }
187
+
188
+ // // 獲取每個文字元素的邊界框並檢查是否重疊
189
+ // function resolveCollisions(labelSelection: d3.Selection<SVGPathElement, RenderDatum, any, any>, data: RenderDatum[]) {
190
+ // const textArray = labelSelection.nodes();
191
+ // const padding = 10; // 調整文字間的間距
192
+
193
+ // // 存儲每個標籤的當前位置
194
+ // const positions = textArray.map((textNode, i) => {
195
+ // const bbox = textNode.getBBox();
196
+ // // const arcCentroid = arc.centroid(data[i]);
197
+ // const arcCentroid = [data[i].x, data[i].y];
198
+ // return {
199
+ // node: textNode,
200
+ // x: arcCentroid[0],
201
+ // y: arcCentroid[1],
202
+ // width: bbox.width,
203
+ // height: bbox.height
204
+ // };
205
+ // });
206
+ // // console.log('positions', positions)
207
+
208
+ // for (let i = 0; i < positions.length; i++) {
209
+ // const a = positions[i];
210
+
211
+ // for (let j = i + 1; j < positions.length; j++) {
212
+ // const b = positions[j];
213
+
214
+ // // 檢查是否重疊
215
+ // if (!(a.x + a.width / 2 < b.x - b.width / 2 ||
216
+ // a.x - a.width / 2 > b.x + b.width / 2 ||
217
+ // a.y + a.height / 2 < b.y - b.height / 2 ||
218
+ // a.y - a.height / 2 > b.y + b.height / 2)) {
219
+
220
+ // // 如果有重疊,則位移其中一個文字,這裡我們進行上下位移
221
+ // const moveDown = (b.y > a.y) ? padding : -padding; // 決定方向
222
+ // b.y += moveDown; // 更新 b 的 y 座標
223
+
224
+ // // 更新 b 的 x 座標,根據與 a 的位置差異進行微調
225
+ // const moveRight = (b.x > a.x) ? padding : -padding;
226
+ // b.x += moveRight;
227
+
228
+ // // // 重新設置 b 的 transform 來移動
229
+ // d3.select(b.node)
230
+ // .transition()
231
+ // .attr("transform", `translate(${b.x},${b.y})`);
232
+
233
+ // data[j].collisionShiftX = moveRight
234
+ // data[j].collisionShiftY = moveDown
235
+ // }
236
+ // }
237
+ // }
238
+ // }
239
+
240
+ // 獲取每個文字元素的邊界框並檢查是否重疊
241
+ function resolveCollisions(textSelection: d3.Selection<SVGTextElement, RenderDatum, any, any>, data: RenderDatum[], textSizePx: number) {
242
+ const textArray = textSelection.nodes();
243
+ const padding = textSizePx // 調整文字間的間距
244
+
245
+ // 存儲每個標籤的當前位置
246
+ const positions = textArray.map((textNode, i) => {
247
+ const bbox = textNode.getBBox();
248
+ // const arcCentroid = arc.centroid(data[i]);
249
+ const arcCentroid = [data[i].x, data[i].y];
250
+ return {
251
+ node: textNode,
252
+ x: arcCentroid[0],
253
+ y: arcCentroid[1],
254
+ width: bbox.width,
255
+ height: bbox.height
256
+ }
257
+ })
258
+
259
+ // 順時針碰撞檢測(只處理 2、4 象限,將較後面的文字碰撞時往外偏移)
260
+ for (let i = 0; i < positions.length; i++) {
261
+ const a = positions[i]
262
+
263
+ for (let j = i + 1; j < positions.length; j++) {
264
+ const b = positions[j]
265
+
266
+ // 記錄文字寬度
267
+ data[i].textWidth = a.width
268
+
269
+ const ax = a.x + data[i].collisionShiftX
270
+ const ay = a.y + data[i].collisionShiftY
271
+ const bx = b.x + data[j].collisionShiftX
272
+ const by = b.y + data[j].collisionShiftY
273
+
274
+ // 檢查是否重疊
275
+ if (!(ax + a.width / 2 < bx - b.width / 2 ||
276
+ ax - a.width / 2 > bx + b.width / 2 ||
277
+ ay + a.height / 2 < by - b.height / 2 ||
278
+ ay - a.height / 2 > by + b.height / 2)) {
279
+
280
+ if (data[j].quadrant == 2) {
281
+ const moveDown = (by > ay)
282
+ ? -padding * 2
283
+ : -padding
284
+ data[j].collisionShiftY += moveDown // 由後一個累加高度
285
+ } else if (data[j].quadrant == 4) {
286
+ const moveDown = (by > ay)
287
+ ? padding
288
+ : padding * 2
289
+ data[j].collisionShiftY += moveDown // 由後一個累加高度
290
+ }
291
+ }
292
+ }
293
+ }
294
+
295
+ // 逆時針碰撞檢測(只處理 1、3 象限,將較前面的文字碰撞時往外偏移)
296
+ for (let i = positions.length - 1; i >= 0; i--) {
297
+ const a = positions[i]
298
+
299
+ for (let j = i - 1; j >= 0; j--) {
300
+ const b = positions[j]
301
+
302
+ // 記錄文字寬度
303
+ data[i].textWidth = a.width
304
+
305
+ const ax = a.x + data[i].collisionShiftX
306
+ const ay = a.y + data[i].collisionShiftY
307
+ const bx = b.x + data[j].collisionShiftX
308
+ const by = b.y + data[j].collisionShiftY
309
+
310
+ // 檢查是否重疊
311
+ if (!(ax + a.width / 2 < bx - b.width / 2 ||
312
+ ax - a.width / 2 > bx + b.width / 2 ||
313
+ ay + a.height / 2 < by - b.height / 2 ||
314
+ ay - a.height / 2 > by + b.height / 2)) {
315
+
316
+ if (data[j].quadrant == 1) {
317
+ const moveDown = (by > ay)
318
+ ? -padding * 2
319
+ : -padding
320
+ data[j].collisionShiftY += moveDown // 由前一個累加高度
321
+ } else if (data[j].quadrant == 3) {
322
+ const moveDown = (by > ay)
323
+ ? padding
324
+ : padding * 2
325
+ data[j].collisionShiftY += moveDown // 由前一個累加高度
326
+ }
327
+ }
328
+ }
329
+ }
330
+
331
+ // 全部算完再來 render
332
+ textSelection
333
+ .data(data)
334
+ .transition()
335
+ .attr('transform', (d) => {
336
+ return `translate(${d.x + d.collisionShiftX},${d.y + d.collisionShiftY})`
337
+ })
338
+ }
339
+
340
+ function renderLine ({ lineGSelection, data, fullParams, fullChartParams }: {
341
+ lineGSelection: d3.Selection<SVGGElement, undefined, any, any>
342
+ data: RenderDatum[]
343
+ fullParams: PieLabelsParams
344
+ fullChartParams: ChartParams
345
+ }) {
346
+
347
+ // 只顯示在有偏移的標籤
348
+ const filteredData = data.filter(d => d.collisionShiftX || d.collisionShiftY)
349
+
350
+ // 添加標籤的連接線
351
+ const lines = lineGSelection.selectAll<SVGPolylineElement, RenderDatum>("polyline")
352
+ .data(filteredData, d => d.pieDatum.id)
353
+ .join("polyline")
354
+ .attr("stroke", d => getDatumColor({ datum: d.pieDatum.data, colorType: fullParams.labelColorType, fullChartParams }))
355
+ .attr("stroke-width", 1)
356
+ .attr("fill", "none")
357
+ .attr("points", (d) => {
358
+ return [[d.lineStartX, d.lineStartY], [d.lineStartX, d.lineStartY]] as any // 畫出從弧線中心到延伸點的線
359
+ })
360
+ lines
361
+ .transition()
362
+ .attr("points", (d) => {
363
+ // const pos = arc.centroid(d) // 起點:弧線的中心點
364
+ // const outerPos = [pos[0] * 2.5, pos[1] * 2.5] // 外部延伸的點(乘以倍率來延長線段)
365
+
366
+ let lineEndX = d.x + d.collisionShiftX
367
+ let lineEndY = d.y + d.collisionShiftY
368
+ // if (d.lineStartX >= Math.abs(d.lineStartY)) {
369
+ // lineEndX -= d.textWidth / 2
370
+ // } else if (d.lineStartX <= - Math.abs(d.lineStartY)) {
371
+ // lineEndX += d.textWidth / 2
372
+ // }
373
+
374
+ return [[lineEndX, lineEndY], [d.lineStartX, d.lineStartY]] as any // 畫出從弧線中心到延伸點的線
375
+ })
376
+
377
+ return lines
378
+ }
379
+
380
+ function highlight ({ textSelection, lineSelection, ids, fullChartParams }: {
381
+ textSelection: d3.Selection<SVGTextElement, RenderDatum, any, any>
382
+ lineSelection: d3.Selection<SVGPolylineElement, RenderDatum, any, any>
383
+ ids: string[]
384
+ fullChartParams: ChartParams
385
+ }) {
386
+ textSelection.interrupt('highlight')
387
+ lineSelection.interrupt('highlight')
388
+
389
+ if (!ids.length) {
390
+ textSelection
391
+ .transition('highlight')
392
+ .duration(200)
393
+ .attr('transform', (d) => {
394
+ return `translate(${d.x + d.collisionShiftX},${d.y + d.collisionShiftY})`
395
+ })
396
+ .style('opacity', 1)
397
+ lineSelection
398
+ .transition('highlight')
399
+ .duration(200)
400
+ .style('opacity', 1)
401
+ return
402
+ }
403
+
404
+ textSelection.each((d, i, n) => {
405
+ const segment = d3.select<SVGTextElement, RenderDatum>(n[i])
406
+
407
+ if (ids.includes(d.pieDatum.id)) {
408
+ segment
409
+ .style('opacity', 1)
410
+ .transition('highlight')
411
+ .duration(200)
412
+ .attr('transform', (d) => {
413
+ // 如果已經有偏移過,則使用偏移後的位置(如果再改變的話很容易造成文字重疊)
414
+ if (d.collisionShiftX || d.collisionShiftY) {
415
+ return `translate(${d.x + d.collisionShiftX},${d.y + d.collisionShiftY})`
416
+ }
417
+ return `translate(${d.mouseoverX + d.collisionShiftX},${d.mouseoverY + d.collisionShiftY})`
418
+ })
419
+ } else {
420
+ segment
421
+ .style('opacity', fullChartParams.styles.unhighlightedOpacity)
422
+ .transition('highlight')
423
+ .duration(200)
424
+ .attr('transform', (d) => {
425
+ return `translate(${d.x + d.collisionShiftX},${d.y + d.collisionShiftY})`
426
+ })
427
+ }
428
+ })
429
+ lineSelection.each((d, i, n) => {
430
+ const segment = d3.select<SVGPolylineElement, RenderDatum>(n[i])
431
+
432
+ if (ids.includes(d.pieDatum.data.id)) {
433
+ segment
434
+ .style('opacity', 1)
435
+ .transition('highlight')
436
+ .duration(200)
437
+ } else {
438
+ segment
439
+ .style('opacity', fullChartParams.styles.unhighlightedOpacity)
440
+ .transition('highlight')
441
+ .duration(200)
442
+ }
443
+ })
444
+ }
445
+
446
+
447
+ function createEachPieLabel (pluginName: string, context: {
448
+ containerSelection: d3.Selection<SVGGElement, any, any, unknown>
449
+ // computedData$: Observable<ComputedDatumSeries[][]>
450
+ containerVisibleComputedSortedData$: Observable<ComputedDatumSeries[]>
451
+ // SeriesDataMap$: Observable<Map<string, ComputedDatumSeries[]>>
452
+ fullParams$: Observable<PieLabelsParams>
453
+ fullChartParams$: Observable<ChartParams>
454
+ textSizePx$: Observable<number>
455
+ seriesHighlight$: Observable<ComputedDatumSeries[]>
456
+ seriesContainerPosition$: Observable<ContainerPosition>
457
+ event$: Subject<EventSeries>
458
+ }) {
459
+ const destroy$ = new Subject()
460
+
461
+ context.containerSelection.selectAll('g').remove()
462
+
463
+ const lineGSelection: d3.Selection<SVGGElement, any, any, unknown> = context.containerSelection.append('g')
464
+ lineGSelection.classed(lineGClassName, true)
465
+ const labelGSelection: d3.Selection<SVGGElement, any, any, unknown> = context.containerSelection.append('g')
466
+ labelGSelection.classed(labelGClassName, true)
467
+
468
+ // const graphicSelection: d3.Selection<SVGGElement, any, any, any> = selection.append('g')
469
+ const textSelection$: Subject<d3.Selection<SVGTextElement, RenderDatum, any, any>> = new Subject()
470
+ const lineSelection$: Subject<d3.Selection<SVGPolylineElement, RenderDatum, any, any>> = new Subject()
471
+ let renderData: RenderDatum[] = []
472
+
473
+ const shorterSideWith$ = context.seriesContainerPosition$.pipe(
474
+ takeUntil(destroy$),
475
+ map(d => d.width < d.height ? d.width : d.height),
476
+ distinctUntilChanged()
477
+ )
478
+
479
+ const lineStartCentroid$ = context.fullParams$.pipe(
480
+ takeUntil(destroy$),
481
+ map(d => {
482
+ return d.labelCentroid >= pieOuterCentroid
483
+ ? pieOuterCentroid // 當 label在 pie的外側時,線條從 pie的邊緣開始
484
+ : d.labelCentroid // 當 label在 pie的內側時,線條從 label未偏移前的位置開始
485
+
486
+ })
487
+ )
488
+
489
+ combineLatest({
490
+ shorterSideWith: shorterSideWith$,
491
+ containerVisibleComputedSortedData: context.containerVisibleComputedSortedData$,
492
+ fullParams: context.fullParams$,
493
+ fullChartParams: context.fullChartParams$,
494
+ textSizePx: context.textSizePx$,
495
+ lineStartCentroid: lineStartCentroid$
496
+ }).pipe(
497
+ takeUntil(destroy$),
498
+ switchMap(async (d) => d),
499
+ ).subscribe(data => {
500
+
501
+ // 弧產生器 (d3.arc())
502
+ const arc = makeD3Arc({
503
+ axisWidth: data.shorterSideWith,
504
+ innerRadius: 0,
505
+ outerRadius: data.fullParams.outerRadius,
506
+ padAngle: 0,
507
+ cornerRadius: 0
508
+ })
509
+
510
+ const arcMouseover = makeD3Arc({
511
+ axisWidth: data.shorterSideWith,
512
+ innerRadius: 0,
513
+ outerRadius: data.fullParams.outerRadiusWhileHighlight, // 外半徑變化
514
+ padAngle: 0,
515
+ cornerRadius: 0
516
+ })
517
+
518
+ const pieData = makePieData({
519
+ data: data.containerVisibleComputedSortedData,
520
+ startAngle: data.fullParams.startAngle,
521
+ endAngle: data.fullParams.endAngle
522
+ })
523
+
524
+ renderData = makeRenderData({
525
+ pieData,
526
+ arc,
527
+ arcMouseover,
528
+ labelCentroid: data.fullParams.labelCentroid,
529
+ lineStartCentroid: data.lineStartCentroid,
530
+ fullParams: data.fullParams
531
+ })
532
+
533
+ // 先移除線條,等偏移後再重新繪製
534
+ lineGSelection.selectAll('polyline').remove()
535
+
536
+ const textSelection = renderLabel({
537
+ labelGSelection,
538
+ data: renderData,
539
+ fullParams: data.fullParams,
540
+ fullChartParams: data.fullChartParams,
541
+ textSizePx: data.textSizePx
542
+ })
543
+
544
+ // 等 label 本身的 transition 結束後再進行碰撞檢測
545
+ setTimeout(() => {
546
+ // resolveCollisions(labelSelection, renderData)
547
+ // 偏移 label
548
+ resolveCollisions(textSelection, renderData, data.textSizePx)
549
+
550
+ const lineSelection = renderLine({ lineGSelection, data: renderData, fullParams: data.fullParams, fullChartParams: data.fullChartParams })
551
+
552
+ lineSelection$.next(lineSelection)
553
+
554
+ }, 1000)
555
+
556
+ textSelection$.next(textSelection)
557
+
558
+ })
559
+
560
+ combineLatest({
561
+ textSelection: textSelection$,
562
+ lineSelection: lineSelection$,
563
+ highlight: context.seriesHighlight$.pipe(
564
+ map(data => data.map(d => d.id))
565
+ ),
566
+ fullChartParams: context.fullChartParams$,
567
+ }).pipe(
568
+ takeUntil(destroy$),
569
+ switchMap(async d => d)
570
+ ).subscribe(data => {
571
+ highlight({
572
+ textSelection: data.textSelection,
573
+ lineSelection: data.lineSelection,
574
+ ids: data.highlight,
575
+ fullChartParams: data.fullChartParams,
576
+ })
577
+ })
578
+
579
+ return () => {
580
+ destroy$.next(undefined)
581
+ }
582
+ }
583
+
584
+
585
+ export const PieLabels = defineSeriesPlugin(pluginConfig)(({ selection, observer, subject }) => {
586
+
587
+ const destroy$ = new Subject()
588
+
589
+ const { seriesCenterSelection$ } = seriesCenterSelectionObservable({
590
+ selection: selection,
591
+ pluginName,
592
+ visibleComputedSortedData$: observer.visibleComputedSortedData$,
593
+ seriesContainerPosition$: observer.seriesContainerPosition$
594
+ })
595
+
596
+ const unsubscribeFnArr: (() => void)[] = []
597
+
598
+ seriesCenterSelection$
599
+ .pipe(
600
+ takeUntil(destroy$)
601
+ )
602
+ .subscribe(seriesCenterSelection => {
603
+ // 每次重新計算時,清除之前的訂閱
604
+ unsubscribeFnArr.forEach(fn => fn())
605
+
606
+ seriesCenterSelection.each((d, containerIndex, g) => {
607
+
608
+ const containerSelection = d3.select(g[containerIndex])
609
+
610
+ const containerVisibleComputedSortedData$ = observer.visibleComputedSortedData$.pipe(
611
+ takeUntil(destroy$),
612
+ map(data => data[containerIndex] ?? data[0])
613
+ )
614
+
615
+ const containerPosition$ = observer.seriesContainerPosition$.pipe(
616
+ takeUntil(destroy$),
617
+ map(data => data[containerIndex] ?? data[0])
618
+ )
619
+
620
+ unsubscribeFnArr[containerIndex] = createEachPieLabel(pluginName, {
621
+ containerSelection: containerSelection,
622
+ // computedData$: observer.computedData$,
623
+ containerVisibleComputedSortedData$: containerVisibleComputedSortedData$,
624
+ // SeriesDataMap$: observer.SeriesDataMap$,
625
+ fullParams$: observer.fullParams$,
626
+ fullChartParams$: observer.fullChartParams$,
627
+ textSizePx$: observer.textSizePx$,
628
+ seriesHighlight$: observer.seriesHighlight$,
629
+ seriesContainerPosition$: containerPosition$,
630
+ event$: subject.event$,
631
+ })
632
+
633
+ })
634
+ })
635
+
636
+ return () => {
637
+ destroy$.next(undefined)
638
+ }
639
+ })