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' ;
2
2
3
3
export function useLiveRegion < T extends HTMLElement = HTMLElement > ( ) {
4
4
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
+ } ;
5
15
6
16
const announce = ( message : string , clearMessage = 1000 ) => {
7
17
const node = ref . current ;
8
18
if ( ! node ) return ;
19
+ clearTimer ( ) ;
9
20
node . textContent = message ;
10
- setTimeout ( ( ) => {
21
+ timerRef . current = setTimeout ( ( ) => {
11
22
if ( node ) node . textContent = '' ;
23
+ timerRef . current = null ;
12
24
} , clearMessage ) ;
13
25
} ;
14
26
27
+ useEffect ( ( ) => clearTimer , [ ] ) ;
28
+
15
29
return { ref, announce } ;
16
30
}
You can’t perform that action at this time.
0 commit comments