@orbcharts/plugins-basic 3.0.0-beta.2 → 3.0.0-beta.20

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