-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
109 lines (89 loc) · 2.64 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
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
const through = require('through2')
const css = require('css')
class AvifCSS {
constructor() {
this.avaibleExtensions = ['png', 'jpg', 'jpeg', 'JPG', 'JPEG']
}
init = (extensions) => {
return through.obj((buffer, _, callback) => {
if (buffer.isNull()) {
return callback(null, buffer)
} else if (buffer.isStream()) {
return callback(null, buffer)
}
if (extensions) {
this.avaibleExtensions = extensions
}
this.buffer = buffer
this.fileData = buffer.contents.toString()
this.transform()
callback(null, this.buffer)
})
}
transform(rules = this.parseCSS()) {
rules.forEach((expression) => {
if (expression.type === 'media') {
return this.transform(expression.rules)
} else if (expression.type === 'rule') {
expression.declarations
.forEach((rule) => {
if (!this.isBackground(rule)) return
const imageExtension = this.getExtension(rule)
if (!imageExtension) return
this.createExpressions({
rule,
selectors: expression.selectors,
position: expression.type === 'media'
? rule.position
: expression.position,
imageExtension
})
})
}
})
this.buffer.contents = new Buffer.from(this.fileData)
}
parseCSS() {
return css.parse(this.fileData).stylesheet.rules
}
isBackground({ property, value }) {
if (
property === 'background' ||
property === 'background-image' &&
value.indexOf('.webp') < 0 &&
value.indexOf('.avif') < 0
) {
return true
}
}
getExtension({ value }) {
return this.avaibleExtensions.find((extension) => {
if (value.indexOf(extension) > 0) {
return extension
}
})
}
createExpressions({ rule, selectors, position, imageExtension }) {
const splitedData = this.fileData.split(/\n/)
const rowIndex = position.end.line - 1
const columnIndex = position.end.column - 1
;['avif', 'webp'].forEach((modernExtension) => {
splitedData.splice(rowIndex, 1, this.changeString(
splitedData[rowIndex],
columnIndex,
`
.${modernExtension} ${selectors.join('')} {
${rule.property}: ${rule.value.replaceAll(imageExtension, modernExtension)}
}
`.replaceAll('\n', '')
)
)
})
this.fileData = splitedData.join('\n')
}
changeString(string, changeIndex, changeText) {
return string.substring(0, changeIndex) + changeText + string.substring(changeIndex)
}
}
const avifcss = new AvifCSS()
module.exports = avifcss.init