1
This commit is contained in:
+14
@@ -0,0 +1,14 @@
|
||||
export declare const ATTR_CACHE_MAP = "data-ant-cssinjs-cache-path";
|
||||
/**
|
||||
* This marks style from the css file.
|
||||
* Which means not exist in `<style />` tag.
|
||||
*/
|
||||
export declare const CSS_FILE_STYLE = "_FILE_STYLE__";
|
||||
export declare function serialize(cachePathMap: Record<string, string>): string;
|
||||
/**
|
||||
* @private Test usage only. Can save remove if no need.
|
||||
*/
|
||||
export declare function reset(mockCache?: Record<string, string>, fromFile?: boolean): void;
|
||||
export declare function prepare(): void;
|
||||
export declare function existPath(path: string): boolean;
|
||||
export declare function getStyleAndHash(path: string): [style: string | null, hash: string];
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
import canUseDom from "@rc-component/util/es/Dom/canUseDom";
|
||||
import { ATTR_MARK } from "../StyleContext";
|
||||
export const ATTR_CACHE_MAP = 'data-ant-cssinjs-cache-path';
|
||||
|
||||
/**
|
||||
* This marks style from the css file.
|
||||
* Which means not exist in `<style />` tag.
|
||||
*/
|
||||
export const CSS_FILE_STYLE = '_FILE_STYLE__';
|
||||
export function serialize(cachePathMap) {
|
||||
return Object.keys(cachePathMap).map(path => {
|
||||
const hash = cachePathMap[path];
|
||||
return `${path}:${hash}`;
|
||||
}).join(';');
|
||||
}
|
||||
let cachePathMap;
|
||||
let fromCSSFile = true;
|
||||
|
||||
/**
|
||||
* @private Test usage only. Can save remove if no need.
|
||||
*/
|
||||
export function reset(mockCache, fromFile = true) {
|
||||
cachePathMap = mockCache;
|
||||
fromCSSFile = fromFile;
|
||||
}
|
||||
export function prepare() {
|
||||
if (!cachePathMap) {
|
||||
cachePathMap = {};
|
||||
if (canUseDom()) {
|
||||
const div = document.createElement('div');
|
||||
div.className = ATTR_CACHE_MAP;
|
||||
div.style.position = 'fixed';
|
||||
div.style.visibility = 'hidden';
|
||||
div.style.top = '-9999px';
|
||||
document.body.appendChild(div);
|
||||
let content = getComputedStyle(div).content || '';
|
||||
content = content.replace(/^"/, '').replace(/"$/, '');
|
||||
|
||||
// Fill data
|
||||
content.split(';').forEach(item => {
|
||||
const [path, hash] = item.split(':');
|
||||
cachePathMap[path] = hash;
|
||||
});
|
||||
|
||||
// Remove inline record style
|
||||
const inlineMapStyle = document.querySelector(`style[${ATTR_CACHE_MAP}]`);
|
||||
if (inlineMapStyle) {
|
||||
fromCSSFile = false;
|
||||
inlineMapStyle.parentNode?.removeChild(inlineMapStyle);
|
||||
}
|
||||
document.body.removeChild(div);
|
||||
}
|
||||
}
|
||||
}
|
||||
export function existPath(path) {
|
||||
prepare();
|
||||
return !!cachePathMap[path];
|
||||
}
|
||||
export function getStyleAndHash(path) {
|
||||
const hash = cachePathMap[path];
|
||||
let styleStr = null;
|
||||
if (hash && canUseDom()) {
|
||||
if (fromCSSFile) {
|
||||
styleStr = CSS_FILE_STYLE;
|
||||
} else {
|
||||
const style = document.querySelector(`style[${ATTR_MARK}="${cachePathMap[path]}"]`);
|
||||
if (style) {
|
||||
styleStr = style.innerHTML;
|
||||
} else {
|
||||
// Clean up since not exist anymore
|
||||
delete cachePathMap[path];
|
||||
}
|
||||
}
|
||||
}
|
||||
return [styleStr, hash];
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import type { HashPriority } from '../StyleContext';
|
||||
export declare const token2CSSVar: (token: string, prefix?: string) => string;
|
||||
export declare const serializeCSSVar: <T extends Record<string, any>>(cssVars: T, hashId: string, options?: {
|
||||
scope?: string | string[];
|
||||
hashCls?: string;
|
||||
hashPriority?: HashPriority;
|
||||
}) => string;
|
||||
export type TokenWithCSSVar<V, T extends Record<string, V> = Record<string, V>> = {
|
||||
[key in keyof T]?: string | V;
|
||||
};
|
||||
export declare const transformToken: <V, T extends Record<string, V> = Record<string, V>>(token: T, themeKey: string, config?: {
|
||||
prefix?: string | undefined;
|
||||
ignore?: { [key in keyof T]?: boolean | undefined; } | undefined;
|
||||
unitless?: { [key_1 in keyof T]?: boolean | undefined; } | undefined;
|
||||
preserve?: { [key_2 in keyof T]?: boolean | undefined; } | undefined;
|
||||
scope?: string | string[] | undefined;
|
||||
hashCls?: string | undefined;
|
||||
hashPriority?: HashPriority | undefined;
|
||||
} | undefined) => [TokenWithCSSVar<V, T>, string];
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import { where } from "../util";
|
||||
export const token2CSSVar = (token, prefix = '') => {
|
||||
return `--${prefix ? `${prefix}-` : ''}${token}`.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/([A-Z]+)([A-Z][a-z0-9]+)/g, '$1-$2').replace(/([a-z])([A-Z0-9])/g, '$1-$2').toLowerCase();
|
||||
};
|
||||
export const serializeCSSVar = (cssVars, hashId, options) => {
|
||||
const {
|
||||
hashCls,
|
||||
hashPriority = 'low',
|
||||
scope
|
||||
} = options || {};
|
||||
if (!Object.keys(cssVars).length) {
|
||||
return '';
|
||||
}
|
||||
const baseSelector = `${where({
|
||||
hashCls,
|
||||
hashPriority
|
||||
})}.${hashId}`;
|
||||
const scopes = [scope].flat().filter(Boolean);
|
||||
const selector = scopes.length ? scopes.map(s => `${baseSelector}.${s}`).join(', ') : baseSelector;
|
||||
return `${selector}{${Object.entries(cssVars).map(([key, value]) => `${key}:${value};`).join('')}}`;
|
||||
};
|
||||
export const transformToken = (token, themeKey, config) => {
|
||||
const {
|
||||
hashCls,
|
||||
hashPriority = 'low',
|
||||
prefix,
|
||||
unitless,
|
||||
ignore,
|
||||
preserve
|
||||
} = config || {};
|
||||
const cssVars = {};
|
||||
const result = {};
|
||||
Object.entries(token).forEach(([key, value]) => {
|
||||
if (preserve?.[key]) {
|
||||
result[key] = value;
|
||||
} else if ((typeof value === 'string' || typeof value === 'number') && !ignore?.[key]) {
|
||||
const cssVar = token2CSSVar(key, prefix);
|
||||
cssVars[cssVar] = typeof value === 'number' && !unitless?.[key] ? `${value}px` : String(value);
|
||||
result[key] = `var(${cssVar})`;
|
||||
}
|
||||
});
|
||||
return [result, serializeCSSVar(cssVars, themeKey, {
|
||||
scope: config?.scope,
|
||||
hashCls,
|
||||
hashPriority
|
||||
})];
|
||||
};
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import type { HashPriority } from '../StyleContext';
|
||||
export declare function memoResult<T extends object, R>(callback: () => R, deps: T[]): R;
|
||||
/**
|
||||
* Flatten token to string, this will auto cache the result when token not change
|
||||
*/
|
||||
export declare function flattenToken(token: any): string;
|
||||
/**
|
||||
* Convert derivative token to key string
|
||||
*/
|
||||
export declare function token2key(token: any, salt: string): string;
|
||||
export declare function supportLayer(): boolean;
|
||||
export declare function supportWhere(): boolean;
|
||||
export declare function supportLogicProps(): boolean;
|
||||
export declare const isClientSide: boolean;
|
||||
export declare function unit(num: string | number): string;
|
||||
export declare function toStyleStr(style: string, tokenKey?: string, styleId?: string, customizeAttrs?: Record<string, string>, plain?: boolean): string;
|
||||
export declare function where(options?: {
|
||||
hashPriority?: HashPriority;
|
||||
hashCls?: string;
|
||||
}): string;
|
||||
export declare const isNonNullable: <T>(val: T) => val is NonNullable<T>;
|
||||
export type Nonce = string | (() => string);
|
||||
/**
|
||||
* Get nonce value and inject it into CSS config if available.
|
||||
*/
|
||||
export declare function injectCSPNonce<T extends {
|
||||
csp?: {
|
||||
nonce?: string;
|
||||
};
|
||||
}>(config: T, nonce: Nonce | undefined): T;
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import hash from '@emotion/hash';
|
||||
import canUseDom from "@rc-component/util/es/Dom/canUseDom";
|
||||
import { removeCSS, updateCSS } from "@rc-component/util/es/Dom/dynamicCSS";
|
||||
import { ATTR_MARK, ATTR_TOKEN } from "../StyleContext";
|
||||
import { Theme } from "../theme";
|
||||
|
||||
// Create a cache for memo concat
|
||||
|
||||
const resultCache = new WeakMap();
|
||||
const RESULT_VALUE = {};
|
||||
export function memoResult(callback, deps) {
|
||||
let current = 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();
|
||||
|
||||
/**
|
||||
* Flatten token to string, this will auto cache the result when token not change
|
||||
*/
|
||||
export function flattenToken(token) {
|
||||
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, salt) {
|
||||
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, handleElement, supportCheck) {
|
||||
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 = undefined;
|
||||
export function supportLayer() {
|
||||
if (canLayer === undefined) {
|
||||
canLayer = supportSelector(`@layer ${randomSelectorKey} { .${randomSelectorKey} { content: "${checkContent}"!important; } }`, ele => {
|
||||
ele.className = randomSelectorKey;
|
||||
});
|
||||
}
|
||||
return canLayer;
|
||||
}
|
||||
let canWhere = undefined;
|
||||
export function supportWhere() {
|
||||
if (canWhere === undefined) {
|
||||
canWhere = supportSelector(`:where(.${randomSelectorKey}) { content: "${checkContent}"!important; }`, ele => {
|
||||
ele.className = randomSelectorKey;
|
||||
});
|
||||
}
|
||||
return canWhere;
|
||||
}
|
||||
let canLogic = undefined;
|
||||
export function supportLogicProps() {
|
||||
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) {
|
||||
if (typeof num === 'number') {
|
||||
return `${num}px`;
|
||||
}
|
||||
return num;
|
||||
}
|
||||
export function toStyleStr(style, tokenKey, styleId, customizeAttrs = {}, plain = false) {
|
||||
if (plain) {
|
||||
return style;
|
||||
}
|
||||
const attrs = {
|
||||
...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) {
|
||||
const {
|
||||
hashCls,
|
||||
hashPriority = 'low'
|
||||
} = options || {};
|
||||
if (!hashCls) {
|
||||
return '';
|
||||
}
|
||||
const hashSelector = `.${hashCls}`;
|
||||
return hashPriority === 'low' ? `:where(${hashSelector})` : hashSelector;
|
||||
}
|
||||
export const isNonNullable = val => {
|
||||
return val !== undefined && val !== null;
|
||||
};
|
||||
/**
|
||||
* Get nonce value and inject it into CSS config if available.
|
||||
*/
|
||||
export function injectCSPNonce(config, nonce) {
|
||||
const nonceStr = typeof nonce === 'function' ? nonce() : nonce;
|
||||
if (nonceStr) {
|
||||
return {
|
||||
...config,
|
||||
csp: {
|
||||
...config.csp,
|
||||
nonce: nonceStr
|
||||
}
|
||||
};
|
||||
}
|
||||
return config;
|
||||
}
|
||||
Reference in New Issue
Block a user