1 | // @flow
|
---|
2 | import type { State, Padding } from '../types';
|
---|
3 | import type {
|
---|
4 | Placement,
|
---|
5 | ComputedPlacement,
|
---|
6 | Boundary,
|
---|
7 | RootBoundary,
|
---|
8 | } from '../enums';
|
---|
9 | import getVariation from './getVariation';
|
---|
10 | import {
|
---|
11 | variationPlacements,
|
---|
12 | basePlacements,
|
---|
13 | placements as allPlacements,
|
---|
14 | } from '../enums';
|
---|
15 | import detectOverflow from './detectOverflow';
|
---|
16 | import getBasePlacement from './getBasePlacement';
|
---|
17 |
|
---|
18 | type Options = {
|
---|
19 | placement: Placement,
|
---|
20 | padding: Padding,
|
---|
21 | boundary: Boundary,
|
---|
22 | rootBoundary: RootBoundary,
|
---|
23 | flipVariations: boolean,
|
---|
24 | allowedAutoPlacements?: Array<Placement>,
|
---|
25 | };
|
---|
26 |
|
---|
27 | type OverflowsMap = { [ComputedPlacement]: number };
|
---|
28 |
|
---|
29 | export default function computeAutoPlacement(
|
---|
30 | state: $Shape<State>,
|
---|
31 | options: Options = {}
|
---|
32 | ): Array<ComputedPlacement> {
|
---|
33 | const {
|
---|
34 | placement,
|
---|
35 | boundary,
|
---|
36 | rootBoundary,
|
---|
37 | padding,
|
---|
38 | flipVariations,
|
---|
39 | allowedAutoPlacements = allPlacements,
|
---|
40 | } = options;
|
---|
41 |
|
---|
42 | const variation = getVariation(placement);
|
---|
43 |
|
---|
44 | const placements = variation
|
---|
45 | ? flipVariations
|
---|
46 | ? variationPlacements
|
---|
47 | : variationPlacements.filter(
|
---|
48 | (placement) => getVariation(placement) === variation
|
---|
49 | )
|
---|
50 | : basePlacements;
|
---|
51 |
|
---|
52 | let allowedPlacements = placements.filter(
|
---|
53 | (placement) => allowedAutoPlacements.indexOf(placement) >= 0
|
---|
54 | );
|
---|
55 |
|
---|
56 | if (allowedPlacements.length === 0) {
|
---|
57 | allowedPlacements = placements;
|
---|
58 | }
|
---|
59 |
|
---|
60 | // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...
|
---|
61 | const overflows: OverflowsMap = allowedPlacements.reduce((acc, placement) => {
|
---|
62 | acc[placement] = detectOverflow(state, {
|
---|
63 | placement,
|
---|
64 | boundary,
|
---|
65 | rootBoundary,
|
---|
66 | padding,
|
---|
67 | })[getBasePlacement(placement)];
|
---|
68 |
|
---|
69 | return acc;
|
---|
70 | }, {});
|
---|
71 |
|
---|
72 | return Object.keys(overflows).sort((a, b) => overflows[a] - overflows[b]);
|
---|
73 | }
|
---|