|
| 1 | +import * as React from "react"; |
| 2 | +import { PropsWithChildren } from "react"; |
| 3 | + |
| 4 | +import { useKnockClient } from "../../core"; |
| 5 | +import { msTeamsProviderKey } from "../../core/utils"; |
| 6 | +import { useMsTeamsConnectionStatus } from "../hooks"; |
| 7 | +import { ConnectionStatus } from "../hooks/useMsTeamsConnectionStatus"; |
| 8 | + |
| 9 | +export interface KnockMsTeamsProviderState { |
| 10 | + knockMsTeamsChannelId: string; |
| 11 | + tenantId: string; |
| 12 | + connectionStatus: ConnectionStatus; |
| 13 | + setConnectionStatus: (connectionStatus: ConnectionStatus) => void; |
| 14 | + errorLabel: string | null; |
| 15 | + setErrorLabel: (label: string) => void; |
| 16 | + actionLabel: string | null; |
| 17 | + setActionLabel: (label: string | null) => void; |
| 18 | +} |
| 19 | + |
| 20 | +const MsTeamsProviderStateContext = |
| 21 | + React.createContext<KnockMsTeamsProviderState | null>(null); |
| 22 | + |
| 23 | +export interface KnockMsTeamsProviderProps { |
| 24 | + knockMsTeamsChannelId: string; |
| 25 | + tenantId: string; |
| 26 | +} |
| 27 | + |
| 28 | +export const KnockMsTeamsProvider: React.FC< |
| 29 | + PropsWithChildren<KnockMsTeamsProviderProps> |
| 30 | +> = ({ knockMsTeamsChannelId, tenantId, children }) => { |
| 31 | + const knock = useKnockClient(); |
| 32 | + |
| 33 | + const { |
| 34 | + connectionStatus, |
| 35 | + setConnectionStatus, |
| 36 | + errorLabel, |
| 37 | + setErrorLabel, |
| 38 | + actionLabel, |
| 39 | + setActionLabel, |
| 40 | + } = useMsTeamsConnectionStatus(knock, knockMsTeamsChannelId, tenantId); |
| 41 | + |
| 42 | + return ( |
| 43 | + <MsTeamsProviderStateContext.Provider |
| 44 | + key={msTeamsProviderKey({ |
| 45 | + knockMsTeamsChannelId, |
| 46 | + tenantId, |
| 47 | + connectionStatus, |
| 48 | + errorLabel, |
| 49 | + })} |
| 50 | + value={{ |
| 51 | + connectionStatus, |
| 52 | + setConnectionStatus, |
| 53 | + errorLabel, |
| 54 | + setErrorLabel, |
| 55 | + actionLabel, |
| 56 | + setActionLabel, |
| 57 | + knockMsTeamsChannelId, |
| 58 | + tenantId, |
| 59 | + }} |
| 60 | + > |
| 61 | + {children} |
| 62 | + </MsTeamsProviderStateContext.Provider> |
| 63 | + ); |
| 64 | +}; |
| 65 | + |
| 66 | +export const useKnockMsTeamsClient = (): KnockMsTeamsProviderState => { |
| 67 | + const context = React.useContext(MsTeamsProviderStateContext); |
| 68 | + if (!context) { |
| 69 | + throw new Error( |
| 70 | + "useKnockMsTeamsClient must be used within a KnockMsTeamsProvider", |
| 71 | + ); |
| 72 | + } |
| 73 | + return context; |
| 74 | +}; |
0 commit comments