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,40 +31,36 @@ 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",
`${height}px` `${height}px`
) )
document.documentElement.style.setProperty( document.documentElement.style.setProperty(
"--sitewide-alert-sticky-height", "--sitewide-alert-sticky-height",
isAlarm ? `${height}px` : "0px" isAlarm ? `${height}px` : "0px"
) )
} }, 100)
}, [isAlarm])
useEffect(() => { const observer = new ResizeObserver(debouncedUpdate)
const alertElement = alertRef.current observer.observe(node)
const debouncedResizeHandler = debounce(() => {
updateHeight()
}, 100)
const observer = new ResizeObserver(debouncedResizeHandler)
if (alertElement) { return () => {
observer.observe(alertElement) if (node) {
} observer.unobserve(node)
}
return () => { observer.disconnect()
if (alertElement) { }
observer.unobserve(alertElement)
} }
observer.disconnect() },
} [isAlarm]
}, [updateHeight]) )
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