-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathFederationContext.js
More file actions
72 lines (59 loc) · 2.01 KB
/
FederationContext.js
File metadata and controls
72 lines (59 loc) · 2.01 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
72
import React, { createContext, useContext, useEffect, useState } from 'react';
/**
* Exposes federation state to the component tree.
* @property {boolean} isFederated - true when the active room is Matrix-bridged
* @property {string|null} matrixHomeserver - the homeserver origin (e.g. "matrix.org")
* @property {boolean} federationLoading - true while room info is being fetched
*/
const FederationContext = createContext({
isFederated: false,
matrixHomeserver: null,
federationLoading: false,
});
export const FederationProvider = ({ children, RCInstance, forceEnabled = false }) => {
const [isFederated, setIsFederated] = useState(forceEnabled);
const [matrixHomeserver, setMatrixHomeserver] = useState(
forceEnabled ? 'matrix.org' : null
);
const [federationLoading, setFederationLoading] = useState(!forceEnabled);
useEffect(() => {
// When force-enabled (demo/story mode), skip server detection
if (forceEnabled) return;
if (!RCInstance) {
setFederationLoading(false);
return;
}
let cancelled = false;
const detectFederation = async () => {
try {
setFederationLoading(true);
const info = await RCInstance.channelInfo();
if (cancelled) return;
const room = info?.room;
const federated =
room?.federated === true || room?.federation != null;
setIsFederated(federated);
if (federated && room?.federation?.origin) {
setMatrixHomeserver(room.federation.origin);
}
} catch {
if (!cancelled) setIsFederated(false);
} finally {
if (!cancelled) setFederationLoading(false);
}
};
detectFederation();
return () => {
cancelled = true;
};
}, [RCInstance, forceEnabled]);
return (
<FederationContext.Provider
value={{ isFederated, matrixHomeserver, federationLoading }}
>
{children}
</FederationContext.Provider>
);
};
export const useFederation = () => useContext(FederationContext);
export default FederationContext;