-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathsvgChart.tsx
294 lines (273 loc) · 7.13 KB
/
svgChart.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import Svg, {
Circle,
Ellipse,
G,
Text,
TSpan,
TextPath,
Path,
Polygon,
Polyline,
Line,
Rect,
Use,
Image,
Symbol,
Defs,
LinearGradient,
RadialGradient,
Stop,
ClipPath,
Pattern,
Mask,
} from 'react-native-svg';
import React, {
ForwardedRef,
useState,
useImperativeHandle,
forwardRef,
memo,
useMemo,
useRef,
useCallback,
} from 'react';
import { Platform, View, Image as RNImage } from 'react-native';
import {
setPlatformAPI,
// DEFAULT_FONT_FAMILY as zrenderFontFamily,
} from 'zrender/lib/core/platform';
import { measureText } from '../utils/platform';
// import { DEFAULT_FONT_FAMILY } from './utils/font';
import { GestureHandler } from '../components/GestureHandler';
import { dispatchEventsToZRender } from '../components/events';
import type {
ChartElement,
DispatchEvents,
SVGChartProps,
SVGVNode,
} from '../types';
export { SVGRenderer } from './SVGRenderer';
export * from '../types';
setPlatformAPI({ measureText });
const tagMap = {
svg: Svg,
circle: Circle,
ellipse: Ellipse,
g: G,
text: Text,
tspan: TSpan,
textPath: TextPath,
path: Path,
polygon: Polygon,
polyline: Polyline,
line: Line,
rect: Rect,
use: Use,
image: Image,
symbol: Symbol,
defs: Defs,
linearGradient: LinearGradient,
radialGradient: RadialGradient,
stop: Stop,
clipPath: ClipPath,
pattern: Pattern,
mask: Mask,
};
const imageSizeMap: any = {};
interface ImageSize {
width: number;
height: number;
}
// 使用 async/await 获取图片尺寸
const getImageSize = async (uri: string): Promise<ImageSize> => {
return new Promise((resolve, reject) => {
RNImage.getSize(
uri,
(width, height) => resolve({ width, height }),
(error) => reject(error)
);
});
};
async function imageInit(url: string) {
const { width, height } = await getImageSize(url);
imageSizeMap[url] = {
width,
height,
};
}
function toCamelCase(str: string) {
var reg = /-(\w)/g;
return str.replace(reg, function (_: any, $1: string) {
return $1.toUpperCase();
});
}
interface SVGVEleProps {
node: SVGVNode;
touchStart?: any;
touchMove?: any;
touchEnd?: any;
}
const fontStyleReg = /([\w-]+):([\w-]+)/;
function SvgEle(props: SVGVEleProps) {
const { node } = props;
if (!node) return null;
const { tag, text, children } = node;
// const Tag = tagMap[tag as keyof typeof tagMap];
// @ts-ignore
const Tag = tagMap[tag];
if (!Tag) return null;
const attrs: any = Object.entries(node.attrs).reduce(
(carry, [key, value]) => {
carry[toCamelCase(key)] = value;
return carry;
},
{} as Record<string, any>
);
if (tag === 'text') {
if (attrs.style) {
// TODO: 全局替换字体做法比较暴力,或者实用定义字体,可能某些场景字体设置失效,需要修复
// attrs.style = attrs.style.replace(new RegExp(zrenderFontFamily, 'g'), DEFAULT_FONT_FAMILY);
const matches = attrs.style.split(';');
matches
.filter((match: string) => fontStyleReg.test(match))
.forEach((match: string) => {
const parts = match.split(':');
const key = parts[0]?.trim();
let value = parts[1]?.trim();
if (key) {
// echart里默认字体sans-serif,ios无法识别
if (
Platform.OS === 'ios' &&
key === 'font-family' &&
value === 'sans-serif'
) {
value = 'Helvetica Neue';
}
attrs[toCamelCase(key)] = value;
}
});
}
if (!attrs.alignmentBaseline && attrs.dominantBaseline) {
attrs.alignmentBaseline = 'middle';
}
// fix: https://github.com/react-native-svg/react-native-svg/issues/1862
if (attrs.paintOrder === 'stroke') {
attrs.strokeWidth = 0;
}
// fixed svg fillOpacity bug in some render processes
if (attrs.fillOpacity === undefined) {
attrs.fillOpacity = 1;
}
return <Text {...attrs}>{text}</Text>;
}
// fix: https://github.com/react-native-svg/react-native-svg/issues/983
if (attrs.clipPath && !attrs.clipRule && Platform.OS === 'android') {
attrs.clipRule = 'nonzero';
}
if (tag === 'path') {
// 全部数据为空,iOS渲染有问题,无效的path过滤掉
if (!attrs.d) return null;
return <Path {...attrs} />;
}
if (tag === 'linearGradient' || tag === 'radialGradient') {
// note: 强制刷新渐变
// https://github.com/software-mansion/react-native-svg/issues/1762
return (
<Tag {...attrs}>
{children?.map((child) =>
SvgEle({
node: child,
})
)}
</Tag>
);
}
if (tag === 'image' && !attrs.width) {
if (imageSizeMap[attrs.href]) {
const { width, height } = imageSizeMap[attrs.href];
attrs.width = (attrs.height / height) * width;
if (attrs.height === 0) {
attrs.opacity = 0;
}
} else {
imageInit(attrs.href);
}
}
return (
<Tag key={node.key} {...attrs}>
{children?.map((child) => <SvgEle key={child.key} node={child} />)}
</Tag>
);
}
function SvgRoot(props: SVGVEleProps) {
const { node } = props;
const { attrs, children } = node;
const { width, height, viewBox } = attrs;
return (
<Svg
width={width as string}
height={height as string}
viewBox={viewBox as string}
>
{children?.map((child) => <SvgEle key={child.key} node={child} />)}
</Svg>
);
}
function SvgComponent(
props: SVGChartProps,
ref: ForwardedRef<(ChartElement & any) | null>
) {
const { node, style, handleGesture = true, ...gestureProps } = props;
const [svgNode, setSvgNode] = useState<SVGVNode | undefined>(node);
const width = useMemo(
() => Number((svgNode?.attrs?.width || style?.width) ?? 0),
[svgNode?.attrs?.width, style?.width]
);
const height = useMemo(
() => Number((svgNode?.attrs?.height || style?.height) ?? 0),
[svgNode?.attrs?.height, style?.height]
);
const zrenderId = useRef<number>();
const dispatchEvents = useCallback<DispatchEvents>(
(types, nativeEvent, eventArgs) => {
if (zrenderId.current === undefined) return;
dispatchEventsToZRender(zrenderId.current, types, nativeEvent, eventArgs);
},
[]
);
useImperativeHandle(
ref,
() => ({
elm: {
setAttribute: (_name: string, _value: any) => {},
setAttributeNS: (_name: string, _value: any) => {},
removeAttribute: (_name: string) => {},
patch: (_oldVnode: SVGVNode, vnode: SVGVNode) => {
setSvgNode(vnode);
},
setZrenderId: (id: number) => {
zrenderId.current = id;
},
},
dispatchEvents,
getChartSize: () => {
return {
width,
height,
};
},
}),
[dispatchEvents, width, height]
);
return svgNode ? (
<View testID="component" style={{ ...style, width, height }}>
<SvgRoot node={svgNode} />
{handleGesture ? (
<GestureHandler dispatchEvents={dispatchEvents} {...gestureProps} />
) : null}
</View>
) : null;
}
const SvgChart = memo(forwardRef(SvgComponent));
SvgChart.displayName = 'SvgChart';
export default SvgChart;