forked from unovue/reka-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopperContent.vue
More file actions
429 lines (385 loc) · 11.1 KB
/
Copy pathPopperContent.vue
File metadata and controls
429 lines (385 loc) · 11.1 KB
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
<script lang="ts">
import type {
Middleware,
Placement,
ReferenceElement,
} from '@floating-ui/vue'
import type { Ref } from 'vue'
import type {
Align,
Side,
} from './utils'
import type { PrimitiveProps } from '@/Primitive'
import type { Direction } from '@/shared/types'
import { createContext, useDirection, useForwardExpose, useSize } from '@/shared'
export const PopperContentPropsDefaultValue = {
side: 'bottom' as Side,
sideOffset: 0,
sideFlip: true,
align: 'center' as Align,
alignOffset: 0,
alignFlip: true,
arrowPadding: 0,
hideShiftedArrow: true,
avoidCollisions: true,
collisionBoundary: () => [],
collisionPadding: 0,
sticky: 'partial' as 'partial' | 'always',
hideWhenDetached: false,
positionStrategy: 'fixed' as 'absolute' | 'fixed',
updatePositionStrategy: 'optimized' as 'optimized' | 'always',
prioritizePosition: false,
}
export interface PopperContentProps extends PrimitiveProps {
/**
* The preferred side of the trigger to render against when open.
* Will be reversed when collisions occur and avoidCollisions
* is enabled.
*
* @defaultValue "bottom"
*/
side?: Side
/**
* The distance in pixels from the trigger.
*
* @defaultValue 0
*/
sideOffset?: number
/**
* Flip to the opposite side when colliding with boundary.
*
* @defaultValue true
*/
sideFlip?: boolean
/**
* The preferred alignment against the trigger.
* May change when collisions occur.
*
* @defaultValue "center"
*/
align?: Align
/**
* An offset in pixels from the `start` or `end` alignment options.
*
* @defaultValue 0
*/
alignOffset?: number
/**
* Flip alignment when colliding with boundary.
* May only occur when `prioritizePosition` is true.
*
* @defaultValue true
*/
alignFlip?: boolean
/**
* When `true`, overrides the side and align preferences
* to prevent collisions with boundary edges.
*
* @defaultValue true
*/
avoidCollisions?: boolean
/**
* The element used as the collision boundary. By default
* this is the viewport, though you can provide additional
* element(s) to be included in this check.
*
* @defaultValue []
*/
collisionBoundary?: Element | null | Array<Element | null>
/**
* The distance in pixels from the boundary edges where collision
* detection should occur. Accepts a number (same for all sides),
* or a partial padding object, for example: { top: 20, left: 20 }.
*
* @defaultValue 0
*/
collisionPadding?: number | Partial<Record<Side, number>>
/**
* The padding between the arrow and the edges of the content.
* If your content has border-radius, this will prevent it from
* overflowing the corners.
*
* @defaultValue 0
*/
arrowPadding?: number
/**
* When `true`, hides the arrow when it cannot be centered
* to the reference element.
*
* @defaultValue true
*/
hideShiftedArrow?: boolean
/**
* The sticky behavior on the align axis. `partial` will keep the
* content in the boundary as long as the trigger is at least partially
* in the boundary whilst "always" will keep the content in the boundary
* regardless.
*
* @defaultValue "partial"
*/
sticky?: 'partial' | 'always'
/**
* Whether to hide the content when the trigger becomes fully occluded.
*
* @defaultValue false
*/
hideWhenDetached?: boolean
/**
* The type of CSS position property to use.
*/
positionStrategy?: 'absolute' | 'fixed'
/**
* Strategy to update the position of the floating element on every animation frame.
*
* @defaultValue 'optimized'
*/
updatePositionStrategy?: 'optimized' | 'always'
/**
* Whether to disable the update position for the content when the layout shifted.
*
* @defaultValue false
*/
disableUpdateOnLayoutShift?: boolean
/**
* Force content to be position within the viewport.
*
* Might overlap the reference element, which may not be desired.
*
* @defaultValue false
*/
prioritizePosition?: boolean
/**
* The custom element or virtual element that will be set as the reference
* to position the floating element.
*
* If provided, it will replace the default anchor element.
*/
reference?: ReferenceElement
/**
* The reading direction of the popper content when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode.
*/
dir?: Direction
}
export interface PopperContentContext {
placedSide: Ref<Side>
onArrowChange: (arrow: HTMLElement | undefined) => void
arrowX?: Ref<number>
arrowY?: Ref<number>
shouldHideArrow: Ref<boolean>
}
export const [injectPopperContentContext, providePopperContentContext]
= createContext<PopperContentContext>('PopperContent')
</script>
<script setup lang="ts">
import {
autoUpdate,
flip,
arrow as floatingUIarrow,
hide,
limitShift,
offset,
shift,
size,
useFloating,
} from '@floating-ui/vue'
import { computedEager } from '@vueuse/core'
import { computed, ref, watchEffect, watchPostEffect } from 'vue'
import {
Primitive,
} from '@/Primitive'
import { injectPopperRootContext } from './PopperRoot.vue'
import {
getSideAndAlignFromPlacement,
isNotNull,
transformOrigin,
} from './utils'
defineOptions({
inheritAttrs: false,
})
const props = withDefaults(defineProps<PopperContentProps>(), {
...PopperContentPropsDefaultValue,
})
const emits = defineEmits<{
placed: [void]
}>()
const rootContext = injectPopperRootContext()
const { forwardRef, currentElement: contentElement } = useForwardExpose()
const dir = useDirection(computed(() => props.dir))
const floatingRef = ref<HTMLElement>()
const arrow = ref<HTMLElement>()
const { width: arrowWidth, height: arrowHeight } = useSize(arrow)
const desiredPlacement = computed(
() =>
(props.side
+ (props.align !== 'center' ? `-${props.align}` : '')) as Placement,
)
const collisionPadding = computed(() => {
return typeof props.collisionPadding === 'number'
? props.collisionPadding
: { top: 0, right: 0, bottom: 0, left: 0, ...props.collisionPadding }
})
const boundary = computed(() => {
return Array.isArray(props.collisionBoundary)
? props.collisionBoundary
: [props.collisionBoundary]
})
const detectOverflowOptions = computed(() => {
return {
padding: collisionPadding.value,
boundary: boundary.value.filter(isNotNull),
// with `strategy: 'fixed'`, this is the only way to get it to respect boundaries
altBoundary: boundary.value.length > 0,
}
})
const flipOptions = computed(() => {
return {
mainAxis: props.sideFlip,
crossAxis: props.alignFlip,
}
})
const computedMiddleware = computedEager(() => {
return [
offset({
mainAxis: props.sideOffset + arrowHeight.value,
alignmentAxis: props.alignOffset,
}),
props.prioritizePosition
&& props.avoidCollisions
&& flip({
...detectOverflowOptions.value,
...flipOptions.value,
}),
props.avoidCollisions
&& shift({
mainAxis: true,
crossAxis: !!props.prioritizePosition,
limiter: props.sticky === 'partial' ? limitShift() : undefined,
...detectOverflowOptions.value,
}),
!props.prioritizePosition
&& props.avoidCollisions
&& flip({
...detectOverflowOptions.value,
...flipOptions.value,
}),
size({
...detectOverflowOptions.value,
apply: ({ elements, rects, availableWidth, availableHeight }) => {
const { width: anchorWidth, height: anchorHeight } = rects.reference
const contentStyle = elements.floating.style
contentStyle.setProperty(
'--reka-popper-available-width',
`${availableWidth}px`,
)
contentStyle.setProperty(
'--reka-popper-available-height',
`${availableHeight}px`,
)
contentStyle.setProperty(
'--reka-popper-anchor-width',
`${anchorWidth}px`,
)
contentStyle.setProperty(
'--reka-popper-anchor-height',
`${anchorHeight}px`,
)
},
}),
arrow.value
&& floatingUIarrow({ element: arrow.value, padding: props.arrowPadding }),
transformOrigin({
arrowWidth: arrowWidth.value,
arrowHeight: arrowHeight.value,
dir: dir.value,
}),
props.hideWhenDetached
&& hide({ strategy: 'referenceHidden', ...detectOverflowOptions.value }),
] as Middleware[]
})
// If provided custom reference, it will overwrite the default anchor element
const reference = computed(() => props.reference ?? rootContext.anchor.value)
const { floatingStyles, placement, isPositioned, middlewareData, update } = useFloating(
reference,
floatingRef,
{
strategy: props.positionStrategy,
placement: desiredPlacement,
whileElementsMounted: (...args) => {
const cleanup = autoUpdate(...args, {
layoutShift: !props.disableUpdateOnLayoutShift,
animationFrame: props.updatePositionStrategy === 'always',
})
return cleanup
},
middleware: computedMiddleware,
},
)
const placedSide = computed(
() => getSideAndAlignFromPlacement(placement.value)[0],
)
const placedAlign = computed(
() => getSideAndAlignFromPlacement(placement.value)[1],
)
watchPostEffect(() => {
if (isPositioned.value)
emits('placed')
})
const shouldHideArrow = computed(() => {
const cannotCenterArrow = middlewareData.value.arrow?.centerOffset !== 0
return props.hideShiftedArrow && cannotCenterArrow
})
const contentZIndex = ref('')
watchEffect(() => {
if (contentElement.value)
contentZIndex.value = window.getComputedStyle(contentElement.value).zIndex
})
const arrowX = computed(() => middlewareData.value.arrow?.x ?? 0)
const arrowY = computed(() => middlewareData.value.arrow?.y ?? 0)
providePopperContentContext({
placedSide,
onArrowChange: element => arrow.value = element,
arrowX,
arrowY,
shouldHideArrow,
})
</script>
<template>
<div
ref="floatingRef"
data-reka-popper-content-wrapper=""
:style="{
...floatingStyles,
transform: isPositioned ? floatingStyles.transform : 'translate(0, -200%)', // keep off the page when measuring
minWidth: 'max-content',
zIndex: contentZIndex,
['--reka-popper-transform-origin' as any]: [
middlewareData.transformOrigin?.x,
middlewareData.transformOrigin?.y,
].join(' '),
// hide the content if using the hide middleware and should be hidden
// set visibility to hidden and disable pointer events so the UI behaves
// as if the PopperContent isn't there at all
...(middlewareData.hide?.referenceHidden && {
visibility: 'hidden',
pointerEvents: 'none',
}),
}"
>
<Primitive
:ref="forwardRef"
v-bind="$attrs"
:as-child="props.asChild"
:as="as"
:data-side="placedSide"
:data-align="placedAlign"
:dir="dir"
:style="{
// if the PopperContent hasn't been placed yet (not all measurements done)
// we prevent animations so that users's animation don't kick in too early referring wrong sides
animation: !isPositioned ? 'none' : undefined,
}"
>
<slot />
</Primitive>
</div>
</template>