@fluentui/react-positioning 0.0.0-nightly9edaf68d4420211116.1 → 0.0.0-nightly9fe22334a320220214.1

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