@fluentui/react-positioning 0.0.0-nightlyfe9829e48120211112.1 → 0.0.0-nightlyff78d1e27a20220217.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (72) hide show
  1. package/CHANGELOG.json +173 -8
  2. package/CHANGELOG.md +49 -7
  3. package/dist/react-positioning.d.ts +113 -35
  4. package/lib/createArrowStyles.d.ts +64 -0
  5. package/lib/createArrowStyles.js +87 -0
  6. package/lib/createArrowStyles.js.map +1 -0
  7. package/lib/createVirtualElementFromClick.js +17 -15
  8. package/lib/createVirtualElementFromClick.js.map +1 -1
  9. package/lib/index.d.ts +2 -1
  10. package/lib/index.js +2 -1
  11. package/lib/index.js.map +1 -1
  12. package/lib/types.d.ts +28 -7
  13. package/lib/types.js.map +1 -1
  14. package/lib/usePopper.d.ts +2 -14
  15. package/lib/usePopper.js +367 -311
  16. package/lib/usePopper.js.map +1 -1
  17. package/lib/usePopperMouseTarget.js +28 -22
  18. package/lib/usePopperMouseTarget.js.map +1 -1
  19. package/lib/utils/getBasePlacement.js +1 -1
  20. package/lib/utils/getBasePlacement.js.map +1 -1
  21. package/lib/utils/getBoundary.js +15 -10
  22. package/lib/utils/getBoundary.js.map +1 -1
  23. package/lib/utils/getReactFiberFromNode.js +39 -35
  24. package/lib/utils/getReactFiberFromNode.js.map +1 -1
  25. package/lib/utils/getScrollParent.js +46 -32
  26. package/lib/utils/getScrollParent.js.map +1 -1
  27. package/lib/utils/index.js.map +1 -1
  28. package/lib/utils/mergeArrowOffset.js +29 -24
  29. package/lib/utils/mergeArrowOffset.js.map +1 -1
  30. package/lib/utils/positioningHelper.d.ts +2 -2
  31. package/lib/utils/positioningHelper.js +38 -30
  32. package/lib/utils/positioningHelper.js.map +1 -1
  33. package/lib/utils/resolvePositioningShorthand.js +57 -19
  34. package/lib/utils/resolvePositioningShorthand.js.map +1 -1
  35. package/lib/utils/useCallbackRef.js +35 -29
  36. package/lib/utils/useCallbackRef.js.map +1 -1
  37. package/lib-commonjs/createArrowStyles.d.ts +64 -0
  38. package/lib-commonjs/createArrowStyles.js +100 -0
  39. package/lib-commonjs/createArrowStyles.js.map +1 -0
  40. package/lib-commonjs/createVirtualElementFromClick.js +23 -16
  41. package/lib-commonjs/createVirtualElementFromClick.js.map +1 -1
  42. package/lib-commonjs/index.d.ts +2 -1
  43. package/lib-commonjs/index.js +28 -6
  44. package/lib-commonjs/index.js.map +1 -1
  45. package/lib-commonjs/types.d.ts +28 -7
  46. package/lib-commonjs/types.js +4 -1
  47. package/lib-commonjs/types.js.map +1 -1
  48. package/lib-commonjs/usePopper.d.ts +2 -14
  49. package/lib-commonjs/usePopper.js +382 -316
  50. package/lib-commonjs/usePopper.js.map +1 -1
  51. package/lib-commonjs/usePopperMouseTarget.js +38 -25
  52. package/lib-commonjs/usePopperMouseTarget.js.map +1 -1
  53. package/lib-commonjs/utils/getBasePlacement.js +7 -2
  54. package/lib-commonjs/utils/getBasePlacement.js.map +1 -1
  55. package/lib-commonjs/utils/getBoundary.js +23 -12
  56. package/lib-commonjs/utils/getBoundary.js.map +1 -1
  57. package/lib-commonjs/utils/getReactFiberFromNode.js +44 -36
  58. package/lib-commonjs/utils/getReactFiberFromNode.js.map +1 -1
  59. package/lib-commonjs/utils/getScrollParent.js +53 -33
  60. package/lib-commonjs/utils/getScrollParent.js.map +1 -1
  61. package/lib-commonjs/utils/index.js +14 -2
  62. package/lib-commonjs/utils/index.js.map +1 -1
  63. package/lib-commonjs/utils/mergeArrowOffset.js +35 -25
  64. package/lib-commonjs/utils/mergeArrowOffset.js.map +1 -1
  65. package/lib-commonjs/utils/positioningHelper.d.ts +2 -2
  66. package/lib-commonjs/utils/positioningHelper.js +46 -31
  67. package/lib-commonjs/utils/positioningHelper.js.map +1 -1
  68. package/lib-commonjs/utils/resolvePositioningShorthand.js +65 -22
  69. package/lib-commonjs/utils/resolvePositioningShorthand.js.map +1 -1
  70. package/lib-commonjs/utils/useCallbackRef.js +45 -32
  71. package/lib-commonjs/utils/useCallbackRef.js.map +1 -1
  72. package/package.json +7 -8
