This repository was archived by the owner on Sep 16, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
61 lines (54 loc) · 1.78 KB
/
index.ts
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
import {ElementNode, parse} from 'svg-parser';
import {generateSwiftUIShape} from './stubs';
import {SwiftUIGeneratorConfig, TranspilerOptions} from './types';
import {handleElement} from './elementHandlers';
import {extractSVGProperties, getSVGElement} from './utils';
import {DEFAULT_CONFIG} from './constants';
/**
* This function converts SVG string into SwiftUI
* Shape structure which is returned as a string.
* @param rawSVGString SVG code as a raw string.
* @param config Optional configuration object.
*/
export function convert(
rawSVGString: string,
config?: SwiftUIGeneratorConfig
): string {
const AST = parse(rawSVGString);
const svgElement = getSVGElement(AST);
if (svgElement) {
return swiftUIGenerator(svgElement, config);
} else {
throw new Error(
'Could not find SVG element, please provide full SVG source!'
);
}
}
/**
* Generates SwiftUI Shape string from SVG HAST (Abstract Syntax Tree).
* @param svgElement Parsed SVG Abstract Syntax Tree.
* @param config Optional configuration object.
*/
function swiftUIGenerator(
svgElement: ElementNode,
config?: SwiftUIGeneratorConfig
): string {
const svgProperties = extractSVGProperties(svgElement);
// The initial options passed to the first element.
const rootTranspilerOptions: TranspilerOptions = {
...svgProperties,
precision: config?.precision || 10,
lastPathId: 0,
indentationSize: config?.indentationSize || 4,
currentIndentationLevel: 0,
parentStyle: {},
};
// Generate SwiftUI Shape body.
const generatedBody = handleElement(svgElement, rootTranspilerOptions);
// Inject generated body into the Shape struct template.
const fullSwiftUIShape = generateSwiftUIShape(generatedBody, {
...DEFAULT_CONFIG,
...config,
});
return fullSwiftUIShape;
}