You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.9 KiB

  1. // @flow
  2. import getBasePlacement from './getBasePlacement';
  3. import getVariation from './getVariation';
  4. import getMainAxisFromPlacement from './getMainAxisFromPlacement';
  5. import type {
  6. Rect,
  7. PositioningStrategy,
  8. Offsets,
  9. ClientRectObject,
  10. } from '../types';
  11. import { top, right, bottom, left, start, end, type Placement } from '../enums';
  12. export default function computeOffsets({
  13. reference,
  14. element,
  15. placement,
  16. }: {
  17. reference: Rect | ClientRectObject,
  18. element: Rect | ClientRectObject,
  19. strategy: PositioningStrategy,
  20. placement?: Placement,
  21. }): Offsets {
  22. const basePlacement = placement ? getBasePlacement(placement) : null;
  23. const variation = placement ? getVariation(placement) : null;
  24. const commonX = reference.x + reference.width / 2 - element.width / 2;
  25. const commonY = reference.y + reference.height / 2 - element.height / 2;
  26. let offsets;
  27. switch (basePlacement) {
  28. case top:
  29. offsets = {
  30. x: commonX,
  31. y: reference.y - element.height,
  32. };
  33. break;
  34. case bottom:
  35. offsets = {
  36. x: commonX,
  37. y: reference.y + reference.height,
  38. };
  39. break;
  40. case right:
  41. offsets = {
  42. x: reference.x + reference.width,
  43. y: commonY,
  44. };
  45. break;
  46. case left:
  47. offsets = {
  48. x: reference.x - element.width,
  49. y: commonY,
  50. };
  51. break;
  52. default:
  53. offsets = {
  54. x: reference.x,
  55. y: reference.y,
  56. };
  57. }
  58. const mainAxis = basePlacement
  59. ? getMainAxisFromPlacement(basePlacement)
  60. : null;
  61. if (mainAxis != null) {
  62. const len = mainAxis === 'y' ? 'height' : 'width';
  63. switch (variation) {
  64. case start:
  65. offsets[mainAxis] =
  66. offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
  67. break;
  68. case end:
  69. offsets[mainAxis] =
  70. offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
  71. break;
  72. default:
  73. }
  74. }
  75. return offsets;
  76. }