package/lib/usePopper.js CHANGED
@@ -1,29 +1,31 @@
1
1
  import { useEventCallback, useIsomorphicLayoutEffect, useFirstMount, canUseDOM } from '@fluentui/react-utilities';
2
2
  import { useFluent } from '@fluentui/react-shared-contexts';
3
- import { getScrollParent, applyRtlToOffset, getPlacement, getReactFiberFromNode, getBoundary, useCallbackRef, getBasePlacement, } from './utils/index';
4
3
  import * as PopperJs from '@popperjs/core';
5
4
  import * as React from 'react';
6
- //
5
+ import { getScrollParent, applyRtlToOffset, getPlacement, getReactFiberFromNode, getBoundary, useCallbackRef, getBasePlacement } from './utils/index'; //
7
6
  // Dev utils to detect if nodes have "autoFocus" props.
8
7
  //
8
+
9
9
  /**
10
10
  * Detects if a passed HTML node has "autoFocus" prop on a React's fiber. Is needed as React handles autofocus behavior
11
11
  * in React DOM and will not pass "autoFocus" to an actual HTML.
12
12
  */
13
+
13
14
  function hasAutofocusProp(node) {
14
- var _a;
15
- // https://github.com/facebook/react/blob/848bb2426e44606e0a55dfe44c7b3ece33772485/packages/react-dom/src/client/ReactDOMHostConfig.js#L157-L166
16
- const isAutoFocusableElement = node.nodeName === 'BUTTON' ||
17
- node.nodeName === 'INPUT' ||
18
- node.nodeName === 'SELECT' ||
19
- node.nodeName === 'TEXTAREA';
20
- if (isAutoFocusableElement) {
21
- return !!((_a = getReactFiberFromNode(node)) === null || _a === void 0 ? void 0 : _a.pendingProps.autoFocus);
22
- }
23
- return false;
15
+ var _a; // https://github.com/facebook/react/blob/848bb2426e44606e0a55dfe44c7b3ece33772485/packages/react-dom/src/client/ReactDOMHostConfig.js#L157-L166
16
+
17
+
18
+ const isAutoFocusableElement = node.nodeName === 'BUTTON' || node.nodeName === 'INPUT' || node.nodeName === 'SELECT' || node.nodeName === 'TEXTAREA';
19
+
20
+ if (isAutoFocusableElement) {
21
+ return !!((_a = getReactFiberFromNode(node)) === null || _a === void 0 ? void 0 : _a.pendingProps.autoFocus);
22
+ }
23
+
24
+ return false;
24
25
  }
