/
createGenerateClassName.js
81 lines (69 loc) · 2.44 KB
/
createGenerateClassName.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
import { unstable_nested as nested } from '@mui/private-theming/ThemeProvider';
/**
* This is the list of the style rule name we use as drop in replacement for the built-in
* pseudo classes (:checked, :disabled, :focused, etc.).
*
* Why do they exist in the first place?
* These classes are used at a specificity of 2.
* It allows them to override previously defined styles as well as
* being untouched by simple user overrides.
*/
const stateClasses = [
'checked',
'disabled',
'error',
'focused',
'focusVisible',
'required',
'expanded',
'selected',
];
// Returns a function which generates unique class names based on counters.
// When new generator function is created, rule counter is reset.
// We need to reset the rule counter for SSR for each request.
//
// It's inspired by
// https://github.com/cssinjs/jss/blob/4e6a05dd3f7b6572fdd3ab216861d9e446c20331/src/utils/createGenerateClassName.js
export default function createGenerateClassName(options = {}) {
const { disableGlobal = false, productionPrefix = 'jss', seed = '' } = options;
const seedPrefix = seed === '' ? '' : `${seed}-`;
let ruleCounter = 0;
const getNextCounterId = () => {
ruleCounter += 1;
if (process.env.NODE_ENV !== 'production') {
if (ruleCounter >= 1e10) {
console.warn(
[
'MUI: You might have a memory leak.',
'The ruleCounter is not supposed to grow that much.',
].join(''),
);
}
}
return ruleCounter;
};
return (rule, styleSheet) => {
const name = styleSheet.options.name;
// Is a global static MUI style?
if (name && name.indexOf('Mui') === 0 && !styleSheet.options.link && !disableGlobal) {
// We can use a shorthand class name, we never use the keys to style the components.
if (stateClasses.indexOf(rule.key) !== -1) {
return `Mui-${rule.key}`;
}
const prefix = `${seedPrefix}${name}-${rule.key}`;
if (!styleSheet.options.theme[nested] || seed !== '') {
return prefix;
}
return `${prefix}-${getNextCounterId()}`;
}
if (process.env.NODE_ENV === 'production') {
return `${seedPrefix}${productionPrefix}${getNextCounterId()}`;
}
const suffix = `${rule.key}-${getNextCounterId()}`;
// Help with debuggability.
if (styleSheet.options.classNamePrefix) {
return `${seedPrefix}${styleSheet.options.classNamePrefix}-${suffix}`;
}
return `${seedPrefix}${suffix}`;
};
}