forked from software-mansion/react-native-svg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xml.js
471 lines (400 loc) · 9.64 KB
/
xml.js
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import React, { Component, useState, useEffect, useMemo } from 'react';
import Rect from './elements/Rect';
import Circle from './elements/Circle';
import Ellipse from './elements/Ellipse';
import Polygon from './elements/Polygon';
import Polyline from './elements/Polyline';
import Line from './elements/Line';
import Svg from './elements/Svg';
import Path from './elements/Path';
import G from './elements/G';
import Text from './elements/Text';
import TSpan from './elements/TSpan';
import TextPath from './elements/TextPath';
import Use from './elements/Use';
import Image from './elements/Image';
import Symbol from './elements/Symbol';
import Defs from './elements/Defs';
import LinearGradient from './elements/LinearGradient';
import RadialGradient from './elements/RadialGradient';
import Stop from './elements/Stop';
import ClipPath from './elements/ClipPath';
import Pattern from './elements/Pattern';
import Mask from './elements/Mask';
export const tags = {
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,
};
export function SvgAst({ ast, override }) {
const { props, children } = ast;
return (
<Svg {...props} {...override}>
{children}
</Svg>
);
}
export function SvgXml(props) {
const { xml, override } = props;
const ast = useMemo(() => xml && parse(xml), [xml]);
return (ast && <SvgAst ast={ast} override={override || props} />) || null;
}
async function fetchText(uri) {
const response = await fetch(uri);
return await response.text();
}
const err = console.error.bind(console);
export function SvgUri(props) {
const { uri } = props;
const [xml, setXml] = useState();
useEffect(() => {
fetchText(uri)
.then(setXml)
.catch(err);
}, [uri]);
return (xml && <SvgXml xml={xml} override={props} />) || null;
}
// Extending Component is required for Animated support.
export class SvgFromXml extends Component {
state = {};
componentDidMount() {
this.parse(this.props.xml);
}
componentDidUpdate(prevProps) {
const { xml } = this.props;
if (xml !== prevProps.xml) {
this.parse(xml);
}
}
parse(xml) {
try {
this.setState({ ast: parse(xml) });
} catch (e) {
console.error(e);
}
}
render() {
const {
props,
state: { ast },
} = this;
return ast ? <SvgAst ast={ast} override={props.override || props} /> : null;
}
}
export class SvgFromUri extends Component {
state = {};
componentDidMount() {
this.fetch(this.props.uri);
}
componentDidUpdate(prevProps) {
const { uri } = this.props;
if (uri !== prevProps.uri) {
this.fetch(uri);
}
}
async fetch(uri) {
try {
this.setState({ xml: await fetchText(uri) });
} catch (e) {
console.error(e);
}
}
render() {
const {
props,
state: { xml },
} = this;
return xml ? <SvgFromXml xml={xml} override={props} /> : null;
}
}
const upperCase = (match, letter) => letter.toUpperCase();
const camelCase = phrase => phrase.replace(/[:\-]([a-z])/g, upperCase);
export function getStyle(string) {
const style = {};
const declarations = string.split(';');
const { length } = declarations;
for (let i = 0; i < length; i++) {
const declaration = declarations[i];
if (declaration.length !== 0) {
const split = declaration.split(':');
const property = split[0];
const value = split[1];
style[camelCase(property.trim())] = value.trim();
}
}
return style;
}
export function astToReact(child, i) {
if (typeof child === 'object') {
const { Tag, props, children } = child;
return (
<Tag key={i} {...props}>
{children.map(astToReact)}
</Tag>
);
}
return child;
}
// slimmed down parser based on https://github.com/Rich-Harris/svg-parser
function repeat(str, i) {
let result = '';
while (i--) {
result += str;
}
return result;
}
const toSpaces = tabs => repeat(' ', tabs.length);
function locate(source, i) {
const lines = source.split('\n');
const nLines = lines.length;
let column = i;
for (let line = 0; line < nLines; line++) {
const { length } = lines[line];
if (column >= length) {
column -= length;
} else {
const before = source.slice(0, i).replace(/^\t+/, toSpaces);
const beforeLine = /(^|\n).*$/.exec(before)[0];
const after = source.slice(i);
const afterLine = /.*(\n|$)/.exec(after)[0];
const pad = repeat(' ', beforeLine.length);
const snippet = `${beforeLine}${afterLine}\n${pad}^`;
return { line, column, snippet };
}
}
}
const validNameCharacters = /[a-zA-Z0-9:_-]/;
const whitespace = /[\s\t\r\n]/;
const quotemarks = /['"]/;
export function parse(source) {
const length = source.length;
let currentElement = null;
let state = metadata;
let children = null;
let root = null;
let stack = [];
function error(message) {
const { line, column, snippet } = locate(source, i);
throw new Error(
`${message} (${line}:${column}). If this is valid SVG, it's probably a bug. Please raise an issue\n\n${snippet}`,
);
}
function metadata() {
while (
i + 1 < length &&
(source[i] !== '<' || !validNameCharacters.test(source[i + 1]))
) {
i++;
}
return neutral();
}
function neutral() {
let text = '';
let char;
while (i < length && (char = source[i]) !== '<') {
text += char;
i += 1;
}
if (/\S/.test(text)) {
children.push(text);
}
if (source[i] === '<') {
return openingTag;
}
return neutral;
}
function openingTag() {
const char = source[i];
if (char === '?') {
return neutral;
} // <?xml...
if (char === '!') {
const start = i + 1;
if (source.slice(start, i + 3) === '--') {
return comment;
}
const end = i + 8;
if (source.slice(start, end) === '[CDATA[') {
return cdata;
}
if (/doctype/i.test(source.slice(start, end))) {
return neutral;
}
}
if (char === '/') {
return closingTag;
}
const tag = getName();
const props = {};
const element = {
tag,
props,
children: [],
Tag: tags[tag],
};
if (currentElement) {
children.push(element);
} else {
root = element;
}
getAttributes(props);
const { style } = props;
if (style) {
props.style = getStyle(style);
}
let selfClosing = false;
if (source[i] === '/') {
i += 1;
selfClosing = true;
}
if (source[i] !== '>') {
error('Expected >');
}
if (!selfClosing) {
currentElement = element;
({ children } = element);
stack.push(element);
}
return neutral;
}
function comment() {
const index = source.indexOf('-->', i);
if (!~index) {
error('expected -->');
}
i = index + 2;
return neutral;
}
function cdata() {
const index = source.indexOf(']]>', i);
if (!~index) {
error('expected ]]>');
}
i = index + 2;
return neutral;
}
function closingTag() {
const tag = getName();
if (!tag) {
error('Expected tag name');
}
if (tag !== currentElement.tag) {
error(
`Expected closing tag </${tag}> to match opening tag <${currentElement.tag}>`,
);
}
if (source[i] !== '>') {
error('Expected >');
}
stack.pop();
currentElement = stack[stack.length - 1];
if (currentElement) {
({ children } = currentElement);
}
return neutral;
}
function getName() {
let name = '';
let char;
while (i < length && validNameCharacters.test((char = source[i]))) {
name += char;
i += 1;
}
return name;
}
function getAttributes(props) {
while (i < length) {
if (!whitespace.test(source[i])) {
return;
}
allowSpaces();
const name = getName();
if (!name) {
return;
}
let value = true;
allowSpaces();
if (source[i] === '=') {
i += 1;
allowSpaces();
value = getAttributeValue();
if (!isNaN(value) && value.trim() !== '') {
value = +value;
}
}
props[camelCase(name)] = value;
}
}
function getAttributeValue() {
return quotemarks.test(source[i])
? getQuotedAttributeValue()
: getUnquotedAttributeValue();
}
function getUnquotedAttributeValue() {
let value = '';
do {
const char = source[i];
if (char === ' ' || char === '>' || char === '/') {
return value;
}
value += char;
i += 1;
} while (i < length);
return value;
}
function getQuotedAttributeValue() {
const quotemark = source[i++];
let value = '';
let escaped = false;
while (i < length) {
const char = source[i++];
if (char === quotemark && !escaped) {
return value;
}
if (char === '\\' && !escaped) {
escaped = true;
}
value += escaped ? `\\${char}` : char;
escaped = false;
}
}
function allowSpaces() {
while (i < length && whitespace.test(source[i])) {
i += 1;
}
}
let i = 0;
while (i < length) {
if (!state) {
error('Unexpected character');
}
state = state();
i += 1;
}
if (state !== neutral) {
error('Unexpected end of input');
}
if (root) {
root.children = root.children.map(astToReact);
}
return root;
}