-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Popup.js
445 lines (372 loc) · 12.1 KB
/
Popup.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import cx from 'clsx'
import _ from 'lodash'
import PropTypes from 'prop-types'
import * as React from 'react'
import { Popper } from 'react-popper'
import shallowEqual from 'shallowequal'
import {
childrenUtils,
createHTMLDivision,
customPropTypes,
getComponentType,
getUnhandledProps,
makeDebugger,
SUI,
useIsomorphicLayoutEffect,
getKeyOnly,
getKeyOrValueAndKey,
useMergedRefs,
usePrevious,
} from '../../lib'
import Portal from '../../addons/Portal'
import { placementMapping, positions, positionsMapping } from './lib/positions'
import createReferenceProxy from './lib/createReferenceProxy'
import PopupContent from './PopupContent'
import PopupHeader from './PopupHeader'
const debug = makeDebugger('popup')
/**
* Calculates props specific for Portal component.
*
* @param {Object} props
*/
function getPortalProps(props) {
const portalProps = {}
const on = props.on ?? ['click', 'hover']
const normalizedOn = _.isArray(on) ? on : [on]
if (props.hoverable) {
portalProps.closeOnPortalMouseLeave = true
portalProps.mouseLeaveDelay = 300
}
if (_.includes(normalizedOn, 'hover')) {
portalProps.openOnTriggerClick = false
portalProps.closeOnTriggerClick = false
portalProps.openOnTriggerMouseEnter = true
portalProps.closeOnTriggerMouseLeave = true
// Taken from SUI: https://git.io/vPmCm
portalProps.mouseLeaveDelay = 70
portalProps.mouseEnterDelay = 50
}
if (_.includes(normalizedOn, 'click')) {
portalProps.openOnTriggerClick = true
portalProps.closeOnTriggerClick = true
portalProps.closeOnDocumentClick = true
}
if (_.includes(normalizedOn, 'focus')) {
portalProps.openOnTriggerFocus = true
portalProps.closeOnTriggerBlur = true
}
return portalProps
}
/**
* Splits props for Portal & Popup.
*
* @param {Object} unhandledProps
* @param {Boolean} disabled
*/
function partitionPortalProps(unhandledProps, disabled) {
if (disabled) {
return {}
}
const contentRestProps = _.reduce(
unhandledProps,
(acc, val, key) => {
if (!_.includes(Portal.handledProps, key)) acc[key] = val
return acc
},
{},
)
const portalRestProps = _.pick(unhandledProps, Portal.handledProps)
return { contentRestProps, portalRestProps }
}
/**
* Performs updates when "popperDependencies" are not shallow equal.
*
* @param {Array} popperDependencies
* @param {React.Ref} positionUpdate
*/
function usePositioningEffect(popperDependencies, positionUpdate) {
const previousDependencies = usePrevious(popperDependencies)
useIsomorphicLayoutEffect(() => {
if (positionUpdate.current) {
positionUpdate.current()
}
}, [shallowEqual(previousDependencies, popperDependencies)])
}
/**
* A Popup displays additional information on top of a page.
*/
const Popup = React.forwardRef(function (props, ref) {
const {
basic,
className,
content,
context,
children,
disabled = false,
eventsEnabled = true,
flowing,
header,
hideOnScroll = false,
inverted,
offset,
pinned = false,
popper,
popperDependencies,
popperModifiers = [],
position = 'top left',
positionFixed,
size,
style,
trigger,
wide,
} = props
const unhandledProps = getUnhandledProps(Popup, props)
const { contentRestProps, portalRestProps } = partitionPortalProps(unhandledProps, disabled)
const elementRef = useMergedRefs(ref)
const positionUpdate = React.useRef()
const triggerRef = React.useRef()
const zIndexWasSynced = React.useRef(false)
// ----------------------------------------
// Effects
// ----------------------------------------
usePositioningEffect(popperDependencies, positionUpdate)
// ----------------------------------------
// Handlers
// ----------------------------------------
const handleClose = (e) => {
debug('handleClose()')
_.invoke(props, 'onClose', e, { ...props, open: false })
}
const handleOpen = (e) => {
debug('handleOpen()')
_.invoke(props, 'onOpen', e, { ...props, open: true })
}
const handlePortalMount = (e) => {
debug('handlePortalMount()')
_.invoke(props, 'onMount', e, props)
}
const handlePortalUnmount = (e) => {
debug('handlePortalUnmount()')
positionUpdate.current = null
_.invoke(props, 'onUnmount', e, props)
}
// ----------------------------------------
// Render
// ----------------------------------------
const renderBody = ({
placement: popperPlacement,
ref: popperRef,
update,
style: popperStyle,
}) => {
positionUpdate.current = update
const classes = cx(
'ui',
placementMapping[popperPlacement],
size,
getKeyOrValueAndKey(wide, 'wide'),
getKeyOnly(basic, 'basic'),
getKeyOnly(flowing, 'flowing'),
getKeyOnly(inverted, 'inverted'),
'popup transition visible',
className,
)
const ElementType = getComponentType(props)
const styles = {
// Heads up! We need default styles to get working correctly `flowing`
left: 'auto',
right: 'auto',
// This is required to be properly positioned inside wrapping `div`
position: 'initial',
...style,
}
const innerElement = (
<ElementType {...contentRestProps} className={classes} style={styles} ref={elementRef}>
{childrenUtils.isNil(children) ? (
<>
{PopupHeader.create(header, { autoGenerateKey: false })}
{PopupContent.create(content, { autoGenerateKey: false })}
</>
) : (
children
)}
</ElementType>
)
// https://github.com/popperjs/popper-core/blob/f1f9d1ab75b6b0e962f90a5b2a50f6cfd307d794/src/createPopper.js#L136-L137
// Heads up!
// A wrapping `div` there is a pure magic, it's required as Popper warns on margins that are
// defined by SUI CSS. It also means that this `div` will be positioned instead of `content`.
return createHTMLDivision(popper || {}, {
overrideProps: {
children: innerElement,
ref: popperRef,
style: {
// Fixes layout for floated elements
// https://github.com/Semantic-Org/Semantic-UI-React/issues/4092
display: 'flex',
...popperStyle,
},
},
})
}
if (disabled) {
return trigger
}
const modifiers = [
{ name: 'arrow', enabled: false },
{ name: 'eventListeners', options: { scroll: !!eventsEnabled, resize: !!eventsEnabled } },
{ name: 'flip', enabled: !pinned },
{ name: 'preventOverflow', enabled: !!offset },
{ name: 'offset', enabled: !!offset, options: { offset } },
...popperModifiers,
// We are syncing zIndex from `.ui.popup.content` to avoid layering issues as in SUIR we are using an additional
// `div` for Popper.js
// https://github.com/Semantic-Org/Semantic-UI-React/issues/4083
{
name: 'syncZIndex',
enabled: true,
phase: 'beforeRead',
fn: ({ state }) => {
if (zIndexWasSynced.current) {
return
}
// if zIndex defined in <Popup popper={{ style: {} }} /> there is no sense to override it
const definedZIndex = popper?.style?.zIndex
if (_.isUndefined(definedZIndex)) {
// eslint-disable-next-line no-param-reassign
state.elements.popper.style.zIndex = window.getComputedStyle(
state.elements.popper.firstChild,
).zIndex
}
zIndexWasSynced.current = true
},
effect: () => {
return () => {
zIndexWasSynced.current = false
}
},
},
]
debug('popper modifiers:', modifiers)
const referenceElement = createReferenceProxy(_.isNil(context) ? triggerRef : context)
const mergedPortalProps = { ...getPortalProps(props), ...portalRestProps }
debug('portal props:', mergedPortalProps)
return (
<Portal
{...mergedPortalProps}
onClose={handleClose}
onMount={handlePortalMount}
onOpen={handleOpen}
onUnmount={handlePortalUnmount}
trigger={trigger}
triggerRef={triggerRef}
hideOnScroll={hideOnScroll}
>
<Popper
modifiers={modifiers}
placement={positionsMapping[position]}
strategy={positionFixed ? 'fixed' : null}
referenceElement={referenceElement}
>
{renderBody}
</Popper>
</Portal>
)
})
Popup.displayName = 'Popup'
Popup.propTypes = {
/** An element type to render as (string or function). */
as: PropTypes.elementType,
/** Display the popup without the pointing arrow. */
basic: PropTypes.bool,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Simple text content for the popover. */
content: customPropTypes.itemShorthand,
/** Existing element the pop-up should be bound to. */
context: PropTypes.oneOfType([PropTypes.object, customPropTypes.refObject]),
/** A disabled popup only renders its trigger. */
disabled: PropTypes.bool,
/** Enables the Popper.js event listeners. */
eventsEnabled: PropTypes.bool,
/** A flowing Popup has no maximum width and continues to flow to fit its content. */
flowing: PropTypes.bool,
/** Takes up the entire width of its offset container. */
// TODO: implement the Popup fluid layout
// fluid: PropTypes.bool,
/** Header displayed above the content in bold. */
header: customPropTypes.itemShorthand,
/** Hide the Popup when scrolling the window. */
hideOnScroll: PropTypes.bool,
/** Whether the popup should not close on hover. */
hoverable: PropTypes.bool,
/** Invert the colors of the Popup. */
inverted: PropTypes.bool,
/**
* Offset values in px unit to apply to rendered popup. The basic offset accepts an
* array with two numbers in the form [skidding, distance]:
* - `skidding` displaces the Popup along the reference element
* - `distance` displaces the Popup away from, or toward, the reference element in the direction of its placement. A positive number displaces it further away, while a negative number lets it overlap the reference.
*
* @see https://popper.js.org/docs/v2/modifiers/offset/
*/
offset: PropTypes.oneOfType([PropTypes.func, PropTypes.arrayOf(PropTypes.number)]),
/** Events triggering the popup. */
on: PropTypes.oneOfType([
PropTypes.oneOf(['hover', 'click', 'focus']),
PropTypes.arrayOf(PropTypes.oneOf(['hover', 'click', 'focus'])),
]),
/**
* Called when a close event happens.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClose: PropTypes.func,
/**
* Called when the portal is mounted on the DOM.
*
* @param {null}
* @param {object} data - All props.
*/
onMount: PropTypes.func,
/**
* Called when an open event happens.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onOpen: PropTypes.func,
/**
* Called when the portal is unmounted from the DOM.
*
* @param {null}
* @param {object} data - All props.
*/
onUnmount: PropTypes.func,
/** Disables automatic repositioning of the component, it will always be placed according to the position value. */
pinned: PropTypes.bool,
/** Position for the popover. */
position: PropTypes.oneOf(positions),
/** Tells `Popper.js` to use the `position: fixed` strategy to position the popover. */
positionFixed: PropTypes.bool,
/** A wrapping element for an actual content that will be used for positioning. */
popper: customPropTypes.itemShorthand,
/** An array containing custom settings for the Popper.js modifiers. */
popperModifiers: PropTypes.array,
/** A popup can have dependencies which update will schedule a position update. */
popperDependencies: PropTypes.array,
/** Popup size. */
size: PropTypes.oneOf(_.without(SUI.SIZES, 'medium', 'big', 'massive')),
/** Custom Popup style. */
style: PropTypes.object,
/** Element to be rendered in-place where the popup is defined. */
trigger: PropTypes.node,
/** Popup width. */
wide: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(['very'])]),
}
Popup.Content = PopupContent
Popup.Header = PopupHeader
export default Popup