-
Notifications
You must be signed in to change notification settings - Fork 37
/
VirtualSvgConverter.ts
81 lines (75 loc) · 1.74 KB
/
VirtualSvgConverter.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*!
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project.
*/
import {
SGMark,
ScenegraphConverter,
ChartOptions,
VSvgNode,
DEFAULT_HEIGHT,
DEFAULT_WIDTH,
} from '@chart-parts/interfaces'
import { renderMark } from './element_renderers'
import { translate } from './element_renderers/interfaces'
const DEFAULT_BG_COLOR = 'transparent'
const DEFAULT_ORIGIN: [number, number] = [0, 0]
/**
* The VirtualSvgRender renders Scenegraph data into a serializable Virtual DOM.
*
* The Virtual Dom acts as an intermediate form that can be rendered out into many forms.
*/
export class VirtualSvgConverter implements ScenegraphConverter<VSvgNode> {
public render(mark: SGMark<any>, options: ChartOptions): VSvgNode {
const {
width = DEFAULT_WIDTH,
height = DEFAULT_HEIGHT,
backgroundColor = DEFAULT_BG_COLOR,
origin = DEFAULT_ORIGIN,
ariaTitle,
ariaDescription,
} = options
const [x = 0, y = 0] = origin
// Create the rendering Context
let id = 0
const context = {
nextId: () => `${++id}`,
}
// Get the rendering of the root mark
const root = renderMark(mark, context)
const children: VSvgNode[] = [
{
type: 'defs',
children: root.defs,
},
{
type: 'g',
transforms: [translate(x, y)],
children: root.nodes,
},
]
// Wrap the rendered root in an SVG
const svg: VSvgNode = {
type: 'svg',
attrs: {
width: width + x,
height: height + y,
/**
* This allows screen-readers to pass over the svg
* https://css-tricks.com/accessible-svgs/
*/
role: 'img',
},
ariaTitle,
ariaDescription,
metadata: {
id: 'root',
},
style: {
backgroundColor,
},
children,
}
return svg
}
}