cacheMapUtil.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import canUseDom from '../../../../_util/canUseDom';
  2. import { ATTR_MARK } from '../../StyleContext';
  3. export const ATTR_CACHE_MAP = 'data-ant-cssinjs-cache-path';
  4. /**
  5. * This marks style from the css file.
  6. * Which means not exist in `<style />` tag.
  7. */
  8. export const CSS_FILE_STYLE = '_FILE_STYLE__';
  9. export function serialize(cachePathMap) {
  10. return Object.keys(cachePathMap).map(path => {
  11. const hash = cachePathMap[path];
  12. return `${path}:${hash}`;
  13. }).join(';');
  14. }
  15. let cachePathMap;
  16. let fromCSSFile = true;
  17. /**
  18. * @private Test usage only. Can save remove if no need.
  19. */
  20. export function reset(mockCache) {
  21. let fromFile = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  22. cachePathMap = mockCache;
  23. fromCSSFile = fromFile;
  24. }
  25. export function prepare() {
  26. var _a;
  27. if (!cachePathMap) {
  28. cachePathMap = {};
  29. if (canUseDom()) {
  30. const div = document.createElement('div');
  31. div.className = ATTR_CACHE_MAP;
  32. div.style.position = 'fixed';
  33. div.style.visibility = 'hidden';
  34. div.style.top = '-9999px';
  35. document.body.appendChild(div);
  36. let content = getComputedStyle(div).content || '';
  37. content = content.replace(/^"/, '').replace(/"$/, '');
  38. // Fill data
  39. content.split(';').forEach(item => {
  40. const [path, hash] = item.split(':');
  41. cachePathMap[path] = hash;
  42. });
  43. // Remove inline record style
  44. const inlineMapStyle = document.querySelector(`style[${ATTR_CACHE_MAP}]`);
  45. if (inlineMapStyle) {
  46. fromCSSFile = false;
  47. (_a = inlineMapStyle.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(inlineMapStyle);
  48. }
  49. document.body.removeChild(div);
  50. }
  51. }
  52. }
  53. export function existPath(path) {
  54. prepare();
  55. return !!cachePathMap[path];
  56. }
  57. export function getStyleAndHash(path) {
  58. const hash = cachePathMap[path];
  59. let styleStr = null;
  60. if (hash && canUseDom()) {
  61. if (fromCSSFile) {
  62. styleStr = CSS_FILE_STYLE;
  63. } else {
  64. const style = document.querySelector(`style[${ATTR_MARK}="${cachePathMap[path]}"]`);
  65. if (style) {
  66. styleStr = style.innerHTML;
  67. } else {
  68. // Clean up since not exist anymore
  69. delete cachePathMap[path];
  70. }
  71. }
  72. }
  73. return [styleStr, hash];
  74. }