-
Notifications
You must be signed in to change notification settings - Fork 6
/
spriteBackgroundImages.js
569 lines (531 loc) · 19.5 KB
/
spriteBackgroundImages.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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
const queryString = require('querystring');
const { promisify } = require('util');
const packers = require('./packers');
const { Canvas, Image } = require('canvas');
// Helper for extracting all nodes defining a specific property from a postcss rule
function getProperties(container, propertyName) {
return container.nodes.filter((node) => node.prop === propertyName);
}
async function getCanvasImageFromImageAsset(imageAsset) {
const canvasImage = new Image();
await new Promise((resolve, reject) => {
canvasImage.onerror = (err) =>
reject(
new Error(
`Error loading ${imageAsset.urlOrDescription}: ${err.message}`,
),
);
canvasImage.onload = resolve;
canvasImage.src = imageAsset.rawSrc;
});
return canvasImage;
}
async function getImageAssetFromCanvas(canvas, assetType, assetGraph) {
if (assetType === 'Png') {
let rawSrc;
try {
rawSrc = await promisify((cb) => canvas.toBuffer(cb))();
} catch (err) {
if (
err.message.includes(
'the surface type is not appropriate for the operation',
)
) {
err.message += ' (are you trying to add an SVG to a sprite?)';
}
throw err;
}
return {
type: 'Png',
rawSrc,
};
} else {
const rawSrc = await promisify((cb) => {
const jpegChunks = [];
canvas
.createJPEGStream()
.on('data', (chunk) => {
jpegChunks.push(chunk);
})
.on('end', () => cb(null, Buffer.concat(jpegChunks)))
.on('error', cb);
})();
return {
type: 'Jpeg',
rawSrc,
};
}
}
function parsePadding(paddingStr, asset) {
let padding;
if (paddingStr) {
// Strip units ('px' assumed)
const tokens = [];
paddingStr.split(/[,+]|\s+/).forEach((token) => {
const num = parseInt(token.replace(/[a-z]+$/, ''), 10);
if (!isNaN(num)) {
tokens.push(num);
}
});
if (tokens.length === 4) {
padding = tokens;
} else if (tokens.length === 3) {
padding = [tokens[0], tokens[1], tokens[2], tokens[1]]; // T, L+R, B
} else if (tokens.length === 2) {
padding = [tokens[0], tokens[1], tokens[0], tokens[1]]; // T+B, L+R
} else if (tokens.length === 1) {
padding = [tokens[0], tokens[0], tokens[0], tokens[0]];
}
} else {
padding = [0, 0, 0, 0];
}
return padding;
}
function maxPaddingDimensions(...paddings) {
// [2, 4, 6, 8], [1, 5, 3, 10], ... => [2, 5, 6, 10]
const result = [0, 0, 0, 0];
for (const padding of paddings) {
if (padding) {
for (let i = 0; i < 4; i += 1) {
result[i] = Math.max(result[i], padding[i]);
}
}
}
return result;
}
function clampPaddingToDpr(padding, devicePixelRatio) {
return padding.map((size) => Math.max(size, devicePixelRatio - 1));
}
function getRelationSpriteInfoFromIncomingRelation(incomingRelation) {
const parsedQueryString = queryString.parse(
incomingRelation.href.match(/\?([^#]*)/)[1],
);
return {
groupName: parsedQueryString.sprite || 'default',
noGroup: 'spriteNoGroup' in parsedQueryString,
padding: parsePadding(parsedQueryString.padding),
asset: incomingRelation.to,
};
}
function extractInfoFromCssRule(cssRule, propertyNamePrefix) {
const info = {};
cssRule.walkDecls((decl) => {
if (!propertyNamePrefix || decl.prop.startsWith(propertyNamePrefix)) {
const keyName = decl.prop
.substr(propertyNamePrefix.length)
.replace(/-([a-z])/g, ($0, $1) => $1.toUpperCase());
info[keyName] = decl.value.replace(/^(['"])(.*)\1$/, '$2');
}
});
return info;
}
module.exports = () =>
async function spriteBackgroundImages(assetGraph) {
const spriteGroups = {};
// Find sprite annotated images and create a data structure with their information
for (const relation of assetGraph.findRelations({
type: 'CssImage',
to: { isImage: true },
href: /\?(?:|[^#]*&)sprite(?:[=&#]|$)/,
})) {
const relationSpriteInfo =
getRelationSpriteInfoFromIncomingRelation(relation);
const spriteGroup = (spriteGroups[relationSpriteInfo.groupName] =
spriteGroups[relationSpriteInfo.groupName] || {
imageInfosById: {},
});
const imageInfo = spriteGroup.imageInfosById[relationSpriteInfo.asset.id];
if (!imageInfo) {
relationSpriteInfo.incomingRelations = [relation];
spriteGroup.imageInfosById[relationSpriteInfo.asset.id] =
relationSpriteInfo;
} else {
imageInfo.incomingRelations.push(relation);
imageInfo.padding = maxPaddingDimensions(
relationSpriteInfo.padding,
imageInfo.padding,
);
}
}
const redefinitionErrors = {};
// Extract sprite grouping information va -sprite- prefixed properties in stylesheets
for (const cssAsset of assetGraph.findAssets({
type: 'Css',
isLoaded: true,
})) {
cssAsset.eachRuleInParseTree((cssRule) => {
if (cssRule.type !== 'rule') {
return;
}
if (getProperties(cssRule, '-sprite-selector-for-group').length > 0) {
const spriteInfo = extractInfoFromCssRule(cssRule, '-sprite-');
const spriteGroupName = spriteInfo.selectorForGroup;
if (spriteInfo.location) {
const matchLocation = spriteInfo.location.match(
/^url\((['"]|)(.*?)\1\)$/,
);
if (matchLocation) {
spriteInfo.location = matchLocation[2];
}
}
const group = spriteGroups[spriteGroupName];
if (group) {
if (!Array.isArray(group.placeHolders)) {
group.placeHolders = [];
}
if (group.placeHolders.length > 0) {
let err;
if (
Object.keys(group.placeHolders[0]).every((key) => {
if (['asset', 'cssRule'].includes(key)) {
return true;
}
return group.placeHolders[0][key] === spriteInfo[key];
})
) {
// Queue up these errors as they tend to come in quite big bunches
if (!Array.isArray(redefinitionErrors[spriteGroupName])) {
redefinitionErrors[spriteGroupName] = [];
}
redefinitionErrors[spriteGroupName].push(cssAsset);
group.placeHolders.push({
...spriteInfo,
asset: cssAsset,
cssRule,
});
} else {
err = new Error(
`assetgraph-sprite: Multiple differing definitions of ${spriteGroupName} sprite.\nThis is most likely an error.`,
);
err.asset = cssAsset;
assetGraph.warn(err);
}
} else {
group.placeHolders.push({
...spriteInfo,
asset: cssAsset,
cssRule,
});
}
}
}
});
}
for (const spriteGroupName of Object.keys(redefinitionErrors)) {
const message = [
`assetgraph-sprite: Multiple identical definitions of ${spriteGroupName} sprite.`,
'This might happen if you duplicate CSS using a preprocessor.',
...redefinitionErrors[spriteGroupName].map(
(asset) => ` ${asset.urlOrDescription}`,
),
].join('\n');
const err = new Error(message);
assetGraph.info(err);
}
for (const spriteGroupName of Object.keys(spriteGroups)) {
const spriteGroup = spriteGroups[spriteGroupName];
let imageInfos = Object.values(spriteGroup.imageInfosById);
const spriteInfo =
(spriteGroup.placeHolders && spriteGroup.placeHolders[0]) || {};
const spritePadding = parsePadding(spriteInfo.padding);
const canvasImages = await Promise.all(
imageInfos.map((imageInfo) =>
getCanvasImageFromImageAsset(imageInfo.asset),
),
);
for (const [i, imageInfo] of imageInfos.entries()) {
const canvasImage = canvasImages[i];
Object.assign(imageInfo, {
canvasImage,
width: canvasImage.width,
height: canvasImage.height,
padding: clampPaddingToDpr(
maxPaddingDimensions(imageInfo.padding, spritePadding),
imageInfo.asset.devicePixelRatio,
),
});
}
const packerName =
{
'jim-scott': 'jimScott',
horizontal: 'horizontal',
vertical: 'vertical',
}[spriteInfo.packer] || 'tryAll';
const packingData = packers[packerName].pack(imageInfos);
const canvas = new Canvas(packingData.width, packingData.height);
const ctx = canvas.getContext('2d');
if ('backgroundColor' in spriteInfo) {
ctx.fillStyle = spriteInfo.backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
imageInfos = packingData.imageInfos;
for (const imageInfo of imageInfos) {
ctx.drawImage(
imageInfo.canvasImage,
imageInfo.x,
imageInfo.y,
imageInfo.width,
imageInfo.height,
);
}
const spriteImageType = /^jpe?g$/.test(spriteInfo.imageFormat)
? 'Jpeg'
: 'Png';
const spriteAssetConfig = await getImageAssetFromCanvas(
canvas,
spriteImageType,
assetGraph,
);
const fileName = `sprite-${spriteGroupName}-${imageInfos.length}${assetGraph[spriteImageType].prototype.defaultExtension}`;
if (Array.isArray(spriteGroup.placeHolders)) {
const location = spriteGroup.placeHolders[0].location;
if (location) {
let href;
if (/^\?/.test(location)) {
href = fileName + location;
} else {
href = location;
}
spriteAssetConfig.url = assetGraph.resolveUrl(assetGraph.root, href);
}
}
if (!spriteAssetConfig.url) {
spriteAssetConfig.fileName = fileName;
}
const spriteAsset = assetGraph.addAsset(spriteAssetConfig);
if (Array.isArray(spriteGroup.placeHolders)) {
for (const spriteInfo of spriteGroup.placeHolders) {
const cssRule = spriteInfo.cssRule;
let propertyName;
let propertyNode;
let tokenNumber;
for (const candidatePropertyName of [
'background-image',
'background',
]) {
const decls = getProperties(cssRule, candidatePropertyName);
if (!propertyName && decls.length > 0) {
propertyName = candidatePropertyName;
let propertyValue = decls[0].value;
if (propertyValue === '!important') {
// Hack so that an existing value of "!important" will DTRT
decls[0].important = true;
propertyValue = 'url(...)';
} else if (/^\s*$/.test(propertyValue)) {
propertyValue = 'url(...)';
} else {
const existingUrlTokens = propertyValue.match(
assetGraph.CssImage.prototype.tokenRegExp,
);
if (existingUrlTokens) {
tokenNumber = existingUrlTokens.length;
}
propertyValue += ' url(...)';
}
decls[0].value = propertyValue;
}
}
if (propertyName) {
propertyNode = getProperties(cssRule, propertyName)[0];
} else {
cssRule.append('background-image: url(...)');
propertyNode = cssRule.last;
}
// I can't see why the ordering of CssImage relations should be significant...
const relation = spriteInfo.asset.addRelation(
{
type: 'CssImage',
node: cssRule,
to: spriteAsset,
propertyName,
propertyNode,
tokenNumber,
},
'last',
);
relation.refreshHref();
spriteInfo.cssRule.walkDecls((decl) => {
if (
[
'-sprite-selector-for-group',
'-sprite-packer',
'-sprite-location',
'-sprite-image-format',
'-sprite-background-color',
'-sprite-important',
'-sprite-padding',
].includes(decl.prop)
) {
decl.remove();
}
});
// If background-size is set, we should update it, The correct size is now the size of the sprite:
const backgroundSizeDecls = getProperties(
spriteInfo.cssRule,
'background-size',
);
if (backgroundSizeDecls.length > 0) {
backgroundSizeDecls[0].value = `${packingData.width}px ${packingData.height}px`;
}
}
}
for (const imageInfo of imageInfos) {
for (const incomingRelation of imageInfo.incomingRelations) {
incomingRelation.from.markDirty();
const relationSpriteInfo =
getRelationSpriteInfoFromIncomingRelation(incomingRelation);
const node = incomingRelation.node;
const existingBackgroundPositionDecls = getProperties(
node,
'background-position',
);
const existingBackgroundDecls = getProperties(node, 'background');
const offsets = [
Math.round(imageInfo.x / imageInfo.asset.devicePixelRatio), // FIXME: Rounding issues?
Math.round(imageInfo.y / imageInfo.asset.devicePixelRatio),
];
let backgroundOffsetsWereUpdated = false;
let existingOffsets;
if (existingBackgroundDecls.length > 0) {
// Warn if there's more than one?
const backgroundTokens =
existingBackgroundDecls[0].value.split(/\s+/);
const positionTokenIndices = [];
existingOffsets = [];
for (const [
i,
existingBackgroundValueToken,
] of backgroundTokens.entries()) {
if (/^(?:-?\d+px|0)$/i.test(existingBackgroundValueToken)) {
positionTokenIndices.push(i);
existingOffsets.push(
parseInt(existingBackgroundValueToken, 10),
);
}
}
if (existingOffsets.length === 2) {
// Patch up the existing background property by replacing the old offsets with corrected ones:
for (let [i, offset] of offsets.entries()) {
offset -= existingOffsets[i];
backgroundTokens.splice(
positionTokenIndices[i],
1,
offset ? `${-offset}px` : '0',
);
}
existingBackgroundDecls[0].value = backgroundTokens.join(' ');
backgroundOffsetsWereUpdated = true;
}
}
if (!backgroundOffsetsWereUpdated) {
// There was no 'background' property, or it didn't contain something that looked like offsets.
// Create or update the background-position property instead:
let backgroundPositionImportant = false;
if (existingBackgroundPositionDecls.length === 1) {
// FIXME: Silently ignores other units than px
backgroundPositionImportant =
existingBackgroundPositionDecls[0].value === '!important' ||
existingBackgroundPositionDecls[0].important;
if (existingBackgroundPositionDecls[0].value !== '!important') {
existingOffsets = existingBackgroundPositionDecls[0].value
.split(' ')
.map((item) => parseInt(item, 10));
if (
existingOffsets.length !== 2 ||
isNaN(existingOffsets[0]) ||
isNaN(existingOffsets[1])
) {
const err = new Error(
`WARNING: trying to sprite ${
imageInfo.asset.url
} with ${existingBackgroundPositionDecls[0].toString()}`,
);
assetGraph.warn(err);
} else {
offsets[0] -= existingOffsets[0];
offsets[1] -= existingOffsets[1];
}
}
}
const newBackgroundPositionValue = offsets
.map((item) => (item ? `${-item}px` : '0'))
.join(' ');
if (existingBackgroundPositionDecls.length > 0) {
existingBackgroundPositionDecls[0].value =
newBackgroundPositionValue;
existingBackgroundPositionDecls[0].important =
backgroundPositionImportant;
} else {
node.append(
`background-position: ${newBackgroundPositionValue}${
backgroundPositionImportant ? ' !important' : ''
}`,
);
}
}
node.walkDecls((decl) => {
if (
[
'-sprite-group',
'-sprite-padding',
'-sprite-no-group-selector',
'-sprite-important',
].includes(decl.prop)
) {
decl.remove();
}
});
// Background-sizes change when spriting, upadte appropriately
if (imageInfo.asset.devicePixelRatio === 1) {
// Device pixel ratio is default. Remove property and let the defaults rule
for (const backgroundSizeDecl of getProperties(
incomingRelation.node,
'background-size',
)) {
backgroundSizeDecl.remove();
}
} else {
// Device pixel ratio is non-default, Set it explicitly with the ratio applied
const dpr = incomingRelation.to.devicePixelRatio;
// TODO: Figure out if rounding might become a problem
const width = packingData.width / dpr;
const height = packingData.height / dpr;
const existingBackgroundSizeDecls = getProperties(
incomingRelation.node,
'background-size',
);
if (existingBackgroundSizeDecls.length > 0) {
existingBackgroundSizeDecls[0].value = `${width}px ${height}px`;
} else {
incomingRelation.node.append(
`background-size: ${width}px ${height}px`,
);
}
}
if (relationSpriteInfo.noGroup || !spriteGroup.placeHolders) {
// The user specified that this selector needs its own background-image/background
// property pointing at the sprite rather than relying on the Html elements also being
// matched by the sprite group's "main" selector, which would have been preferable.
const relation = incomingRelation.from.addRelation(
{
type: 'CssImage',
node: incomingRelation.node,
propertyNode: incomingRelation.propertyNode,
to: spriteAsset,
},
'before',
incomingRelation,
);
relation.refreshHref();
incomingRelation.remove();
} else {
incomingRelation.detach();
}
// Remove the original image if it has become an orphan:
if (!assetGraph.findRelations({ to: incomingRelation.to }).length) {
assetGraph.removeAsset(incomingRelation.to);
}
}
}
}
};