-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
190 lines (146 loc) · 4.51 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
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
/**
This regex represents a loose rule of an “image candidate string”.
@see https://html.spec.whatwg.org/multipage/images.html#srcset-attribute
An “image candidate string” roughly consists of the following:
1. Zero or more whitespace characters.
2. A non-empty URL that does not start or end with `,`.
3. Zero or more whitespace characters.
4. An optional “descriptor” that starts with a whitespace character.
5. Zero or more whitespace characters.
6. Each image candidate string is separated by a `,`.
We intentionally implement a loose rule here so that we can perform more aggressive error handling and reporting in the below code.
*/
const imageCandidateRegex = /\s*([^,]\S*[^,](?:\s+[^,]+)?)\s*(?:,|$)/;
const duplicateDescriptorCheck = (allDescriptors, value, postfix) => {
allDescriptors[postfix] = allDescriptors[postfix] || {};
if (allDescriptors[postfix][value]) {
throw new Error(`No more than one image candidate is allowed for a given descriptor: ${value}${postfix}`);
}
allDescriptors[postfix][value] = true;
};
const fallbackDescriptorDuplicateCheck = allDescriptors => {
if (allDescriptors.fallback) {
throw new Error('Only one fallback image candidate is allowed');
}
// TODO: Use `?`.
if (allDescriptors.x && allDescriptors.x['1']) {
throw new Error('A fallback image is equivalent to a 1x descriptor, providing both is invalid.');
}
allDescriptors.fallback = true;
};
const descriptorCountCheck = (allDescriptors, currentDescriptors) => {
if (currentDescriptors.length === 0) {
fallbackDescriptorDuplicateCheck(allDescriptors);
} else if (currentDescriptors.length > 1) {
throw new Error(`Image candidate may have no more than one descriptor, found ${currentDescriptors.length}: ${currentDescriptors.join(' ')}`);
}
};
const validDescriptorCheck = (value, postfix, descriptor) => {
if (Number.isNaN(value)) {
throw new TypeError(`${descriptor || value} is not a valid number`);
}
switch (postfix) {
case 'w': {
if (value <= 0) {
throw new Error('Width descriptor must be greater than zero');
} else if (!Number.isInteger(value)) {
throw new TypeError('Width descriptor must be an integer');
}
break;
}
case 'x': {
if (value <= 0) {
throw new Error('Pixel density descriptor must be greater than zero');
}
break;
}
case 'h': {
throw new Error('Height descriptor is no longer allowed');
}
default: {
throw new Error(`Invalid srcset descriptor: ${descriptor}`);
}
}
};
export function parseSrcset(string, {strict = false} = {}) {
const allDescriptors = strict ? {} : undefined;
return string
.replace(/\r?\n/, '')
.replace(/,\s+/, ', ')
.split(imageCandidateRegex)
.filter((part, index) => index % 2 === 1)
.map(part => {
const [url, ...descriptors] = part.trim().split(/\s+/);
const result = {url};
if (strict) {
descriptorCountCheck(allDescriptors, descriptors);
}
for (const descriptor of descriptors) {
const postfix = descriptor[descriptor.length - 1];
const value = Number.parseFloat(descriptor.slice(0, -1));
if (strict) {
validDescriptorCheck(value, postfix, descriptor);
duplicateDescriptorCheck(allDescriptors, value, postfix);
}
switch (postfix) {
case 'w': {
result.width = value;
break;
}
case 'h': {
result.height = value;
break;
}
case 'x': {
result.density = value;
break;
}
// No default
}
}
return result;
});
}
const knownDescriptors = new Set(['width', 'height', 'density']);
export function stringifySrcset(array, {strict = false} = {}) {
const allDescriptors = strict ? {} : undefined;
return array.map(element => {
if (!element.url) {
if (strict) {
throw new Error('URL is required');
}
return '';
}
const descriptorKeys = Object.keys(element).filter(key => knownDescriptors.has(key));
if (strict) {
descriptorCountCheck(allDescriptors, descriptorKeys);
}
const result = [element.url];
for (const descriptorKey of descriptorKeys) {
const value = element[descriptorKey];
let postfix;
switch (descriptorKey) {
case 'width': {
postfix = 'w';
break;
}
case 'height': {
postfix = 'h';
break;
}
case 'density': {
postfix = 'x';
break;
}
// No default
}
const descriptor = `${value}${postfix}`;
if (strict) {
validDescriptorCheck(value, postfix);
duplicateDescriptorCheck(allDescriptors, value, postfix);
}
result.push(descriptor);
}
return result.join(' ');
}).join(', ');
}