/
trace-svg.js
187 lines (166 loc) · 4.47 KB
/
trace-svg.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
const { promisify } = require(`bluebird`)
const fs = require(`fs-extra`)
const _ = require(`lodash`)
const tmpDir = require(`os`).tmpdir()
const path = require(`path`)
const sharp = require(`./safe-sharp`)
const filenamify = require(`filenamify`)
const duotone = require(`./duotone`)
const { getPluginOptions, healOptions } = require(`./plugin-options`)
const { reportError } = require(`./report-error`)
const {
createContentDigest,
} = require(`gatsby-core-utils/create-content-digest`)
exports.notMemoizedPrepareTraceSVGInputFile = async ({
file,
options,
tmpFilePath,
reporter,
}) => {
let pipeline
try {
pipeline = sharp()
if (!options.rotate) {
pipeline.rotate()
}
fs.createReadStream(file.absolutePath).pipe(pipeline)
} catch (err) {
reportError(`Failed to process image ${file.absolutePath}`, err, reporter)
return
}
pipeline
.resize(options.width, options.height, {
position: options.cropFocus,
})
.png({
compressionLevel: options.pngCompressionLevel,
adaptiveFiltering: false,
force: options.toFormat === `png`,
})
.jpeg({
quality: options.quality,
progressive: options.jpegProgressive,
force: options.toFormat === `jpg`,
})
// grayscale
if (options.grayscale) {
pipeline = pipeline.grayscale()
}
// rotate
if (options.rotate && options.rotate !== 0) {
pipeline = pipeline.rotate(options.rotate)
}
// duotone
if (options.duotone) {
pipeline = await duotone(options.duotone, options.toFormat, pipeline)
}
await new Promise((resolve, reject) =>
pipeline.toFile(tmpFilePath, err => {
if (err) {
return reject(err)
}
return resolve()
})
)
}
const optimize = svg => {
const { optimize } = require(`svgo`)
const { data } = optimize(svg, {
multipass: true,
floatPrecision: 0,
plugins: [
{
name: `preset-default`,
params: {
overrides: {
// disable removeViewBox plugin
removeViewBox: false,
},
},
},
{
name: `addAttributesToSVGElement`,
params: {
attributes: [
{
preserveAspectRatio: `none`,
},
],
},
},
],
})
return data
}
exports.notMemoizedtraceSVG = async ({ file, args, fileArgs, reporter }) => {
const options = healOptions(
getPluginOptions(),
{
// use maxWidth/maxHeight as width/height if available
// if width/height is used in fileArgs, the maxWidth/maxHeight
// values will be overritten
...(fileArgs && fileArgs.maxWidth && fileArgs.maxHeight
? {
height: fileArgs.maxHeight,
width: fileArgs.maxWidth,
}
: {}),
...fileArgs,
},
file.extension
)
const optionsHash = createContentDigest(options)
const tmpFilePath = path.join(
tmpDir,
filenamify(`${file.internal.contentDigest}-${file.name}-${optionsHash}`) +
`.${file.extension}`
)
await exports.memoizedPrepareTraceSVGInputFile({
tmpFilePath,
file,
options,
reporter,
})
const svgToMiniDataURI = require(`mini-svg-data-uri`)
const potrace = require(`@gatsbyjs/potrace`)
const trace = promisify(potrace.trace)
const defaultArgs = {
color: `lightgray`,
optTolerance: 0.4,
turdSize: 100,
turnPolicy: potrace.Potrace.TURNPOLICY_MAJORITY,
}
const optionsSVG = _.defaults({}, args, defaultArgs)
// `srcset` attribute rejects URIs with literal spaces
const encodeSpaces = str => str.replace(/ /gi, `%20`)
return trace(tmpFilePath, optionsSVG)
.then(optimize)
.then(svgToMiniDataURI)
.then(encodeSpaces)
}
let memoizedPrepareTraceSVGInputFile
let memoizedTraceSVG
const createMemoizedFunctions = () => {
exports.memoizedPrepareTraceSVGInputFile = memoizedPrepareTraceSVGInputFile =
_.memoize(
exports.notMemoizedPrepareTraceSVGInputFile,
({ tmpFilePath }) => tmpFilePath
)
exports.memoizedTraceSVG = memoizedTraceSVG = _.memoize(
exports.notMemoizedtraceSVG,
({ file, args, fileArgs }) =>
`${file.internal.contentDigest}${JSON.stringify(args)}${JSON.stringify(
fileArgs
)}`
)
}
// This is very hacky, but memoized function are pretty tricky to spy on
// in tests ;(
createMemoizedFunctions()
exports.createMemoizedFunctions = () => {
createMemoizedFunctions()
}
exports.clearMemoizeCaches = () => {
memoizedTraceSVG.cache.clear()
memoizedPrepareTraceSVGInputFile.cache.clear()
}