Merged in fix/SW-3068-sitewide-alert-fix (pull request #2381)
fix(SW-3068): fix race condition that cause alert height not to be set correctly * fix(SW-3068): fix race condition that cause alert height not to be set correctly Approved-by: Linus Flood
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useRef } from "react"
|
||||
import { useCallback, useRef } from "react"
|
||||
|
||||
import { trpc } from "@/lib/trpc/client"
|
||||
import { StickyElementNameEnum } from "@/stores/sticky-position"
|
||||
@@ -31,40 +31,36 @@ export default function SiteWideAlert() {
|
||||
name: StickyElementNameEnum.SITEWIDE_ALERT,
|
||||
})
|
||||
|
||||
const updateHeight = useCallback(() => {
|
||||
if (alertRef.current) {
|
||||
const height = alertRef.current.offsetHeight
|
||||
const updateHeightRefCallback = useCallback(
|
||||
(node: HTMLDivElement | null) => {
|
||||
if (node) {
|
||||
const debouncedUpdate = debounce(([entry]) => {
|
||||
const height = entry.contentRect.height
|
||||
|
||||
document.documentElement.style.setProperty(
|
||||
"--sitewide-alert-height",
|
||||
`${height}px`
|
||||
)
|
||||
document.documentElement.style.setProperty(
|
||||
"--sitewide-alert-height",
|
||||
`${height}px`
|
||||
)
|
||||
|
||||
document.documentElement.style.setProperty(
|
||||
"--sitewide-alert-sticky-height",
|
||||
isAlarm ? `${height}px` : "0px"
|
||||
)
|
||||
}
|
||||
}, [isAlarm])
|
||||
document.documentElement.style.setProperty(
|
||||
"--sitewide-alert-sticky-height",
|
||||
isAlarm ? `${height}px` : "0px"
|
||||
)
|
||||
}, 100)
|
||||
|
||||
useEffect(() => {
|
||||
const alertElement = alertRef.current
|
||||
const debouncedResizeHandler = debounce(() => {
|
||||
updateHeight()
|
||||
}, 100)
|
||||
const observer = new ResizeObserver(debouncedResizeHandler)
|
||||
const observer = new ResizeObserver(debouncedUpdate)
|
||||
observer.observe(node)
|
||||
|
||||
if (alertElement) {
|
||||
observer.observe(alertElement)
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (alertElement) {
|
||||
observer.unobserve(alertElement)
|
||||
return () => {
|
||||
if (node) {
|
||||
observer.unobserve(node)
|
||||
}
|
||||
observer.disconnect()
|
||||
}
|
||||
}
|
||||
observer.disconnect()
|
||||
}
|
||||
}, [updateHeight])
|
||||
},
|
||||
[isAlarm]
|
||||
)
|
||||
|
||||
if (isLoading || !alert) {
|
||||
return null
|
||||
@@ -73,7 +69,10 @@ export default function SiteWideAlert() {
|
||||
return (
|
||||
<div
|
||||
id="sitewide-alert"
|
||||
ref={alertRef}
|
||||
ref={(node) => {
|
||||
updateHeightRefCallback(node)
|
||||
alertRef.current = node
|
||||
}}
|
||||
className={`${styles.sitewideAlert} ${isAlarm ? styles.alarm : ""}`}
|
||||
>
|
||||
<Alert
|
||||
|
||||
Reference in New Issue
Block a user