@@ -3,13 +3,16 @@ import { getRootVariable } from './css-loader';
3
3
const INTERVAL_MS = 8 ;
4
4
const TIMEOUT_MS = 50 ;
5
5
6
+ interface BaseObject {
7
+ id : string ;
8
+ }
9
+
6
10
interface ImageSrc {
7
11
light : string ;
8
12
dark : string ;
9
13
}
10
14
11
- interface ReplaceImageObject {
12
- id : string ;
15
+ interface ImageObject extends BaseObject {
13
16
src : ImageSrc ;
14
17
alt : string ;
15
18
}
@@ -36,10 +39,10 @@ const waitForStyle = (property: string): Promise<string> => {
36
39
} ) ;
37
40
} ;
38
41
39
- const replaceProc = async ( replaceImageObjectArray : ReplaceImageObject [ ] ) : Promise < void > => {
42
+ const replaceProc = async ( imageObjectArray : ImageObject [ ] ) : Promise < void > => {
40
43
const scheme = await waitForStyle ( '--color-scheme' ) ;
41
44
42
- for ( const x of replaceImageObjectArray ) {
45
+ for ( const x of imageObjectArray ) {
43
46
const elm = document . getElementById ( x . id ) ;
44
47
45
48
if ( elm === null ) {
@@ -57,16 +60,32 @@ const replaceProc = async (replaceImageObjectArray: ReplaceImageObject[]): Promi
57
60
}
58
61
} ;
59
62
60
- export const replaceId = ( replaceImageObjectArray : ReplaceImageObject [ ] ) : void => {
61
- replaceProc ( replaceImageObjectArray ) ;
63
+ const debounce = < T extends BaseObject > ( fn : ( ...args : T [ ] ) => void , delay : number ) : ( ( ...args : T [ ] ) => void ) => {
64
+ let timeoutId : ReturnType < typeof setTimeout > ;
65
+
66
+ return ( ...args : T [ ] ) => {
67
+ clearTimeout ( timeoutId ) ;
68
+ timeoutId = setTimeout ( ( ) => fn ( ...args ) , delay ) ;
69
+ } ;
70
+ } ;
71
+
72
+ export const replaceId = ( imageObjectArray : ImageObject [ ] ) : ( ( ) => void ) => {
73
+ replaceProc ( imageObjectArray ) ;
74
+
75
+ const debouncedReplace = debounce ( ( ) => replaceProc ( imageObjectArray ) , 150 ) ;
62
76
63
77
const observer = new MutationObserver ( mutations => {
64
78
for ( const x of mutations ) {
65
79
if ( x . attributeName === 'class' ) {
66
- replaceProc ( replaceImageObjectArray ) ;
80
+ debouncedReplace ( ) ;
67
81
}
68
82
}
69
83
} ) ;
70
84
71
85
observer . observe ( document . documentElement , { attributes : true , attributeFilter : [ 'class' ] } ) ;
86
+
87
+ // Cleanup function that can be called when needed
88
+ return ( ) => {
89
+ observer . disconnect ( ) ;
90
+ } ;
72
91
} ;
0 commit comments