index.js
8.37 KB
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
'use strict';
const postcss = require('postcss');
const selectorParser = require('postcss-selector-parser');
const hasOwnProperty = Object.prototype.hasOwnProperty;
function getSingleLocalNamesForComposes(root) {
return root.nodes.map(node => {
if (node.type !== 'selector' || node.nodes.length !== 1) {
throw new Error(
`composition is only allowed when selector is single :local class name not in "${root}"`
);
}
node = node.nodes[0];
if (
node.type !== 'pseudo' ||
node.value !== ':local' ||
node.nodes.length !== 1
) {
throw new Error(
'composition is only allowed when selector is single :local class name not in "' +
root +
'", "' +
node +
'" is weird'
);
}
node = node.first;
if (node.type !== 'selector' || node.length !== 1) {
throw new Error(
'composition is only allowed when selector is single :local class name not in "' +
root +
'", "' +
node +
'" is weird'
);
}
node = node.first;
if (node.type !== 'class') {
// 'id' is not possible, because you can't compose ids
throw new Error(
'composition is only allowed when selector is single :local class name not in "' +
root +
'", "' +
node +
'" is weird'
);
}
return node.value;
});
}
const whitespace = '[\\x20\\t\\r\\n\\f]';
const unescapeRegExp = new RegExp(
'\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)',
'ig'
);
function unescape(str) {
return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
const high = '0x' + escaped - 0x10000;
// NaN means non-codepoint
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace
? escaped
: high < 0
? // BMP codepoint
String.fromCharCode(high + 0x10000)
: // Supplemental Plane codepoint (surrogate pair)
String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
});
}
const processor = postcss.plugin('postcss-modules-scope', function(options) {
return css => {
const generateScopedName =
(options && options.generateScopedName) || processor.generateScopedName;
const generateExportEntry =
(options && options.generateExportEntry) || processor.generateExportEntry;
const exportGlobals = options && options.exportGlobals;
const exports = Object.create(null);
function exportScopedName(name, rawName) {
const scopedName = generateScopedName(
rawName ? rawName : name,
css.source.input.from,
css.source.input.css
);
const exportEntry = generateExportEntry(
rawName ? rawName : name,
scopedName,
css.source.input.from,
css.source.input.css
);
const { key, value } = exportEntry;
exports[key] = exports[key] || [];
if (exports[key].indexOf(value) < 0) {
exports[key].push(value);
}
return scopedName;
}
function localizeNode(node) {
switch (node.type) {
case 'selector':
node.nodes = node.map(localizeNode);
return node;
case 'class':
return selectorParser.className({
value: exportScopedName(
node.value,
node.raws && node.raws.value ? node.raws.value : null
),
});
case 'id': {
return selectorParser.id({
value: exportScopedName(
node.value,
node.raws && node.raws.value ? node.raws.value : null
),
});
}
}
throw new Error(
`${node.type} ("${node}") is not allowed in a :local block`
);
}
function traverseNode(node) {
switch (node.type) {
case 'pseudo':
if (node.value === ':local') {
if (node.nodes.length !== 1) {
throw new Error('Unexpected comma (",") in :local block');
}
const selector = localizeNode(node.first, node.spaces);
// move the spaces that were around the psuedo selector to the first
// non-container node
selector.first.spaces = node.spaces;
const nextNode = node.next();
if (
nextNode &&
nextNode.type === 'combinator' &&
nextNode.value === ' ' &&
/\\[A-F0-9]{1,6}$/.test(selector.last.value)
) {
selector.last.spaces.after = ' ';
}
node.replaceWith(selector);
return;
}
/* falls through */
case 'root':
case 'selector': {
node.each(traverseNode);
break;
}
case 'id':
case 'class':
if (exportGlobals) {
exports[node.value] = [node.value];
}
break;
}
return node;
}
// Find any :import and remember imported names
const importedNames = {};
css.walkRules(rule => {
if (/^:import\(.+\)$/.test(rule.selector)) {
rule.walkDecls(decl => {
importedNames[decl.prop] = true;
});
}
});
// Find any :local classes
css.walkRules(rule => {
if (
rule.nodes &&
rule.selector.slice(0, 2) === '--' &&
rule.selector.slice(-1) === ':'
) {
// ignore custom property set
return;
}
let parsedSelector = selectorParser().astSync(rule);
rule.selector = traverseNode(parsedSelector.clone()).toString();
rule.walkDecls(/composes|compose-with/, decl => {
const localNames = getSingleLocalNamesForComposes(parsedSelector);
const classes = decl.value.split(/\s+/);
classes.forEach(className => {
const global = /^global\(([^\)]+)\)$/.exec(className);
if (global) {
localNames.forEach(exportedName => {
exports[exportedName].push(global[1]);
});
} else if (hasOwnProperty.call(importedNames, className)) {
localNames.forEach(exportedName => {
exports[exportedName].push(className);
});
} else if (hasOwnProperty.call(exports, className)) {
localNames.forEach(exportedName => {
exports[className].forEach(item => {
exports[exportedName].push(item);
});
});
} else {
throw decl.error(
`referenced class name "${className}" in ${decl.prop} not found`
);
}
});
decl.remove();
});
rule.walkDecls(decl => {
let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
tokens = tokens.map((token, idx) => {
if (idx === 0 || tokens[idx - 1] === ',') {
const localMatch = /^(\s*):local\s*\((.+?)\)/.exec(token);
if (localMatch) {
return (
localMatch[1] +
exportScopedName(localMatch[2]) +
token.substr(localMatch[0].length)
);
} else {
return token;
}
} else {
return token;
}
});
decl.value = tokens.join('');
});
});
// Find any :local keyframes
css.walkAtRules(atrule => {
if (/keyframes$/i.test(atrule.name)) {
const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atrule.params);
if (localMatch) {
atrule.params = exportScopedName(localMatch[1]);
}
}
});
// If we found any :locals, insert an :export rule
const exportedNames = Object.keys(exports);
if (exportedNames.length > 0) {
const exportRule = postcss.rule({ selector: ':export' });
exportedNames.forEach(exportedName =>
exportRule.append({
prop: exportedName,
value: exports[exportedName].join(' '),
raws: { before: '\n ' },
})
);
css.append(exportRule);
}
};
});
processor.generateScopedName = function(name, path) {
const sanitisedPath = path
.replace(/\.[^\.\/\\]+$/, '')
.replace(/[\W_]+/g, '_')
.replace(/^_|_$/g, '');
return `_${sanitisedPath}__${name}`.trim();
};
processor.generateExportEntry = function(name, scopedName) {
return {
key: unescape(name),
value: unescape(scopedName),
};
};
module.exports = processor;