-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdiv.js
More file actions
249 lines (212 loc) · 7.59 KB
/
div.js
File metadata and controls
249 lines (212 loc) · 7.59 KB
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
// TODO[refactor] split into smaller functions
import $ from '../utils/dom-render-svg'
import { parse as parseGradient } from 'gradient-parser'
import { uid } from 'uid'
import ImageRenderer from './image'
const kebabToCamel = s => s.replace(/-./g, x => x[1].toUpperCase())
function isTransparent (color) {
if (!color || color === 'none' || color === 'transparent') return true
if (color.startsWith('rgba')) {
const rgba = color.match(/[\d.]+/g)
if (rgba[3] === '0') return true
}
return false
}
function parseBorders (s) {
let borders = null
for (const dir of ['top', 'right', 'bottom', 'left']) {
const color = s.getPropertyValue(`border-${dir}-color`)
const width = parseInt(s.getPropertyValue(`border-${dir}-width`))
const style = s.getPropertyValue(`border-${dir}-style`)
// Skip invisible
if (isTransparent(color)) continue
if (!width || isNaN(width)) continue
if (style === 'none' || style === 'hidden') continue
borders ??= {}
borders[dir] = { color, width, style }
}
return borders
}
async function getImageSize (url) {
return new Promise(resolve => {
const image = new Image()
image.onload = () => resolve({ width: image.width, height: image.height })
image.src = url
})
}
export default ({
debug,
fonts
}) => async (element, { x, y, width, height, style, defs }) => {
if (!width || !height) return
const backgroundColor = style.getPropertyValue('background-color')
const backgroundImage = style.getPropertyValue('background-image') ?? 'none'
const boxShadow = style.getPropertyValue('box-shadow') ?? 'none'
const borderRadius = parseInt(style.getPropertyValue('border-radius')) ?? null
const borders = parseBorders(style)
// Skip visually empty blocks
if (isTransparent(backgroundColor) && isTransparent(backgroundImage) && !borders) return
// Render initial rect
const g = $('g')
const rect = $('rect', {
x,
y,
width,
height,
fill: backgroundColor,
rx: borderRadius
}, g)
// Render background-image
if (!isTransparent(backgroundImage)) {
const url = (backgroundImage.match(/url\("?(.*?)"?\)/) ?? [])[1]
// Render background-image
if (url) {
const backgroundSize = style.getPropertyValue('background-size')
const renderImage = ImageRenderer({ debug, fonts })
// TODO handle background-size
// TODO handle background-repeat
const size = await getImageSize(url)
const image = await renderImage({ src: url }, {
x,
y,
width: Math.max(width, size.width),
height: Math.max(height, size.height)
})
const clipPath = $('clipPath', { id: 'clip_' + uid() }, defs, [$('rect', { x, y, width, height })])
image.setAttribute('clip-path', `url(#${clipPath.id})`)
g.appendChild(image)
} else {
// TODO handle multiple gradients
const {
colorStops,
orientation,
type
} = parseGradient(backgroundImage)?.[0] ?? {}
// TODO handle repeating gradients type, SEE https://github.com/rafaelcaricio/gradient-parser?tab=readme-ov-file#ast
const gradient = $(kebabToCamel(type), {
id: 'gradient_' + uid(),
gradientUnits: 'objectBoundingBox', // Allow specifying rotation center in %
gradientTransform: orientation
? (() => {
switch (orientation.type) {
case 'angular': return `rotate(${270 + parseFloat(orientation.value)}, 0.5, 0.5)`
case 'directional': {
switch (orientation.value) {
case 'top': return 'rotate(270, 0.5, 0.5)'
case 'right': return null
case 'bottom': return 'rotate(90, 0.5, 0.5)'
case 'left': return 'rotate(180, 0.5, 0.5)'
}
}
}
})()
: 'rotate(90, 0.5, 0.5)'
}, defs)
// Add color stops
for (let index = 0; index < colorStops.length; index++) {
const colorStop = colorStops[index]
const stop = $('stop', {
offset: colorStop.length
// TODO handle colorStop.length.type other than '%'
? +colorStop.length.value / 100
: index / (colorStops.length - 1),
'stop-color': `${colorStop.type}(${colorStop.value})`
})
gradient.appendChild(stop)
}
rect.setAttribute('fill', `url(#${gradient.id})`)
}
}
// Render box shadow
if (boxShadow !== 'none') {
const filter = $('filter', { id: 'filter_' + uid() }, defs)
// This assumes browser consistency of the CSSStyleDeclaration.getPropertyValue returned string
const REGEX_SHADOW_DECLARATION = /rgba?\(([\d.]{1,3}(,\s)?){3,4}\)\s(-?(\d+)px\s?){4}/g
const REGEX_SHADOW_DECLARATION_PARSER = /(rgba?\((?:[\d.]{1,3}(?:,\s)?){3,4}\))\s(-?[\d.]+)px\s(-?[\d.]+)px\s(-?[\d.]+)px\s(-?[\d.]+)px/
for (const shadowString of boxShadow.match(REGEX_SHADOW_DECLARATION) ?? []) {
let [
,
color,
offx,
offy,
blur,
spread
] = shadowString.match(REGEX_SHADOW_DECLARATION_PARSER)
offx = parseInt(offx)
offy = parseInt(offy)
spread = parseInt(spread)
filter.appendChild($('feGaussianBlur', { stdDeviation: blur / 2 }))
const shadow = $('rect', {
x: x + offx - spread,
y: y + offy - spread,
width: width + spread * 2,
height: height + spread * 2,
fill: color,
rx: borderRadius,
filter: `url(#${filter.id})`
})
g.prepend(shadow)
}
}
// Render border
if (!borderRadius) {
for (const [dir, border] of Object.entries(borders ?? {})) {
const geom = {}
switch (dir) {
case 'top':
geom.x1 = x
geom.x2 = x + width
geom.y1 = geom.y2 = y + parseInt(border.width) / 2
break
case 'right':
geom.x1 = geom.x2 = x + width - parseInt(border.width) / 2
geom.y1 = y
geom.y2 = y + height
break
case 'bottom':
geom.x1 = x
geom.x2 = x + width
geom.y1 = geom.y2 = y + height - parseInt(border.width) / 2
break
case 'left':
geom.x1 = geom.x2 = x + parseInt(border.width) / 2
geom.y1 = y
geom.y2 = y + height
break
}
$('line', {
...geom,
stroke: border.color,
'stroke-width': border.width,
...(() => {
switch (border.style) {
case 'dotted': return {
'stroke-dasharray': [0, border.width * 2].join(' '),
'stroke-dashoffset': 1,
'stroke-linejoin': 'round',
'stroke-linecap': 'round'
}
case 'dashed': return {
// https://developer.mozilla.org/en-US/docs/Web/CSS/border-style#dashed
'stroke-dasharray': [border.width * 2, 4].join(' ')
}
default: return {}
}
})()
}, g)
}
} else if (borders?.top) {
// Handle border-radius by drawing the whole border as a standard stroke
// TODO handle border-radius for specific border-dir.
// For now, we use borders.top as a placeholder for all borders
rect.setAttribute('stroke', borders.top.color)
rect.setAttribute('stroke-width', borders.top.width)
// Draw border from center
rect.setAttribute('rx', borderRadius - borders.top.width / 2)
rect.setAttribute('x', x + borders.top.width / 2)
rect.setAttribute('y', y + borders.top.width / 2)
rect.setAttribute('width', width - borders.top.width)
rect.setAttribute('height', height - borders.top.width)
}
return g
}