-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
73 lines (61 loc) · 1.63 KB
/
index.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
import { html2json } from 'html2json'
import deasync from 'deasync'
import flatten from 'flatten'
import SvgOptimiser from 'svgo'
import toCamelCase from 'to-camel-case'
import toPascalCase from 'to-pascal-case'
const getGroupType = layers => {
if (has('MSShapePathLayer', layers)) {
return 'Svg'
} else if (has('MSRectangleShape', layers)) {
return false
}
}
const getAttrs = (attr, legacy) => (
Object.keys(attr).filter(a => a !== 'xmlns').map(prop => {
let value = attr[prop]
if (Array.isArray(value)) {
value = value.join(' ')
}
return `${toCamelCase(prop)}${legacy ? ':' : ''} ${value}`
})
)
const getBlock = (raw, legacy) => {
const name = toPascalCase(raw)
return legacy ? `- block: ${name}` : name
}
const IGNORE = [
'title',
'desc',
]
const indent = lines => (
lines.map(l => Array.isArray(l) ? indent(l) : ` ${l}`)
)
const parseSvg = ({ attr, child, tag }, legacy) => {
const s = []
if (!tag || IGNORE.includes(tag.toLowerCase())) return false
s.push(getBlock(tag, legacy))
if (attr) {
const attrs = getAttrs(attr, legacy)
s.push(legacy ? indent(attrs) : attrs)
}
if (child) {
if (legacy) s.push(' blocks:')
s.push(child.map(c => {
const parsed = parseSvg(c, legacy)
return parsed && [legacy ? indent(parsed) : parsed, '']
}))
}
return s
}
const svgo = new SvgOptimiser()
export default (raw, legacy=false) => {
let text
let done = false
svgo.optimize(raw, res => {
text = res.data
done = true
})
deasync.loopWhile(() => !done)
return flatten(parseSvg(html2json(text).child[0], legacy)).filter(l => l !== false).join('\n')
}