26
+
25
27
  function hasAutofocusFilter(node) {
26
- return hasAutofocusProp(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
28
+ return hasAutofocusProp(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
27
29
  }
28
30
  /**
29
31
  * Provides a callback to resolve Popper options, it's stable and should be used as a dependency to trigger updates
@@ -32,188 +34,217 @@ function hasAutofocusFilter(node) {
32
34
  * A callback is used there intentionally as some of Popper.js modifiers require DOM nodes (targer, container, arrow)
33
35
  * that can't be resolved properly during an initial rendering.
34
36
  */
37
+
38
+
35
39
  function usePopperOptions(options, popperOriginalPositionRef) {
36
- const { arrowPadding, autoSize, coverTarget, flipBoundary, offset, onStateUpdate, overflowBoundary,
40
+ const {
41
+ align,
42
+ arrowPadding,
43
+ autoSize,
44
+ coverTarget,
45
+ flipBoundary,
46
+ offset,
47
+ overflowBoundary,
48
+ pinned,
49
+ position,
50
+ positionFixed,
37
51
  // eslint-disable-next-line @typescript-eslint/naming-convention
38
- unstable_disableTether, pinned, } = options;
39
- const isRtl = useFluent().dir === 'rtl';
40
- const placement = getPlacement(options.align, options.position, isRtl);
41
- const strategy = options.positionFixed ? 'fixed' : 'absolute';
42
- const handleStateUpdate = useEventCallback(({ state }) => {
43
- if (onStateUpdate) {
44
- onStateUpdate(state);
45
- }
46
- });
47
- const offsetModifier = React.useMemo(() => offset
48
- ? {
49
- name: 'offset',
50
- options: { offset: isRtl ? applyRtlToOffset(offset) : offset },
52
+ unstable_disableTether
53
+ } = options;
54
+ const isRtl = useFluent().dir === 'rtl';
55
+ const placement = getPlacement(align, position, isRtl);
56
+ const strategy = positionFixed ? 'fixed' : 'absolute';
57
+ const offsetModifier = React.useMemo(() => offset ? {
58
+ name: 'offset',
59
+ options: {
60
+ offset: isRtl ? applyRtlToOffset(offset) : offset
61
+ }
62
+ } : null, [offset, isRtl]);
63
+ return React.useCallback((target, container, arrow) => {
64
+ var _a;
65
+
66
+ const scrollParentElement = getScrollParent(container);
67
+ const hasScrollableElement = scrollParentElement ? scrollParentElement !== ((_a = scrollParentElement.ownerDocument) === null || _a === void 0 ? void 0 : _a.body) : false;
68
+ const modifiers = [
69
+ /**
70
+ * We are setting the position to `fixed` in the first effect to prevent scroll jumps in case of the content
71
+ * with managed focus. Modifier sets the position to `fixed` before all other modifier effects. Another part of
72
+ * a patch modifies ".forceUpdate()" directly after a Popper will be created.
73
+ */
74
+ {
75
+ name: 'positionStyleFix',
76
+ enabled: true,
77
+ phase: 'afterWrite',
78
+ effect: ({
79
+ state,
80
+ instance
81
+ }) => {
82
+ // ".isFirstRun" is a part of our patch, on a first evaluation it will "undefined"
83
+ // should be disabled for subsequent runs as it breaks positioning for them
84
+ if (instance.isFirstRun !== false) {
85
+ popperOriginalPositionRef.current = state.elements.popper.style.position;
86
+ state.elements.popper.style.position = 'fixed';
51
87
  }
52
- : null, [offset, isRtl]);
53
- return React.useCallback((target, container, arrow) => {
54
- var _a;
55
- const scrollParentElement = getScrollParent(container);
56
- const hasScrollableElement = scrollParentElement
57
- ? scrollParentElement !== ((_a = scrollParentElement.ownerDocument) === null || _a === void 0 ? void 0 : _a.body)
58
- : false;
59
- const modifiers = [
60
- /**
61
- * We are setting the position to `fixed` in the first effect to prevent scroll jumps in case of the content
62
- * with managed focus. Modifier sets the position to `fixed` before all other modifier effects. Another part of
63
- * a patch modifies ".forceUpdate()" directly after a Popper will be created.
64
- */
65
- {
66
- name: 'positionStyleFix',
67
- enabled: true,
68
- phase: 'afterWrite',
69
- effect: ({ state, instance }) => {
70
- // ".isFirstRun" is a part of our patch, on a first evaluation it will "undefined"
71
- // should be disabled for subsequent runs as it breaks positioning for them
72
- if (instance.isFirstRun !== false) {
73
- popperOriginalPositionRef.current = state.elements.popper.style.position;
74
- state.elements.popper.style.position = 'fixed';
75
- }
76
- return () => undefined;
77
- },
78
- requires: [],
79
- },
80
- { name: 'flip', options: { flipVariations: true } },
81
- /**
82
- * pinned disables the flip modifier by setting flip.enabled to false; this
83
- * disables automatic repositioning of the popper box; it will always be placed according to
84
- * the values of `align` and `position` props, regardless of the size of the component, the
85
- * reference element or the viewport.
86
- */
87
- pinned && { name: 'flip', enabled: false },
88
- /**
89
- * When the popper box is placed in the context of a scrollable element, we need to set
90
- * preventOverflow.escapeWithReference to true and flip.boundariesElement to 'scrollParent'
91
- * (default is 'viewport') so that the popper box will stick with the targetRef when we
92
- * scroll targetRef out of the viewport.
93
- */
94
- hasScrollableElement && { name: 'flip', options: { boundary: 'clippingParents' } },
95
- hasScrollableElement && { name: 'preventOverflow', options: { boundary: 'clippingParents' } },
96
- offsetModifier,
97
- /**
98
- * This modifier is necessary to retain behaviour from popper v1 where untethered poppers are allowed by
99
- * default. i.e. popper is still rendered fully in the viewport even if anchor element is no longer in the
100
- * viewport.
101
- */
102
- unstable_disableTether && {
103
- name: 'preventOverflow',
104
- options: { altAxis: unstable_disableTether === 'all', tether: false },
105
- },
106
- flipBoundary && {
107
- name: 'flip',
108
- options: {
109
- altBoundary: true,
110
- boundary: getBoundary(container, flipBoundary),
111
- },
112
- },
113
- overflowBoundary && {
114
- name: 'preventOverflow',
115
- options: {
116
- altBoundary: true,
117
- boundary: getBoundary(container, overflowBoundary),
118
- },
119
- },
120
- {
121
- name: 'onUpdate',
122
- enabled: true,
123
- phase: 'afterWrite',
124
- fn: handleStateUpdate,
125
- },
126
- {
127
- // Similar code as popper-maxsize-modifier: https://github.com/atomiks/popper.js/blob/master/src/modifiers/maxSize.js
128
- // popper-maxsize-modifier only calculates the max sizes.
129
- // This modifier can apply max sizes always, or apply the max sizes only when overflow is detected
130
- name: 'applyMaxSize',
131
- enabled: !!autoSize,
132
- phase: 'beforeWrite',
133
- requiresIfExists: ['offset', 'preventOverflow', 'flip'],
134
- options: {
135
- altBoundary: true,
136
- boundary: getBoundary(container, overflowBoundary),
137
- },
138
- fn({ state, options: modifierOptions }) {
139
- const overflow = PopperJs.detectOverflow(state, modifierOptions);
140
- const { x, y } = state.modifiersData.preventOverflow || { x: 0, y: 0 };
141
- const { width, height } = state.rects.popper;
142
- const basePlacement = getBasePlacement(state.placement);
143
- const widthProp = basePlacement === 'left' ? 'left' : 'right';
144
- const heightProp = basePlacement === 'top' ? 'top' : 'bottom';
145
- const applyMaxWidth = autoSize === 'always' ||
146
- autoSize === 'width-always' ||
147
- (overflow[widthProp] > 0 && (autoSize === true || autoSize === 'width'));
148
- const applyMaxHeight = autoSize === 'always' ||
149
- autoSize === 'height-always' ||
150
- (overflow[heightProp] > 0 && (autoSize === true || autoSize === 'height'));
151
- if (applyMaxWidth) {
152
- state.styles.popper.maxWidth = `${width - overflow[widthProp] - x}px`;
153
- }
154
- if (applyMaxHeight) {
155
- state.styles.popper.maxHeight = `${height - overflow[heightProp] - y}px`;
156
- }
157
- },
158
- },
159
- /**
160
- * This modifier is necessary in order to render the pointer. Refs are resolved in effects, so it can't be
161
- * placed under computed modifiers. Deep merge is not required as this modifier has only these properties.
162
- */
163
- {
164
- name: 'arrow',
165
- enabled: !!arrow,
166
- options: { element: arrow, padding: arrowPadding },
167
- },
168
- /**
169
- * Modifies popper offsets to cover the reference rect, but still keep edge alignment
170
- */
171
- {
172
- name: 'coverTarget',
173
- enabled: !!coverTarget,
174
- phase: 'main',
175
- requiresIfExists: ['offset', 'preventOverflow', 'flip'],
176
- fn({ state }) {
177
- const basePlacement = getBasePlacement(state.placement);
178
- switch (basePlacement) {
179
- case 'bottom':
180
- state.modifiersData.popperOffsets.y -= state.rects.reference.height;
181
- break;
182
- case 'top':
183
- state.modifiersData.popperOffsets.y += state.rects.reference.height;
184
- break;
185
- case 'left':
186
- state.modifiersData.popperOffsets.x += state.rects.reference.width;
187
- break;
188
- case 'right':
189
- state.modifiersData.popperOffsets.x -= state.rects.reference.width;
190
- break;
191
- }
192
- },
193
- },
194
- ].filter(Boolean); // filter boolean conditional spreading values
195
- const popperOptions = {
196
- modifiers,
197
- placement,
198
- strategy,
199
- onFirstUpdate: state => handleStateUpdate({ state }),
88
+
89
+ return () => undefined;
90
+ },
91
+ requires: []
92
+ }, {
93
+ name: 'flip',
94
+ options: {
95
+ flipVariations: true
96
+ }
97
+ },
98
+ /**
99
+ * pinned disables the flip modifier by setting flip.enabled to false; this
100
+ * disables automatic repositioning of the popper box; it will always be placed according to
101
+ * the values of `align` and `position` props, regardless of the size of the component, the
102
+ * reference element or the viewport.
103
+ */
104
+ pinned && {
105
+ name: 'flip',
106
+ enabled: false
107
+ },
108
+ /**
109
+ * When the popper box is placed in the context of a scrollable element, we need to set
110
+ * preventOverflow.escapeWithReference to true and flip.boundariesElement to 'scrollParent'
111
+ * (default is 'viewport') so that the popper box will stick with the targetRef when we
112
+ * scroll targetRef out of the viewport.
113
+ */
114
+ hasScrollableElement && {
115
+ name: 'flip',
116
+ options: {
117
+ boundary: 'clippingParents'
118
+ }
119
+ }, hasScrollableElement && {
120
+ name: 'preventOverflow',
121
+ options: {
122
+ boundary: 'clippingParents'
123
+ }
124
+ }, offsetModifier,
125
+ /**
126
+ * This modifier is necessary to retain behaviour from popper v1 where untethered poppers are allowed by
127
+ * default. i.e. popper is still rendered fully in the viewport even if anchor element is no longer in the
128
+ * viewport.
129
+ */
130
+ unstable_disableTether && {
131
+ name: 'preventOverflow',
132
+ options: {
133
+ altAxis: unstable_disableTether === 'all',
134
+ tether: false
135
+ }
136
+ }, flipBoundary && {
137
+ name: 'flip',
138
+ options: {
139
+ altBoundary: true,
140
+ boundary: getBoundary(container, flipBoundary)
141
+ }
142
+ }, overflowBoundary && {
143
+ name: 'preventOverflow',
144
+ options: {
145
+ altBoundary: true,
146
+ boundary: getBoundary(container, overflowBoundary)
147
+ }
148
+ }, {
149
+ // Similar code as popper-maxsize-modifier: https://github.com/atomiks/popper.js/blob/master/src/modifiers/maxSize.js
150
+ // popper-maxsize-modifier only calculates the max sizes.
151
+ // This modifier can apply max sizes always, or apply the max sizes only when overflow is detected
152
+ name: 'applyMaxSize',
153
+ enabled: !!autoSize,
154
+ phase: 'beforeWrite',
155
+ requiresIfExists: ['offset', 'preventOverflow', 'flip'],
156
+ options: {
157
+ altBoundary: true,
158
+ boundary: getBoundary(container, overflowBoundary)
159
+ },
160
+
161
+ fn({
162
+ state,
163
+ options: modifierOptions
164
+ }) {
165
+ const overflow = PopperJs.detectOverflow(state, modifierOptions);
166
+ const {
167
+ x,
168
+ y
169
+ } = state.modifiersData.preventOverflow || {
170
+ x: 0,
171
+ y: 0
200
172
  };
201
- return popperOptions;
202
- }, [
203
- arrowPadding,
204
- autoSize,
205
- coverTarget,
206
- flipBoundary,
207
- offsetModifier,
208
- overflowBoundary,
209
- placement,
210
- strategy,
211
- unstable_disableTether,
212
- pinned,
213
- // These can be skipped from deps as they will not ever change
214
- handleStateUpdate,
215
- popperOriginalPositionRef,
216
- ]);
173
+ const {
174
+ width,
175
+ height
176
+ } = state.rects.popper;
177
+ const basePlacement = getBasePlacement(state.placement);
178
+ const widthProp = basePlacement === 'left' ? 'left' : 'right';
179
+ const heightProp = basePlacement === 'top' ? 'top' : 'bottom';
180
+ const applyMaxWidth = autoSize === 'always' || autoSize === 'width-always' || overflow[widthProp] > 0 && (autoSize === true || autoSize === 'width');
181
+ const applyMaxHeight = autoSize === 'always' || autoSize === 'height-always' || overflow[heightProp] > 0 && (autoSize === true || autoSize === 'height');
182
+
183
+ if (applyMaxWidth) {
184
+ state.styles.popper.maxWidth = `${width - overflow[widthProp] - x}px`;
185
+ }
186
+
187
+ if (applyMaxHeight) {
188
+ state.styles.popper.maxHeight = `${height - overflow[heightProp] - y}px`;
189
+ }
190
+ }
191
+
192
+ },
193
+ /**
194
+ * This modifier is necessary in order to render the pointer. Refs are resolved in effects, so it can't be
195
+ * placed under computed modifiers. Deep merge is not required as this modifier has only these properties.
196
+ */
197
+ {
198
+ name: 'arrow',
199
+ enabled: !!arrow,
200
+ options: {
201
+ element: arrow,
202
+ padding: arrowPadding
203
+ }
204
+ },
205
+ /**
206
+ * Modifies popper offsets to cover the reference rect, but still keep edge alignment
207
+ */
208
+ {
209
+ name: 'coverTarget',
210
+ enabled: !!coverTarget,
211
+ phase: 'main',
212
+ requiresIfExists: ['offset', 'preventOverflow', 'flip'],
213
+
214
+ fn({
215
+ state
216
+ }) {
217
+ const basePlacement = getBasePlacement(state.placement);
218
+
219
+ switch (basePlacement) {
220
+ case 'bottom':
221
+ state.modifiersData.popperOffsets.y -= state.rects.reference.height;
222
+ break;
223
+
224
+ case 'top':
225
+ state.modifiersData.popperOffsets.y += state.rects.reference.height;
226
+ break;
227
+
228
+ case 'left':
229
+ state.modifiersData.popperOffsets.x += state.rects.reference.width;
230
+ break;
231
+
232
+ case 'right':
233
+ state.modifiersData.popperOffsets.x -= state.rects.reference.width;
234
+ break;
235
+ }
236
+ }
237
+
238
+ }].filter(Boolean); // filter boolean conditional spreading values
239
+
240
+ const popperOptions = {
241
+ modifiers,
242
+ placement,
243
+ strategy
244
+ };
245
+ return popperOptions;
246
+ }, [arrowPadding, autoSize, coverTarget, flipBoundary, offsetModifier, overflowBoundary, placement, strategy, unstable_disableTether, pinned, // These can be skipped from deps as they will not ever change
247
+ popperOriginalPositionRef]);
217
248
  }
218
249
  /**
219
250
  * Exposes Popper positioning API via React hook. Contains few important differences between an official "react-popper"
@@ -223,128 +254,153 @@ function usePopperOptions(options, popperOriginalPositionRef) {
223
254
  * - contains a specific to React fix related to initial positioning when containers have components with managed focus
224
255
  * to avoid focus jumps
225
256
  */
257
+
258
+
226
259
  export function usePopper(options = {}) {
227
- const { enabled = true } = options;
228
- const isFirstMount = useFirstMount();
229
- const popperOriginalPositionRef = React.useRef('absolute');
230
- const resolvePopperOptions = usePopperOptions(options, popperOriginalPositionRef);
231
- const popperInstanceRef = React.useRef(null);
232
- const handlePopperUpdate = useEventCallback(() => {
233
- var _a;
234
- (_a = popperInstanceRef.current) === null || _a === void 0 ? void 0 : _a.destroy();
235
- popperInstanceRef.current = null;
236
- const { target = targetRef.current } = options;
237
- let popperInstance = null;
238
- if (canUseDOM() && enabled) {
239
- if (target && containerRef.current) {
240
- popperInstance = PopperJs.createPopper(target, containerRef.current, resolvePopperOptions(target, containerRef.current, arrowRef.current));
241
- }
242
- }
243
- if (popperInstance) {
244
- /**
245
- * The patch updates `.forceUpdate()` Popper function which restores the original position before the first
246
- * forceUpdate() call. See also "positionStyleFix" modifier in usePopperOptions().
247
- */
248
- const originalForceUpdate = popperInstance.forceUpdate;
249
- popperInstance.isFirstRun = true;
250
- popperInstance.forceUpdate = () => {
251
- if (popperInstance === null || popperInstance === void 0 ? void 0 : popperInstance.isFirstRun) {
252
- popperInstance.state.elements.popper.style.position = popperOriginalPositionRef.current;
253
- popperInstance.isFirstRun = false;
254
- }
255
- originalForceUpdate();
256
- };
257
- }
258
- popperInstanceRef.current = popperInstance;
259
- });
260
- // Refs are managed by useCallbackRef() to handle ref updates scenarios.
261
- //
262
- // The first scenario are updates for a targetRef, we can handle it properly only via callback refs, but it causes
263
- // re-renders (we would like to avoid them).
264
- //
265
- // The second problem is related to refs resolution on React's layer: refs are resolved in the same order as effects
266
- // that causes an issue when you have a container inside a target, for example: a menu in ChatMessage.
267
- //
268
- // function ChatMessage(props) {
269
- // <div className="message" ref={targetRef}> // 3) ref will be resolved only now, but it's too late already
270
- // <Popper target={targetRef}> // 2) create a popper instance
271
- // <div className="menu" /> // 1) capture ref from this element
272
- // </Popper>
273
- // </div>
274
- // }
275
- //
276
- // Check a demo on CodeSandbox: https://codesandbox.io/s/popper-refs-emy60.
277
- //
278
- // This again can be solved with callback refs. It's not a huge issue as with hooks we are moving popper's creation
279
- // to ChatMessage itself, however, without `useCallback()` refs it's still a Pandora box.
280
- const targetRef = useCallbackRef(null, handlePopperUpdate, true);
281
- const containerRef = useCallbackRef(null, handlePopperUpdate, true);
282
- const arrowRef = useCallbackRef(null, handlePopperUpdate, true);
283
- React.useImperativeHandle(options.popperRef, () => ({
284
- updatePosition: () => {
285
- var _a;
286
- (_a = popperInstanceRef.current) === null || _a === void 0 ? void 0 : _a.update();
287
- },
288
- }), []);
289
- useIsomorphicLayoutEffect(() => {
290
- handlePopperUpdate();
291
- return () => {
292
- var _a;
293
- (_a = popperInstanceRef.current) === null || _a === void 0 ? void 0 : _a.destroy();
294
- popperInstanceRef.current = null;
295
- };
296
- }, [handlePopperUpdate, options.enabled, options.target]);
297
- useIsomorphicLayoutEffect(() => {
298
- var _a;
299
- if (!isFirstMount) {
300
- (_a = popperInstanceRef.current) === null || _a === void 0 ? void 0 : _a.setOptions(resolvePopperOptions(options.target || targetRef.current, containerRef.current, arrowRef.current));
260
+ const {
261
+ enabled = true
262
+ } = options;
263
+ const isFirstMount = useFirstMount();
264
+ const popperOriginalPositionRef = React.useRef('absolute');
265
+ const resolvePopperOptions = usePopperOptions(options, popperOriginalPositionRef);
266
+ const popperInstanceRef = React.useRef(null);
267
+ const handlePopperUpdate = useEventCallback(() => {
268
+ var _a, _b;
269
+
270
+ (_a = popperInstanceRef.current) === null || _a === void 0 ? void 0 : _a.destroy();
271
+ popperInstanceRef.current = null;
272
+ const target = (_b = overrideTargetRef.current) !== null && _b !== void 0 ? _b : targetRef.current;
273
+ let popperInstance = null;
274
+
275
+ if (canUseDOM() && enabled) {
276
+ if (target && containerRef.current) {
277
+ popperInstance = PopperJs.createPopper(target, containerRef.current, resolvePopperOptions(target, containerRef.current, arrowRef.current));
278
+ }
279
+ }
280
+
281
+ if (popperInstance) {
282
+ /**
283
+ * The patch updates `.forceUpdate()` Popper function which restores the original position before the first
284
+ * forceUpdate() call. See also "positionStyleFix" modifier in usePopperOptions().
285
+ */
286
+ const originalForceUpdate = popperInstance.forceUpdate;
287
+ popperInstance.isFirstRun = true;
288
+
289
+ popperInstance.forceUpdate = () => {
290
+ if (popperInstance === null || popperInstance === void 0 ? void 0 : popperInstance.isFirstRun) {
291
+ popperInstance.state.elements.popper.style.position = popperOriginalPositionRef.current;
292
+ popperInstance.isFirstRun = false;
301
293
  }
302
- },
303
- // Missing deps:
304
- // options.target - The useIsomorphicLayoutEffect before this will create a new popper instance if target changes
305
- // isFirstMount - Should never change after mount
306
- // arrowRef, containerRef, targetRef - Stable between renders
307
- // eslint-disable-next-line react-hooks/exhaustive-deps
308
- [resolvePopperOptions]);
309
- if (process.env.NODE_ENV !== 'production') {
310
- // This checked should run only in development mode
311
- // eslint-disable-next-line react-hooks/rules-of-hooks
312
- React.useEffect(() => {
313
- var _a;
314
- if (containerRef.current) {
315
- const contentNode = containerRef.current;
316
- const treeWalker = (_a = contentNode.ownerDocument) === null || _a === void 0 ? void 0 : _a.createTreeWalker(contentNode, NodeFilter.SHOW_ELEMENT, {
317
- acceptNode: hasAutofocusFilter,
318
- });
319
- while (treeWalker === null || treeWalker === void 0 ? void 0 : treeWalker.nextNode()) {
320
- const node = treeWalker.currentNode;
321
- // eslint-disable-next-line no-console
322
- console.warn('<Popper>:', node);
323
- // eslint-disable-next-line no-console
324
- console.warn([
325
- '<Popper>: ^ this node contains "autoFocus" prop on a React element. This can break the initial',
326
- 'positioning of an element and cause a window jump effect. This issue occurs because React polyfills',
327
- '"autoFocus" behavior to solve inconsistencies between different browsers:',
328
- 'https://github.com/facebook/react/issues/11851#issuecomment-351787078',
329
- '\n',
330
- 'However, ".focus()" in this case occurs before any other React effects will be executed',
331
- '(React.useEffect(), componentDidMount(), etc.) and we can not prevent this behavior. If you really',
332
- 'want to use "autoFocus" please add "position: fixed" to styles of the element that is wrapped by',
333
- '"Popper".',
334
- `In general, it's not recommended to use "autoFocus" as it may break accessibility aspects:`,
335
- 'https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-autofocus.md',
336
- '\n',
337
- 'We suggest to use the "trapFocus" prop on Fluent components or a catch "ref" and then use',
338
- '"ref.current.focus" in React.useEffect():',
339
- 'https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element',
340
- ].join(' '));
341
- }
342
- }
343
- // We run this check once, no need to add deps here
344
- // TODO: Should be rework to handle options.enabled and contentRef updates
345
- // eslint-disable-next-line react-hooks/exhaustive-deps
346
- }, []);
294
+
295
+ originalForceUpdate();
296
+ };
347
297
  }
348
- return { targetRef, containerRef, arrowRef };
298
+
299
+ popperInstanceRef.current = popperInstance;
300
+ }); // Refs are managed by useCallbackRef() to handle ref updates scenarios.
301
+ //
302
+ // The first scenario are updates for a targetRef, we can handle it properly only via callback refs, but it causes
303
+ // re-renders (we would like to avoid them).
304
+ //
305
+ // The second problem is related to refs resolution on React's layer: refs are resolved in the same order as effects
306
+ // that causes an issue when you have a container inside a target, for example: a menu in ChatMessage.
307
+ //
308
+ // function ChatMessage(props) {
309
+ // <div className="message" ref={targetRef}> // 3) ref will be resolved only now, but it's too late already
310
+ // <Popper target={targetRef}> // 2) create a popper instance
311
+ // <div className="menu" /> // 1) capture ref from this element
312
+ // </Popper>
313
+ // </div>
314
+ // }
315
+ //
316
+ // Check a demo on CodeSandbox: https://codesandbox.io/s/popper-refs-emy60.
317
+ //
318
+ // This again can be solved with callback refs. It's not a huge issue as with hooks we are moving popper's creation
319
+ // to ChatMessage itself, however, without `useCallback()` refs it's still a Pandora box.
320
+
321
+ const targetRef = useCallbackRef(null, handlePopperUpdate, true);
322
+ const containerRef = useCallbackRef(null, handlePopperUpdate, true);
323
+ const arrowRef = useCallbackRef(null, handlePopperUpdate, true); // Stores external target from options.target or setTarget
324
+
325
+ const overrideTargetRef = useCallbackRef(null, handlePopperUpdate, true);
326
+ React.useImperativeHandle(options.popperRef, () => ({
327
+ updatePosition: () => {
328
+ var _a;
329
+
330
+ (_a = popperInstanceRef.current) === null || _a === void 0 ? void 0 : _a.update();
331
+ },
332
+ setTarget: target => {
333
+ if (options.target && process.env.NODE_ENV !== 'production') {
334
+ const err = new Error(); // eslint-disable-next-line no-console
335
+
336
+ console.warn('Imperative setTarget should not be used at the same time as target option'); // eslint-disable-next-line no-console
337
+
338
+ console.warn(err.stack);
339
+ }
340
+
341
+ overrideTargetRef.current = target;
342
+ }
343
+ }), // Missing deps:
344
+ // options.target - only used for a runtime warning
345
+ // targetRef - Stable between renders
346
+ // eslint-disable-next-line react-hooks/exhaustive-deps
347
+ []);
348
+ useIsomorphicLayoutEffect(() => {
349
+ if (options.target) {
350
+ overrideTargetRef.current = options.target;
351
+ }
352
+ }, [options.target, overrideTargetRef]);
353
+ useIsomorphicLayoutEffect(() => {
354
+ handlePopperUpdate();
355
+ return () => {
356
+ var _a;
357
+
358
+ (_a = popperInstanceRef.current) === null || _a === void 0 ? void 0 : _a.destroy();
359
+ popperInstanceRef.current = null;
360
+ };
361
+ }, [handlePopperUpdate, options.enabled]);
362
+ useIsomorphicLayoutEffect(() => {
363
+ var _a, _b;
364
+
365
+ if (!isFirstMount) {
366
+ (_a = popperInstanceRef.current) === null || _a === void 0 ? void 0 : _a.setOptions(resolvePopperOptions((_b = overrideTargetRef.current) !== null && _b !== void 0 ? _b : targetRef.current, containerRef.current, arrowRef.current));
367
+ }
368
+ }, // Missing deps:
369
+ // isFirstMount - Should never change after mount
370
+ // arrowRef, containerRef, targetRef - Stable between renders
371
+ // eslint-disable-next-line react-hooks/exhaustive-deps
372
+ [resolvePopperOptions]);
373
+
374
+ if (process.env.NODE_ENV !== 'production') {
375
+ // This checked should run only in development mode
376
+ // eslint-disable-next-line react-hooks/rules-of-hooks
377
+ React.useEffect(() => {
378
+ var _a;
379
+
380
+ if (containerRef.current) {
381
+ const contentNode = containerRef.current;
382
+ const treeWalker = (_a = contentNode.ownerDocument) === null || _a === void 0 ? void 0 : _a.createTreeWalker(contentNode, NodeFilter.SHOW_ELEMENT, {
383
+ acceptNode: hasAutofocusFilter
384
+ });
385
+
386
+ while (treeWalker === null || treeWalker === void 0 ? void 0 : treeWalker.nextNode()) {
387
+ const node = treeWalker.currentNode; // eslint-disable-next-line no-console
388
+
389
+ console.warn('<Popper>:', node); // eslint-disable-next-line no-console
390
+
391
+ console.warn(['<Popper>: ^ this node contains "autoFocus" prop on a React element. This can break the initial', 'positioning of an element and cause a window jump effect. This issue occurs because React polyfills', '"autoFocus" behavior to solve inconsistencies between different browsers:', 'https://github.com/facebook/react/issues/11851#issuecomment-351787078', '\n', 'However, ".focus()" in this case occurs before any other React effects will be executed', '(React.useEffect(), componentDidMount(), etc.) and we can not prevent this behavior. If you really', 'want to use "autoFocus" please add "position: fixed" to styles of the element that is wrapped by', '"Popper".', `In general, it's not recommended to use "autoFocus" as it may break accessibility aspects:`, 'https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-autofocus.md', '\n', 'We suggest to use the "trapFocus" prop on Fluent components or a catch "ref" and then use', '"ref.current.focus" in React.useEffect():', 'https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element'].join(' '));
392
+ }
393
+ } // We run this check once, no need to add deps here
394
+ // TODO: Should be rework to handle options.enabled and contentRef updates
395
+ // eslint-disable-next-line react-hooks/exhaustive-deps
396
+
397
+ }, []);
398
+ }
399
+
400
+ return {
401
+ targetRef,
402
+ containerRef,
403
+ arrowRef
404
+ };
349
405
  }
350
406
  //# sourceMappingURL=usePopper.js.map