forked from ant-design/cssinjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseStyleRegister.tsx
618 lines (539 loc) · 16.9 KB
/
useStyleRegister.tsx
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
import hash from '@emotion/hash';
import type * as CSS from 'csstype';
import { removeCSS, updateCSS } from 'rc-util/lib/Dom/dynamicCSS';
import * as React from 'react';
// @ts-ignore
import unitless from '@emotion/unitless';
import { compile, serialize, stringify } from 'stylis';
import type { Theme, Transformer } from '..';
import type Keyframes from '../Keyframes';
import type { Linter } from '../linters';
import { contentQuotesLinter, hashedAnimationLinter } from '../linters';
import type { HashPriority } from '../StyleContext';
import StyleContext, {
ATTR_CACHE_PATH,
ATTR_MARK,
ATTR_TOKEN,
CSS_IN_JS_INSTANCE,
} from '../StyleContext';
import { isClientSide, toStyleStr } from '../util';
import {
CSS_FILE_STYLE,
existPath,
getStyleAndHash,
} from '../util/cacheMapUtil';
import type { ExtractStyle } from './useGlobalCache';
import useGlobalCache from './useGlobalCache';
const SKIP_CHECK = '_skip_check_';
const MULTI_VALUE = '_multi_value_';
export interface LayerConfig {
name: string;
dependencies?: string[];
}
export type CSSProperties = Omit<
CSS.PropertiesFallback<number | string>,
'animationName'
> & {
animationName?:
| CSS.PropertiesFallback<number | string>['animationName']
| Keyframes;
};
export type CSSPropertiesWithMultiValues = {
[K in keyof CSSProperties]:
| CSSProperties[K]
| readonly Extract<CSSProperties[K], string>[]
| {
[SKIP_CHECK]?: boolean;
[MULTI_VALUE]?: boolean;
value: CSSProperties[K] | CSSProperties[K][];
};
};
export type CSSPseudos = { [K in CSS.Pseudos]?: CSSObject };
type ArrayCSSInterpolation = readonly CSSInterpolation[];
export type InterpolationPrimitive =
| null
| undefined
| boolean
| number
| string
| CSSObject;
export type CSSInterpolation =
| InterpolationPrimitive
| ArrayCSSInterpolation
| Keyframes;
export type CSSOthersObject = Record<string, CSSInterpolation>;
export interface CSSObject
extends CSSPropertiesWithMultiValues,
CSSPseudos,
CSSOthersObject {}
// ============================================================================
// == Parser ==
// ============================================================================
// Preprocessor style content to browser support one
export function normalizeStyle(styleStr: string) {
const serialized = serialize(compile(styleStr), stringify);
return serialized.replace(/\{%%%\:[^;];}/g, ';');
}
function isCompoundCSSProperty(value: CSSObject[string]) {
return (
typeof value === 'object' &&
value &&
(SKIP_CHECK in value || MULTI_VALUE in value)
);
}
// 注入 hash 值
function injectSelectorHash(
key: string,
hashId: string,
hashPriority?: HashPriority,
) {
if (!hashId) {
return key;
}
const hashClassName = `.${hashId}`;
const hashSelector =
hashPriority === 'low' ? `:where(${hashClassName})` : hashClassName;
// 注入 hashId
const keys = key.split(',').map((k) => {
const fullPath = k.trim().split(/\s+/);
// 如果 Selector 第一个是 HTML Element,那我们就插到它的后面。反之,就插到最前面。
let firstPath = fullPath[0] || '';
const htmlElement = firstPath.match(/^\w+/)?.[0] || '';
firstPath = `${htmlElement}${hashSelector}${firstPath.slice(
htmlElement.length,
)}`;
return [firstPath, ...fullPath.slice(1)].join(' ');
});
return keys.join(',');
}
export interface ParseConfig {
hashId?: string;
hashPriority?: HashPriority;
layer?: LayerConfig;
path?: string;
transformers?: Transformer[];
linters?: Linter[];
}
export interface ParseInfo {
root?: boolean;
injectHash?: boolean;
parentSelectors: string[];
}
// Parse CSSObject to style content
export const parseStyle = (
interpolation: CSSInterpolation,
config: ParseConfig = {},
{ root, injectHash, parentSelectors }: ParseInfo = {
root: true,
parentSelectors: [],
},
): [
parsedStr: string,
// Style content which should be unique on all of the style (e.g. Keyframes).
// Firefox will flick with same animation name when exist multiple same keyframes.
effectStyle: Record<string, string>,
] => {
const {
hashId,
layer,
path,
hashPriority,
transformers = [],
linters = [],
} = config;
let styleStr = '';
let effectStyle: Record<string, string> = {};
function parseKeyframes(keyframes: Keyframes) {
const animationName = keyframes.getName(hashId);
if (!effectStyle[animationName]) {
const [parsedStr] = parseStyle(keyframes.style, config, {
root: false,
parentSelectors,
});
effectStyle[animationName] = `@keyframes ${keyframes.getName(
hashId,
)}${parsedStr}`;
}
}
function flattenList(
list: ArrayCSSInterpolation,
fullList: CSSObject[] = [],
) {
list.forEach((item) => {
if (Array.isArray(item)) {
flattenList(item, fullList);
} else if (item) {
fullList.push(item as CSSObject);
}
});
return fullList;
}
const flattenStyleList = flattenList(
Array.isArray(interpolation) ? interpolation : [interpolation],
);
flattenStyleList.forEach((originStyle) => {
// Only root level can use raw string
const style: CSSObject =
typeof originStyle === 'string' && !root ? {} : originStyle;
if (typeof style === 'string') {
styleStr += `${style}\n`;
} else if ((style as any)._keyframe) {
// Keyframe
parseKeyframes(style as unknown as Keyframes);
} else {
const mergedStyle = transformers.reduce(
(prev, trans) => trans?.visit?.(prev) || prev,
style,
);
// Normal CSSObject
Object.keys(mergedStyle).forEach((key) => {
const value = mergedStyle[key];
if (
typeof value === 'object' &&
value &&
(key !== 'animationName' || !(value as Keyframes)._keyframe) &&
!isCompoundCSSProperty(value)
) {
let subInjectHash = false;
// 当成嵌套对象来处理
let mergedKey = key.trim();
// Whether treat child as root. In most case it is false.
let nextRoot = false;
// 拆分多个选择器
if ((root || injectHash) && hashId) {
if (mergedKey.startsWith('@')) {
// 略过媒体查询,交给子节点继续插入 hashId
subInjectHash = true;
} else if (mergedKey === '&') {
// 抹掉 root selector 上的单个 &
mergedKey = injectSelectorHash('', hashId, hashPriority);
} else {
// 注入 hashId
mergedKey = injectSelectorHash(key, hashId, hashPriority);
}
} else if (
root &&
!hashId &&
(mergedKey === '&' || mergedKey === '')
) {
// In case of `{ '&': { a: { color: 'red' } } }` or `{ '': { a: { color: 'red' } } }` without hashId,
// we will get `&{a:{color:red;}}` or `{a:{color:red;}}` string for stylis to compile.
// But it does not conform to stylis syntax,
// and finally we will get `{color:red;}` as css, which is wrong.
// So we need to remove key in root, and treat child `{ a: { color: 'red' } }` as root.
mergedKey = '';
nextRoot = true;
}
const [parsedStr, childEffectStyle] = parseStyle(
value as any,
config,
{
root: nextRoot,
injectHash: subInjectHash,
parentSelectors: [...parentSelectors, mergedKey],
},
);
effectStyle = {
...effectStyle,
...childEffectStyle,
};
styleStr += `${mergedKey}${parsedStr}`;
} else {
function appendStyle(cssKey: string, cssValue: any) {
if (
process.env.NODE_ENV !== 'production' &&
(typeof value !== 'object' || !(value as any)?.[SKIP_CHECK])
) {
[contentQuotesLinter, hashedAnimationLinter, ...linters].forEach(
(linter) =>
linter(cssKey, cssValue, { path, hashId, parentSelectors }),
);
}
// 如果是样式则直接插入
const styleName = cssKey.replace(
/[A-Z]/g,
(match) => `-${match.toLowerCase()}`,
);
// Auto suffix with px
let formatValue = cssValue;
if (
!unitless[cssKey] &&
typeof formatValue === 'number' &&
formatValue !== 0
) {
formatValue = `${formatValue}px`;
}
// handle animationName & Keyframe value
if (
cssKey === 'animationName' &&
(cssValue as Keyframes)?._keyframe
) {
parseKeyframes(cssValue as Keyframes);
formatValue = (cssValue as Keyframes).getName(hashId);
}
styleStr += `${styleName}:${formatValue};`;
}
const actualValue = (value as any)?.value ?? value;
if (
typeof value === 'object' &&
(value as any)?.[MULTI_VALUE] &&
Array.isArray(actualValue)
) {
actualValue.forEach((item) => {
appendStyle(key, item);
});
} else {
appendStyle(key, actualValue);
}
}
});
}
});
if (!root) {
styleStr = `{${styleStr}}`;
} else if (layer) {
// fixme: https://github.com/thysultan/stylis/pull/339
if (styleStr) {
styleStr = `@layer ${layer.name} {${styleStr}}`;
}
if (layer.dependencies) {
effectStyle[`@layer ${layer.name}`] = layer.dependencies
.map((deps) => `@layer ${deps}, ${layer.name};`)
.join('\n');
}
}
return [styleStr, effectStyle];
};
// ============================================================================
// == Register ==
// ============================================================================
export function uniqueHash(path: (string | number)[], styleStr: string) {
return hash(`${path.join('%')}${styleStr}`);
}
function Empty() {
return null;
}
export const STYLE_PREFIX = 'style';
type StyleCacheValue = [
styleStr: string,
tokenKey: string,
styleId: string,
effectStyle: Record<string, string>,
clientOnly: boolean | undefined,
order: number,
];
/**
* Register a style to the global style sheet.
*/
export default function useStyleRegister(
info: {
theme: Theme<any, any>;
token: any;
path: string[];
hashId?: string;
layer?: LayerConfig;
nonce?: string | (() => string);
clientOnly?: boolean;
/**
* Tell cssinjs the insert order of style.
* It's useful when you need to insert style
* before other style to overwrite for the same selector priority.
*/
order?: number;
},
styleFn: () => CSSInterpolation,
) {
const { token, path, hashId, layer, nonce, clientOnly, order = 0 } = info;
const {
autoClear,
mock,
defaultCache,
hashPriority,
container,
ssrInline,
transformers,
linters,
cache,
layer: enableLayer,
} = React.useContext(StyleContext);
const tokenKey = token._tokenKey as string;
const fullPath = [tokenKey];
if (enableLayer) {
fullPath.push('layer');
}
fullPath.push(...path);
// Check if need insert style
let isMergedClientSide = isClientSide;
if (process.env.NODE_ENV !== 'production' && mock !== undefined) {
isMergedClientSide = mock === 'client';
}
const [cachedStyleStr, cachedTokenKey, cachedStyleId] =
useGlobalCache<StyleCacheValue>(
STYLE_PREFIX,
fullPath,
// Create cache if needed
() => {
const cachePath = fullPath.join('|');
// Get style from SSR inline style directly
if (existPath(cachePath)) {
const [inlineCacheStyleStr, styleHash] = getStyleAndHash(cachePath);
if (inlineCacheStyleStr) {
return [
inlineCacheStyleStr,
tokenKey,
styleHash,
{},
clientOnly,
order,
];
}
}
// Generate style
const styleObj = styleFn();
const [parsedStyle, effectStyle] = parseStyle(styleObj, {
hashId,
hashPriority,
layer: enableLayer ? layer : undefined,
path: path.join('-'),
transformers,
linters,
});
const styleStr = normalizeStyle(parsedStyle);
const styleId = uniqueHash(fullPath, styleStr);
return [styleStr, tokenKey, styleId, effectStyle, clientOnly, order];
},
// Remove cache if no need
([, , styleId], fromHMR) => {
if ((fromHMR || autoClear) && isClientSide) {
removeCSS(styleId, { mark: ATTR_MARK });
}
},
// Effect: Inject style here
([styleStr, _, styleId, effectStyle]) => {
if (isMergedClientSide && styleStr !== CSS_FILE_STYLE) {
const mergedCSSConfig: Parameters<typeof updateCSS>[2] = {
mark: ATTR_MARK,
prepend: enableLayer ? false : 'queue',
attachTo: container,
priority: order,
};
const nonceStr = typeof nonce === 'function' ? nonce() : nonce;
if (nonceStr) {
mergedCSSConfig.csp = { nonce: nonceStr };
}
// ================= Split Effect Style =================
// We will split effectStyle here since @layer should be at the top level
const effectLayerKeys: string[] = [];
const effectRestKeys: string[] = [];
Object.keys(effectStyle).forEach((key) => {
if (key.startsWith('@layer')) {
effectLayerKeys.push(key);
} else {
effectRestKeys.push(key);
}
});
// ================= Inject Layer Style =================
// Inject layer style
effectLayerKeys.forEach((effectKey) => {
updateCSS(
normalizeStyle(effectStyle[effectKey]),
`_layer-${effectKey}`,
{ ...mergedCSSConfig, prepend: true },
);
});
// ==================== Inject Style ====================
// Inject style
const style = updateCSS(styleStr, styleId, mergedCSSConfig);
(style as any)[CSS_IN_JS_INSTANCE] = cache.instanceId;
// Used for `useCacheToken` to remove on batch when token removed
style.setAttribute(ATTR_TOKEN, tokenKey);
// Debug usage. Dev only
if (process.env.NODE_ENV !== 'production') {
style.setAttribute(ATTR_CACHE_PATH, fullPath.join('|'));
}
// ================ Inject Effect Style =================
// Inject client side effect style
effectRestKeys.forEach((effectKey) => {
updateCSS(
normalizeStyle(effectStyle[effectKey]),
`_effect-${effectKey}`,
mergedCSSConfig,
);
});
}
},
);
return (node: React.ReactElement) => {
let styleNode: React.ReactElement;
if (!ssrInline || isMergedClientSide || !defaultCache) {
styleNode = <Empty />;
} else {
styleNode = (
<style
{...{
[ATTR_TOKEN]: cachedTokenKey,
[ATTR_MARK]: cachedStyleId,
}}
dangerouslySetInnerHTML={{ __html: cachedStyleStr }}
/>
);
}
return (
<>
{styleNode}
{node}
</>
);
};
}
export const extract: ExtractStyle<StyleCacheValue> = (
cache,
effectStyles,
options,
) => {
const [
styleStr,
tokenKey,
styleId,
effectStyle,
clientOnly,
order,
]: StyleCacheValue = cache;
const { plain } = options || {};
// Skip client only style
if (clientOnly) {
return null;
}
let keyStyleText = styleStr;
// ====================== Share ======================
// Used for rc-util
const sharedAttrs = {
'data-rc-order': 'prependQueue',
'data-rc-priority': `${order}`,
};
// ====================== Style ======================
keyStyleText = toStyleStr(styleStr, tokenKey, styleId, sharedAttrs, plain);
// =============== Create effect style ===============
if (effectStyle) {
Object.keys(effectStyle).forEach((effectKey) => {
// Effect style can be reused
if (!effectStyles[effectKey]) {
effectStyles[effectKey] = true;
const effectStyleStr = normalizeStyle(effectStyle[effectKey]);
const effectStyleHTML = toStyleStr(
effectStyleStr,
tokenKey,
`_effect-${effectKey}`,
sharedAttrs,
plain,
);
if (effectKey.startsWith('@layer')) {
keyStyleText = effectStyleHTML + keyStyleText;
} else {
keyStyleText += effectStyleHTML;
}
}
});
}
return [order, styleId, keyStyleText];
};