-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathindex.ts
More file actions
206 lines (174 loc) · 4.98 KB
/
index.ts
File metadata and controls
206 lines (174 loc) · 4.98 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
import hash from '@emotion/hash';
import canUseDom from '@rc-component/util/lib/Dom/canUseDom';
import { removeCSS, updateCSS } from '@rc-component/util/lib/Dom/dynamicCSS';
import type { HashPriority } from '../StyleContext';
import { ATTR_MARK, ATTR_TOKEN } from '../StyleContext';
import { Theme } from '../theme';
// Create a cache for memo concat
type NestWeakMap<T> = WeakMap<object, NestWeakMap<T> | T>;
const resultCache: NestWeakMap<object> = new WeakMap();
const RESULT_VALUE = {};
export function memoResult<T extends object, R>(
callback: () => R,
deps: T[],
): R {
let current: WeakMap<any, any> = resultCache;
for (let i = 0; i < deps.length; i += 1) {
const dep = deps[i];
if (!current.has(dep)) {
current.set(dep, new WeakMap());
}
current = current.get(dep)!;
}
if (!current.has(RESULT_VALUE)) {
current.set(RESULT_VALUE, callback());
}
return current.get(RESULT_VALUE);
}
// Create a cache here to avoid always loop generate
const flattenTokenCache = new WeakMap<any, string>();
/**
* Flatten token to string, this will auto cache the result when token not change
*/
export function flattenToken(token: any) {
let str = flattenTokenCache.get(token) || '';
if (!str) {
Object.keys(token).forEach((key) => {
const value = token[key];
str += key;
if (value instanceof Theme) {
str += value.id;
} else if (value && typeof value === 'object') {
str += flattenToken(value);
} else {
str += value;
}
});
// https://github.com/ant-design/ant-design/issues/48386
// Should hash the string to avoid style tag name too long
str = hash(str);
// Put in cache
flattenTokenCache.set(token, str);
}
return str;
}
/**
* Convert derivative token to key string
*/
export function token2key(token: any, salt: string): string {
return hash(`${salt}_${flattenToken(token)}`);
}
const randomSelectorKey = `random-${Date.now()}-${Math.random()}`.replace(
/\./g,
'',
);
// Magic `content` for detect selector support
const checkContent = '_bAmBoO_';
function supportSelector(
styleStr: string,
handleElement: (ele: HTMLElement) => void,
supportCheck?: (ele: HTMLElement) => boolean,
): boolean {
if (canUseDom()) {
updateCSS(styleStr, randomSelectorKey);
const ele = document.createElement('div');
ele.style.position = 'fixed';
ele.style.left = '0';
ele.style.top = '0';
handleElement?.(ele);
document.body.appendChild(ele);
if (process.env.NODE_ENV !== 'production') {
ele.innerHTML = 'Test';
ele.style.zIndex = '9999999';
}
const support = supportCheck
? supportCheck(ele)
: getComputedStyle(ele).content?.includes(checkContent);
ele.parentNode?.removeChild(ele);
removeCSS(randomSelectorKey);
return support;
}
return false;
}
let canLayer: boolean | undefined = undefined;
export function supportLayer(): boolean {
if (canLayer === undefined) {
canLayer = supportSelector(
`@layer ${randomSelectorKey} { .${randomSelectorKey} { content: "${checkContent}"!important; } }`,
(ele) => {
ele.className = randomSelectorKey;
},
);
}
return canLayer!;
}
let canWhere: boolean | undefined = undefined;
export function supportWhere(): boolean {
if (canWhere === undefined) {
canWhere = supportSelector(
`:where(.${randomSelectorKey}) { content: "${checkContent}"!important; }`,
(ele) => {
ele.className = randomSelectorKey;
},
);
}
return canWhere!;
}
let canLogic: boolean | undefined = undefined;
export function supportLogicProps(): boolean {
if (canLogic === undefined) {
canLogic = supportSelector(
`.${randomSelectorKey} { inset-block: 93px !important; }`,
(ele) => {
ele.className = randomSelectorKey;
},
(ele) => getComputedStyle(ele).bottom === '93px',
);
}
return canLogic!;
}
export const isClientSide = canUseDom();
export function unit(num: string | number) {
if (typeof num === 'number') {
return `${num}px`;
}
return num;
}
export function toStyleStr(
style: string,
tokenKey?: string,
styleId?: string,
customizeAttrs: Record<string, string> = {},
plain = false,
) {
if (plain) {
return style;
}
const attrs: Record<string, string | undefined> = {
...customizeAttrs,
[ATTR_TOKEN]: tokenKey,
[ATTR_MARK]: styleId,
};
const attrStr = Object.keys(attrs)
.map((attr) => {
const val = attrs[attr];
return val ? `${attr}="${val}"` : null;
})
.filter((v) => v)
.join(' ');
return `<style ${attrStr}>${style}</style>`;
}
export function where(options?: {
hashPriority?: HashPriority;
hashCls?: string;
}) {
const { hashCls, hashPriority = 'low' } = options || {};
if (!hashCls) {
return '';
}
const hashSelector = `.${hashCls}`;
return hashPriority === 'low' ? `:where(${hashSelector})` : hashSelector;
}
export const isNonNullable = <T>(val: T): val is NonNullable<T> => {
return val !== undefined && val !== null;
};