Repository navigation
Expand file tree
/
Copy pathangie-plugin-detection.ts
More file actions
71 lines (60 loc) · 1.74 KB
/
Copy pathangie-plugin-detection.ts
File metadata and controls
71 lines (60 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { AngieDetector } from './angie-detector';
const DEFAULT_TIMEOUT_MS = 3000;
const POLL_INTERVAL_MS = 50;
let sharedDetector: AngieDetector | null = null;
const sleep = ( ms: number ) => new Promise<void>( ( resolve ) => setTimeout( resolve, ms ) );
const pollUntil = async (
deadline: number,
predicate: () => boolean,
intervalMs = POLL_INTERVAL_MS,
): Promise<boolean> => {
while ( Date.now() < deadline ) {
if ( predicate() ) {
return true;
}
await sleep( intervalMs );
}
return predicate();
};
const getSharedDetector = (): AngieDetector => {
if ( ! sharedDetector ) {
sharedDetector = new AngieDetector();
}
return sharedDetector;
};
export const isAngiePluginAvailable = (): boolean => {
if ( typeof window === 'undefined' ) {
return false;
}
return window.angiePlugin?.available === true;
};
export const isAngiePluginActive = (): boolean => {
if ( ! isAngiePluginAvailable() ) {
return false;
}
return getSharedDetector().isReady();
};
export const waitForAngiePluginAvailable = async (
timeoutMs = DEFAULT_TIMEOUT_MS,
): Promise<boolean> => {
if ( typeof window === 'undefined' ) {
return false;
}
const deadline = Date.now() + timeoutMs;
return pollUntil( deadline, isAngiePluginAvailable );
};
export const waitForAngiePluginActive = async (
timeoutMs = DEFAULT_TIMEOUT_MS,
): Promise<boolean> => {
if ( typeof window === 'undefined' ) {
return false;
}
const start = Date.now();
const available = await waitForAngiePluginAvailable( timeoutMs );
if ( ! available ) {
return false;
}
const remaining = Math.max( 0, timeoutMs - ( Date.now() - start ) );
const result = await getSharedDetector().waitUntilReady( remaining );
return result.isReady;
};