cacheMapUtil.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
  2. import canUseDom from "rc-util/es/Dom/canUseDom";
  3. import { ATTR_MARK } from "../StyleContext";
  4. export var ATTR_CACHE_MAP = 'data-ant-cssinjs-cache-path';
  5. /**
  6. * This marks style from the css file.
  7. * Which means not exist in `<style />` tag.
  8. */
  9. export var CSS_FILE_STYLE = '_FILE_STYLE__';
  10. export function serialize(cachePathMap) {
  11. return Object.keys(cachePathMap).map(function (path) {
  12. var hash = cachePathMap[path];
  13. return "".concat(path, ":").concat(hash);
  14. }).join(';');
  15. }
  16. var cachePathMap;
  17. var fromCSSFile = true;
  18. /**
  19. * @private Test usage only. Can save remove if no need.
  20. */
  21. export function reset(mockCache) {
  22. var fromFile = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  23. cachePathMap = mockCache;
  24. fromCSSFile = fromFile;
  25. }
  26. export function prepare() {
  27. if (!cachePathMap) {
  28. cachePathMap = {};
  29. if (canUseDom()) {
  30. var 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. var content = getComputedStyle(div).content || '';
  37. content = content.replace(/^"/, '').replace(/"$/, '');
  38. // Fill data
  39. content.split(';').forEach(function (item) {
  40. var _item$split = item.split(':'),
  41. _item$split2 = _slicedToArray(_item$split, 2),
  42. path = _item$split2[0],
  43. hash = _item$split2[1];
  44. cachePathMap[path] = hash;
  45. });
  46. // Remove inline record style
  47. var inlineMapStyle = document.querySelector("style[".concat(ATTR_CACHE_MAP, "]"));
  48. if (inlineMapStyle) {
  49. var _inlineMapStyle$paren;
  50. fromCSSFile = false;
  51. (_inlineMapStyle$paren = inlineMapStyle.parentNode) === null || _inlineMapStyle$paren === void 0 || _inlineMapStyle$paren.removeChild(inlineMapStyle);
  52. }
  53. document.body.removeChild(div);
  54. }
  55. }
  56. }
  57. export function existPath(path) {
  58. prepare();
  59. return !!cachePathMap[path];
  60. }
  61. export function getStyleAndHash(path) {
  62. var hash = cachePathMap[path];
  63. var styleStr = null;
  64. if (hash && canUseDom()) {
  65. if (fromCSSFile) {
  66. styleStr = CSS_FILE_STYLE;
  67. } else {
  68. var _style = document.querySelector("style[".concat(ATTR_MARK, "=\"").concat(cachePathMap[path], "\"]"));
  69. if (_style) {
  70. styleStr = _style.innerHTML;
  71. } else {
  72. // Clean up since not exist anymore
  73. delete cachePathMap[path];
  74. }
  75. }
  76. }
  77. return [styleStr, hash];
  78. }