ant-design-vue/components/_util/cssinjs/hooks/useGlobalCache.tsx

59 lines
1.8 KiB
Vue
Raw Normal View History

2023-01-24 14:51:59 +00:00
import { useStyleInject } from '../StyleContext';
import type { KeyType } from '../Cache';
import useHMR from './useHMR';
2023-03-13 03:11:40 +00:00
import type { ShallowRef, Ref } from 'vue';
import { onBeforeUnmount, watch, watchEffect, shallowRef } from 'vue';
2023-01-24 14:51:59 +00:00
export default function useClientCache<CacheType>(
prefix: string,
keyPath: Ref<KeyType[]>,
cacheFn: () => CacheType,
onCacheRemove?: (cache: CacheType, fromHMR: boolean) => void,
2023-03-13 03:11:40 +00:00
): ShallowRef<CacheType> {
2023-01-24 14:51:59 +00:00
const styleContext = useStyleInject();
2023-03-12 15:48:46 +00:00
const fullPathStr = shallowRef('');
2023-03-13 03:11:40 +00:00
const res = shallowRef<CacheType>();
2023-03-12 15:48:46 +00:00
watchEffect(() => {
2023-03-13 03:11:40 +00:00
fullPathStr.value = [prefix, ...keyPath.value].join('%');
2023-03-12 15:48:46 +00:00
});
2023-01-24 14:51:59 +00:00
const HMRUpdate = useHMR();
2023-03-13 03:11:40 +00:00
const clearCache = (pathStr: string) => {
styleContext.value.cache.update(pathStr, prevCache => {
2023-01-24 14:51:59 +00:00
const [times = 0, cache] = prevCache || [];
const nextCount = times - 1;
if (nextCount === 0) {
onCacheRemove?.(cache, false);
return null;
}
return [times - 1, cache];
});
};
2023-03-12 15:48:46 +00:00
watch(
2023-03-13 03:11:40 +00:00
fullPathStr,
(newStr, oldStr) => {
if (oldStr) clearCache(oldStr);
// Create cache
styleContext.value.cache.update(newStr, prevCache => {
2023-03-13 03:11:40 +00:00
const [times = 0, cache] = prevCache || [];
2023-01-24 14:51:59 +00:00
2023-03-13 03:11:40 +00:00
// HMR should always ignore cache since developer may change it
let tmpCache = cache;
if (process.env.NODE_ENV !== 'production' && cache && HMRUpdate) {
onCacheRemove?.(tmpCache, HMRUpdate);
tmpCache = null;
}
const mergedCache = tmpCache || cacheFn();
2023-01-24 14:51:59 +00:00
2023-03-13 03:11:40 +00:00
return [times + 1, mergedCache];
});
res.value = styleContext.value.cache.get(fullPathStr.value)![1];
2023-01-24 14:51:59 +00:00
},
{ immediate: true },
);
onBeforeUnmount(() => {
2023-03-13 03:11:40 +00:00
clearCache(fullPathStr.value);
2023-03-12 15:48:46 +00:00
});
2023-03-13 03:11:40 +00:00
return res;
2023-01-24 14:51:59 +00:00
}