File tree Expand file tree Collapse file tree 1 file changed +16
-2
lines changed Expand file tree Collapse file tree 1 file changed +16
-2
lines changed Original file line number Diff line number Diff line change 1- import { useRef } from 'preact/hooks' ;
1+ import { useRef , useEffect } from 'preact/hooks' ;
22
33export function useLiveRegion < T extends HTMLElement = HTMLElement > ( ) {
44 const ref = useRef < T | null > ( null ) ;
5+ const timerRef = useRef < ReturnType < typeof setTimeout > | null > ( null ) ;
6+
7+ /** Clear any existing timer */
8+ const clearTimer = ( ) => {
9+ if ( timerRef . current !== null ) {
10+ clearTimeout ( timerRef . current ) ;
11+ timerRef . current = null ;
12+ }
13+ if ( ref . current ) ref . current . textContent = '' ;
14+ } ;
515
616 const announce = ( message : string , clearMessage = 1000 ) => {
717 const node = ref . current ;
818 if ( ! node ) return ;
19+ clearTimer ( ) ;
920 node . textContent = message ;
10- setTimeout ( ( ) => {
21+ timerRef . current = setTimeout ( ( ) => {
1122 if ( node ) node . textContent = '' ;
23+ timerRef . current = null ;
1224 } , clearMessage ) ;
1325 } ;
1426
27+ useEffect ( ( ) => clearTimer , [ ] ) ;
28+
1529 return { ref, announce } ;
1630}
You can’t perform that action at this time.
0 commit comments