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:
Tobias Johansson
2025-06-17 12:46:22 +00:00
parent a29f2b94a7
commit d80e92a646

View File

@@ -1,6 +1,6 @@
"use client" "use client"
import { useCallback, useEffect, useRef } from "react" import { useCallback, useRef } from "react"
import { trpc } from "@/lib/trpc/client" import { trpc } from "@/lib/trpc/client"
import { StickyElementNameEnum } from "@/stores/sticky-position" import { StickyElementNameEnum } from "@/stores/sticky-position"
@@ -31,9 +31,11 @@ export default function SiteWideAlert() {
name: StickyElementNameEnum.SITEWIDE_ALERT, name: StickyElementNameEnum.SITEWIDE_ALERT,
}) })
const updateHeight = useCallback(() => { const updateHeightRefCallback = useCallback(
if (alertRef.current) { (node: HTMLDivElement | null) => {
const height = alertRef.current.offsetHeight if (node) {
const debouncedUpdate = debounce(([entry]) => {
const height = entry.contentRect.height
document.documentElement.style.setProperty( document.documentElement.style.setProperty(
"--sitewide-alert-height", "--sitewide-alert-height",
@@ -44,27 +46,21 @@ export default function SiteWideAlert() {
"--sitewide-alert-sticky-height", "--sitewide-alert-sticky-height",
isAlarm ? `${height}px` : "0px" isAlarm ? `${height}px` : "0px"
) )
}
}, [isAlarm])
useEffect(() => {
const alertElement = alertRef.current
const debouncedResizeHandler = debounce(() => {
updateHeight()
}, 100) }, 100)
const observer = new ResizeObserver(debouncedResizeHandler)
if (alertElement) { const observer = new ResizeObserver(debouncedUpdate)
observer.observe(alertElement) observer.observe(node)
}
return () => { return () => {
if (alertElement) { if (node) {
observer.unobserve(alertElement) observer.unobserve(node)
} }
observer.disconnect() observer.disconnect()
} }
}, [updateHeight]) }
},
[isAlarm]
)
if (isLoading || !alert) { if (isLoading || !alert) {
return null return null
@@ -73,7 +69,10 @@ export default function SiteWideAlert() {
return ( return (
<div <div
id="sitewide-alert" id="sitewide-alert"
ref={alertRef} ref={(node) => {
updateHeightRefCallback(node)
alertRef.current = node
}}
className={`${styles.sitewideAlert} ${isAlarm ? styles.alarm : ""}`} className={`${styles.sitewideAlert} ${isAlarm ? styles.alarm : ""}`}
> >
<Alert <Alert