useZIndex.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import React from 'react';
  2. import useToken from '../../theme/useToken';
  3. import { devUseWarning } from '../warning';
  4. import zIndexContext from '../zindexContext';
  5. // Z-Index control range
  6. // Container: 1000 + offset 100 (max base + 10 * offset = 2000)
  7. // Popover: offset 50
  8. // Notification: Container Max zIndex + componentOffset
  9. const CONTAINER_OFFSET = 100;
  10. const CONTAINER_OFFSET_MAX_COUNT = 10;
  11. export const CONTAINER_MAX_OFFSET = CONTAINER_OFFSET * CONTAINER_OFFSET_MAX_COUNT;
  12. /**
  13. * Static function will default be the `CONTAINER_MAX_OFFSET`.
  14. * But it still may have children component like Select, Dropdown.
  15. * So the warning zIndex should exceed the `CONTAINER_MAX_OFFSET`.
  16. */
  17. const CONTAINER_MAX_OFFSET_WITH_CHILDREN = CONTAINER_MAX_OFFSET + CONTAINER_OFFSET;
  18. export const containerBaseZIndexOffset = {
  19. Modal: CONTAINER_OFFSET,
  20. Drawer: CONTAINER_OFFSET,
  21. Popover: CONTAINER_OFFSET,
  22. Popconfirm: CONTAINER_OFFSET,
  23. Tooltip: CONTAINER_OFFSET,
  24. Tour: CONTAINER_OFFSET,
  25. FloatButton: CONTAINER_OFFSET
  26. };
  27. export const consumerBaseZIndexOffset = {
  28. SelectLike: 50,
  29. Dropdown: 50,
  30. DatePicker: 50,
  31. Menu: 50,
  32. ImagePreview: 1
  33. };
  34. function isContainerType(type) {
  35. return type in containerBaseZIndexOffset;
  36. }
  37. export const useZIndex = (componentType, customZIndex) => {
  38. const [, token] = useToken();
  39. const parentZIndex = React.useContext(zIndexContext);
  40. const isContainer = isContainerType(componentType);
  41. let result;
  42. if (customZIndex !== undefined) {
  43. result = [customZIndex, customZIndex];
  44. } else {
  45. let zIndex = parentZIndex !== null && parentZIndex !== void 0 ? parentZIndex : 0;
  46. if (isContainer) {
  47. zIndex +=
  48. // Use preset token zIndex by default but not stack when has parent container
  49. (parentZIndex ? 0 : token.zIndexPopupBase) +
  50. // Container offset
  51. containerBaseZIndexOffset[componentType];
  52. } else {
  53. zIndex += consumerBaseZIndexOffset[componentType];
  54. }
  55. result = [parentZIndex === undefined ? customZIndex : zIndex, zIndex];
  56. }
  57. if (process.env.NODE_ENV !== 'production') {
  58. const warning = devUseWarning(componentType);
  59. const maxZIndex = token.zIndexPopupBase + CONTAINER_MAX_OFFSET_WITH_CHILDREN;
  60. const currentZIndex = result[0] || 0;
  61. process.env.NODE_ENV !== "production" ? warning(customZIndex !== undefined || currentZIndex <= maxZIndex, 'usage', '`zIndex` is over design token `zIndexPopupBase` too much. It may cause unexpected override.') : void 0;
  62. }
  63. return result;
  64. };