/
floating.tsx
562 lines (486 loc) · 18.6 KB
/
floating.tsx
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
import {
autoUpdate,
flip as flipMiddleware,
inner as innerMiddleware,
offset as offsetMiddleware,
shift as shiftMiddleware,
size as sizeMiddleware,
useFloating,
useInnerOffset,
useInteractions,
type InnerProps,
type UseFloatingReturn,
} from '@floating-ui/react'
import * as React from 'react'
import { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react'
import { useDisposables } from '../hooks/use-disposables'
import { useEvent } from '../hooks/use-event'
import { useIsoMorphicEffect } from '../hooks/use-iso-morphic-effect'
type Align = 'start' | 'end'
type Placement = 'top' | 'right' | 'bottom' | 'left'
type BaseAnchorProps = {
/**
* The `gap` is the space between the trigger and the panel.
*/
gap: number | string // For `var()` support
/**
* The `offset` is the amount the panel should be nudged from its original position.
*/
offset: number | string // For `var()` support
/**
* The `padding` is the minimum space between the panel and the viewport.
*/
padding: number | string // For `var()` support
}
export type AnchorProps = Partial<
BaseAnchorProps & {
/**
* The `to` value defines which side of the trigger the panel should be placed on and its
* alignment.
*/
to: `${Placement}` | `${Placement} ${Align}`
}
>
export type AnchorPropsWithSelection = Partial<
BaseAnchorProps & {
/**
* The `to` value defines which side of the trigger the panel should be placed on and its
* alignment.
*/
to: `${Placement | 'selection'}` | `${Placement | 'selection'} ${Align}`
}
>
export type InternalFloatingPanelProps = Partial<{
inner: {
listRef: InnerProps['listRef']
index: InnerProps['index']
}
}>
let FloatingContext = createContext<{
styles?: UseFloatingReturn<any>['floatingStyles']
setReference: UseFloatingReturn<any>['refs']['setReference']
setFloating: UseFloatingReturn<any>['refs']['setFloating']
getReferenceProps: ReturnType<typeof useInteractions>['getReferenceProps']
getFloatingProps: ReturnType<typeof useInteractions>['getFloatingProps']
slot: Partial<{
anchor: `${Placement | 'selection'}` | `${Placement | 'selection'} ${Align}`
}>
}>({
styles: undefined,
setReference: () => {},
setFloating: () => {},
getReferenceProps: () => ({}),
getFloatingProps: () => ({}),
slot: {},
})
FloatingContext.displayName = 'FloatingContext'
let PlacementContext = createContext<((value: AnchorPropsWithSelection | null) => void) | null>(
null
)
PlacementContext.displayName = 'PlacementContext'
export function useFloatingReference() {
return useContext(FloatingContext).setReference
}
export function useFloatingReferenceProps() {
return useContext(FloatingContext).getReferenceProps
}
export function useFloatingPanelProps() {
let { getFloatingProps, slot } = useContext(FloatingContext)
return useCallback(
(...args: Parameters<typeof getFloatingProps>) => {
return Object.assign({}, getFloatingProps(...args), {
'data-anchor': slot.anchor,
})
},
[getFloatingProps, slot]
)
}
export function useFloatingPanel(
placement?: AnchorPropsWithSelection & InternalFloatingPanelProps
) {
let updatePlacementConfig = useContext(PlacementContext)
let stablePlacement = useMemo(
() => placement,
[
JSON.stringify(
placement,
typeof HTMLElement !== 'undefined'
? (_, v) => {
if (v instanceof HTMLElement) {
return v.outerHTML
}
return v
}
: undefined
),
]
)
useIsoMorphicEffect(() => {
updatePlacementConfig?.(stablePlacement ?? null)
}, [updatePlacementConfig, stablePlacement])
let context = useContext(FloatingContext)
return useMemo(
() => [context.setFloating, context.styles] as const,
[context.setFloating, context.styles]
)
}
// TODO: Make this a config part of the `config`. Just need to decide on a name.
let MINIMUM_ITEMS_VISIBLE = 4
export function FloatingProvider({
children,
enabled = true,
}: {
children: React.ReactNode
enabled?: boolean
}) {
let [config, setConfig] = useState<
(AnchorPropsWithSelection & InternalFloatingPanelProps) | null
>(null)
let [innerOffset, setInnerOffset] = useState(0)
let overflowRef = useRef(null)
let [floatingEl, setFloatingElement] = useState<HTMLElement | null>(null)
useFixScrollingPixel(floatingEl)
let isEnabled = enabled && config !== null && floatingEl !== null
let {
to: placement = 'bottom',
gap = 0,
offset = 0,
padding = 0,
inner,
} = useResolvedConfig(config, floatingEl)
let [to, align = 'center'] = placement.split(' ') as [Placement | 'selection', Align | 'center']
// Reset
useIsoMorphicEffect(() => {
if (!isEnabled) return
setInnerOffset(0)
}, [isEnabled])
let { refs, floatingStyles, context } = useFloating({
open: isEnabled,
placement:
to === 'selection'
? align === 'center'
? 'bottom'
: `bottom-${align}`
: align === 'center'
? `${to}`
: `${to}-${align}`,
// This component will be used in combination with a `Portal`, which means the floating
// element will be rendered outside of the current DOM tree.
strategy: 'fixed',
// We use the panel in a `Dialog` which is making the page inert, therefore no re-positioning is
// needed when scrolling changes.
transform: false,
middleware: [
// - The `mainAxis` is set to `gap` which defines the gap between the panel and the
// trigger/reference.
// - The `crossAxis` is set to `offset` which nudges the panel from its original position.
//
// When we are showing the panel on top of the selected item, we don't want a gap between the
// reference and the panel, therefore setting the `mainAxis` to `0`.
offsetMiddleware({
mainAxis: to === 'selection' ? 0 : gap,
crossAxis: offset,
}),
// When the panel overflows the viewport, we will try to nudge the panel to the other side to
// ensure it's not clipped. We use the `padding` to define the minimum space between the
// panel and the viewport.
shiftMiddleware({ padding }),
// The `flip` middleware will swap the `placement` of the panel if there is not enough room.
// This is not compatible with the `inner` middleware (which is only enabled when `to` is set
// to "selection").
to !== 'selection' && flipMiddleware(),
// The `inner` middleware will ensure the panel is always fully visible on screen and
// positioned on top of the reference and moved to the currently selected item.
to === 'selection' && inner
? innerMiddleware({
...inner,
padding, // For overflow detection
overflowRef,
offset: innerOffset,
minItemsVisible: MINIMUM_ITEMS_VISIBLE,
referenceOverflowThreshold: padding,
onFallbackChange(fallback) {
if (!fallback) return
let parent = context.elements.floating
if (!parent) return
let scrollPaddingBottom =
parseFloat(getComputedStyle(parent!).scrollPaddingBottom) || 0
// We want at least X visible items, but if there are less than X items in the list,
// we want to show as many as possible.
let missing = Math.min(MINIMUM_ITEMS_VISIBLE, parent.childElementCount)
let elementHeight = 0
let elementAmountVisible = 0
for (let child of context.elements.floating?.childNodes ?? []) {
if (child instanceof HTMLElement) {
let childTop = child.offsetTop
// It can be that the child is fully visible, but we also want to keep the scroll
// padding into account to ensure the UI looks good. Therefore we fake that the
// bottom of the child is actually `scrollPaddingBottom` amount of pixels lower.
let childBottom = childTop + child.clientHeight + scrollPaddingBottom
let parentTop = parent.scrollTop
let parentBottom = parentTop + parent.clientHeight
// Figure out if the child is fully visible in the scroll parent.
if (childTop >= parentTop && childBottom <= parentBottom) {
missing--
} else {
// Not fully visible, so we will use this child to calculate the height of
// each item. We will also use this to calculate how much of the item is
// already visible.
elementAmountVisible = Math.max(
0,
Math.min(childBottom, parentBottom) - Math.max(childTop, parentTop)
)
elementHeight = child.clientHeight
break
}
}
}
// There are fewer visible items than we want, so we will try to nudge the offset
// to show more items.
if (missing >= 1) {
setInnerOffset((existingOffset) => {
let newInnerOffset =
elementHeight * missing - // `missing` amount of `elementHeight`
elementAmountVisible + // The amount of the last item that is visible
scrollPaddingBottom // The scroll padding to ensure the UI looks good
// Nudged enough already, no need to continue
if (existingOffset >= newInnerOffset) {
return existingOffset
}
return newInnerOffset
})
}
},
})
: null,
// The `size` middleware will ensure the panel is never bigger than the viewport minus the
// provided `padding` that we want.
sizeMiddleware({
apply({ availableWidth, availableHeight, elements }) {
Object.assign(elements.floating.style, {
maxWidth: `${availableWidth - padding}px`,
maxHeight: `${availableHeight - padding}px`,
})
},
}),
].filter(Boolean),
whileElementsMounted: autoUpdate,
})
// Calculate placement information to expose as data attributes
let [exposedTo = to, exposedAlign = align] = context.placement.split('-')
// If userland code is using custom styles specifically for `bottom`, but they chose `selection`,
// then we want to make sure to map it to selection again otherwise styles could be wrong.
if (to === 'selection') exposedTo = 'selection'
let data = useMemo(
() => ({
anchor: [exposedTo, exposedAlign].filter(Boolean).join(' ') as React.ContextType<
typeof FloatingContext
>['slot']['anchor'],
}),
[exposedTo, exposedAlign]
)
let innerOffsetConfig = useInnerOffset(context, {
overflowRef,
onChange: setInnerOffset,
})
let { getReferenceProps, getFloatingProps } = useInteractions([innerOffsetConfig])
let setFloatingRef = useEvent((el: HTMLElement | null) => {
setFloatingElement(el)
refs.setFloating(el)
})
return (
<PlacementContext.Provider value={setConfig}>
<FloatingContext.Provider
value={{
setFloating: setFloatingRef,
setReference: refs.setReference,
styles: !isEnabled ? {} : floatingStyles,
getReferenceProps,
getFloatingProps,
slot: data,
}}
>
{children}
</FloatingContext.Provider>
</PlacementContext.Provider>
)
}
function useFixScrollingPixel(element: HTMLElement | null) {
useIsoMorphicEffect(() => {
if (!element) return
let observer = new MutationObserver(() => {
let maxHeight = element.style.maxHeight
if (parseFloat(maxHeight) !== parseInt(maxHeight)) {
element.style.maxHeight = `${Math.ceil(parseFloat(maxHeight))}px`
}
})
observer.observe(element, {
attributes: true,
attributeFilter: ['style'],
})
return () => {
observer.disconnect()
}
}, [element])
}
function useResolvedConfig(
config: (AnchorPropsWithSelection & InternalFloatingPanelProps) | null,
element?: HTMLElement | null
) {
let gap = useResolvePxValue(config?.gap, element)
let offset = useResolvePxValue(config?.offset, element)
let padding = useResolvePxValue(config?.padding, element)
return { ...config, gap, offset, padding }
}
function useResolvePxValue(
input?: string | number,
element?: HTMLElement | null,
defaultValue: number | undefined = undefined
) {
let d = useDisposables()
let computeValue = useEvent((value?: string | number, element?: HTMLElement | null) => {
// Nullish
if (value == null) return [defaultValue, null] as const
// Number as-is
if (typeof value === 'number') return [value, null] as const
// String values, the interesting part
if (typeof value === 'string') {
if (!element) return [defaultValue, null] as const
let result = resolveCSSVariablePxValue(value, element)
return [
result,
(setValue: (value?: number) => void) => {
let variables = resolveVariables(value)
// TODO: Improve this part and make it work
//
// Observe variables themselves. Currently the browser doesn't support this, but the
// variables we are interested in resolve to a pixel value. Which means that we can use
// this variable in the `margin` of an element. Then we can observe the `margin` of the
// element and we will be notified when the variable changes.
//
// if (typeof ResizeObserver !== 'undefined') {
// let tmpEl = document.createElement('div')
// element.appendChild(tmpEl)
//
// // Didn't use `fontSize` because a `fontSize` can't be negative.
// tmpEl.style.setProperty('margin-top', '0px', 'important')
//
// // Set the new value, if this is invalid the previous value will be used.
// tmpEl.style.setProperty('margin-top', value, 'important')
//
// let observer = new ResizeObserver(() => {
// let newResult = resolveCSSVariableValue(value, element)
//
// if (result !== newResult) {
// setValue(newResult)
// result = newResult
// }
// })
// observer.observe(tmpEl)
// d.add(() => observer.disconnect())
// return d.dispose
// }
// Works as a fallback, but not very performant because we are polling the value.
{
let history = variables.map((variable) =>
window.getComputedStyle(element!).getPropertyValue(variable)
)
d.requestAnimationFrame(function check() {
d.nextFrame(check)
// Fast path, detect if the value of the CSS Variable has changed before completely
// computing the new value. Once we use `resolveCSSVariablePxValue` we will have to
// compute the actual px value by injecting a temporary element into the DOM.
//
// This is a lot of work, so we want to avoid it if possible.
let changed = false
for (let [idx, variable] of variables.entries()) {
let value = window.getComputedStyle(element!).getPropertyValue(variable)
if (history[idx] !== value) {
history[idx] = value
changed = true
break
}
}
// Nothing changed, no need to perform the expensive computation.
if (!changed) return
let newResult = resolveCSSVariablePxValue(value, element)
if (result !== newResult) {
setValue(newResult)
result = newResult
}
})
}
return d.dispose
},
] as const
}
return [defaultValue, null] as const
})
// Calculate the value immediately when the input or element changes. Later we can setup a watcher
// to track the value changes over time.
let immediateValue = useMemo(() => computeValue(input, element)[0], [input, element])
let [value = immediateValue, setValue] = useState<number | undefined>()
useIsoMorphicEffect(() => {
let [value, watcher] = computeValue(input, element)
setValue(value)
if (!watcher) return
return watcher(setValue)
}, [input, element])
return value
}
function resolveVariables(value: string): string[] {
let matches = /var\((.*)\)/.exec(value)
if (matches) {
let idx = matches[1].indexOf(',')
if (idx === -1) {
return [matches[1]]
}
let variable = matches[1].slice(0, idx).trim()
let fallback = matches[1].slice(idx + 1).trim()
if (fallback) {
return [variable, ...resolveVariables(fallback)]
}
return [variable]
}
return []
}
function resolveCSSVariablePxValue(input: string, element: HTMLElement) {
// Resolve the value: Instead of trying to compute the value ourselves by converting rem /
// vwh / ... values to pixels or by parsing out the fallback values and evaluating it
// (because it can contain calc expressions or other variables).
//
// We will let the browser compute all of it by creating a temporary element and setting
// the value as a CSS variable. Then we can read the computed value from the browser.
//
//
// BUG REPORT ABOUT INCORRECT VALUES, look here:
// ---------------------------------------------
//
// Currently this technically contains a bug because we are rendering a new element inside of the
// current element. Which means that if the passed in element has CSS that looks like:
//
// ```css
// .the-element {
// --the-variable: 1rem
// }
//
// .the-element > * {
// --the-variable: 2rem
// }
// ```
//
// Then this will result to resolved value of `2rem`, instead of `1rem`
let tmpEl = document.createElement('div')
element.appendChild(tmpEl)
// Set the value to `0px` otherwise if an invalid value is provided later the browser will read
// out the default value.
//
// Didn't use `fontSize` because a `fontSize` can't be negative.
tmpEl.style.setProperty('margin-top', '0px', 'important')
// Set the new value, if this is invalid the previous value will be used.
tmpEl.style.setProperty('margin-top', input, 'important')
// Reading the `margin-top` will already be in pixels (e.g.: 123px).
let pxValue = parseFloat(window.getComputedStyle(tmpEl).marginTop) || 0
element.removeChild(tmpEl)
return pxValue
}