feat: refactor TopLoader to use a hook for active state management and improve CSS for fixed positioning
CI/CD - ERP Distribution / Build & Deploy Backend (pull_request) Failing after 10m33s
CI/CD - ERP Distribution / Build & Deploy Frontend (pull_request) Failing after 14m21s

This commit is contained in:
Kalana B. Thilakarathna
2026-10-19 23:37:45 +05:30
parent 21b38b5276
commit 28c465f59b
4 changed files with 52 additions and 29 deletions
@@ -1,26 +1,44 @@
'use client'
import { useEffect, useState } from 'react'
import { useEffect, useState, useSyncExternalStore } from 'react'
/**
* Thin top strip shown while `active` is true. Stays visible for at least
* `minDurationMs` so quick fetches don't produce an invisible flicker.
*/
export function TopLoader({ active, minDurationMs = 350 }: { active: boolean; minDurationMs?: number }) {
const [visible, setVisible] = useState(active)
// Global ref-count store. Any page can call useTopLoader(active) and the
// shared <TopLoader /> (mounted once in the dashboard layout) will reflect it.
let activeCount = 0
const listeners = new Set<() => void>()
function emit() { listeners.forEach(l => l()) }
function subscribe(cb: () => void) { listeners.add(cb); return () => { listeners.delete(cb) } }
function getSnapshot() { return activeCount }
export function useTopLoader(active: boolean) {
useEffect(() => {
if (!active) return
activeCount += 1
emit()
return () => {
activeCount = Math.max(0, activeCount - 1)
emit()
}
}, [active])
}
// Short tail so a sub-100ms fetch still shows the strip briefly.
const TAIL_MS = 350
export function TopLoader() {
const count = useSyncExternalStore(subscribe, getSnapshot, () => 0)
const [tailing, setTailing] = useState(false)
useEffect(() => {
if (active) {
setVisible(true)
return
}
const t = setTimeout(() => setVisible(false), minDurationMs)
if (count > 0) { setTailing(true); return }
const t = setTimeout(() => setTailing(false), TAIL_MS)
return () => clearTimeout(t)
}, [active, minDurationMs])
}, [count])
if (!visible) return null
if (count === 0 && !tailing) return null
return (
<div className="top-loader">
<div className="top-loader" aria-hidden="true">
<div className="top-loader__bar">
<span className="top-loader__head" />
</div>