mirror of
https://github.com/pezkuwichain/pwap.git
synced 2026-04-26 23:57:55 +00:00
Initial commit - PezkuwiChain Web Governance App
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
|
||||
interface AppContextType {
|
||||
sidebarOpen: boolean;
|
||||
toggleSidebar: () => void;
|
||||
}
|
||||
|
||||
const defaultAppContext: AppContextType = {
|
||||
sidebarOpen: false,
|
||||
toggleSidebar: () => {},
|
||||
};
|
||||
|
||||
const AppContext = createContext<AppContextType>(defaultAppContext);
|
||||
|
||||
export const useAppContext = () => useContext(AppContext);
|
||||
|
||||
export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||
|
||||
const toggleSidebar = () => {
|
||||
setSidebarOpen(prev => !prev);
|
||||
};
|
||||
|
||||
return (
|
||||
<AppContext.Provider
|
||||
value={{
|
||||
sidebarOpen,
|
||||
toggleSidebar,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AppContext.Provider>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,213 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from 'react';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
import { User } from '@supabase/supabase-js';
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
loading: boolean;
|
||||
isAdmin: boolean;
|
||||
signIn: (email: string, password: string) => Promise<{ error: any }>;
|
||||
signUp: (email: string, password: string, username: string, referralCode?: string) => Promise<{ error: any }>;
|
||||
signOut: () => Promise<void>;
|
||||
checkAdminStatus: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
// Demo/Founder account credentials
|
||||
const FOUNDER_ACCOUNT = {
|
||||
email: 'info@pezkuwichain.io',
|
||||
password: 'Sq230515yBkB@#nm90',
|
||||
id: 'founder-001',
|
||||
user_metadata: {
|
||||
full_name: 'Satoshi Qazi Muhammed',
|
||||
phone: '+9647700557978',
|
||||
recovery_email: 'satoshi@pezkuwichain.io',
|
||||
founder: true
|
||||
}
|
||||
};
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Check active sessions and sets the user
|
||||
supabase.auth.getSession().then(({ data: { session } }) => {
|
||||
setUser(session?.user ?? null);
|
||||
if (session?.user) {
|
||||
checkAdminStatus();
|
||||
}
|
||||
setLoading(false);
|
||||
}).catch(() => {
|
||||
// If Supabase is not available, continue without auth
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
// Listen for changes on auth state
|
||||
const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
|
||||
setUser(session?.user ?? null);
|
||||
if (session?.user) {
|
||||
checkAdminStatus();
|
||||
}
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
return () => subscription.unsubscribe();
|
||||
}, []);
|
||||
|
||||
const checkAdminStatus = async () => {
|
||||
try {
|
||||
const { data: { user } } = await supabase.auth.getUser();
|
||||
if (!user) return false;
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('admin_roles')
|
||||
.select('role')
|
||||
.eq('user_id', user.id)
|
||||
.single();
|
||||
|
||||
const adminStatus = !error && data && ['admin', 'super_admin'].includes(data.role);
|
||||
setIsAdmin(adminStatus);
|
||||
return adminStatus;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const signIn = async (email: string, password: string) => {
|
||||
// Check if this is the founder account (demo/fallback mode)
|
||||
if (email === FOUNDER_ACCOUNT.email && password === FOUNDER_ACCOUNT.password) {
|
||||
// Try Supabase first
|
||||
try {
|
||||
const { data, error } = await supabase.auth.signInWithPassword({
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
if (!error && data.user) {
|
||||
await checkAdminStatus();
|
||||
return { error: null };
|
||||
}
|
||||
} catch {
|
||||
// Supabase not available
|
||||
}
|
||||
|
||||
// Fallback to demo mode for founder account
|
||||
const demoUser = {
|
||||
id: FOUNDER_ACCOUNT.id,
|
||||
email: FOUNDER_ACCOUNT.email,
|
||||
user_metadata: FOUNDER_ACCOUNT.user_metadata,
|
||||
email_confirmed_at: new Date().toISOString(),
|
||||
created_at: new Date().toISOString(),
|
||||
} as User;
|
||||
|
||||
setUser(demoUser);
|
||||
setIsAdmin(true);
|
||||
|
||||
// Store in localStorage for persistence
|
||||
localStorage.setItem('demo_user', JSON.stringify(demoUser));
|
||||
|
||||
return { error: null };
|
||||
}
|
||||
|
||||
// For other accounts, use Supabase
|
||||
try {
|
||||
const { data, error } = await supabase.auth.signInWithPassword({
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
if (!error && data.user) {
|
||||
await checkAdminStatus();
|
||||
}
|
||||
|
||||
return { error };
|
||||
} catch (err) {
|
||||
return {
|
||||
error: {
|
||||
message: 'Authentication service unavailable. Please try again later.'
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const signUp = async (email: string, password: string, username: string, referralCode?: string) => {
|
||||
try {
|
||||
const { data, error } = await supabase.auth.signUp({
|
||||
email,
|
||||
password,
|
||||
options: {
|
||||
data: {
|
||||
username,
|
||||
referral_code: referralCode || null,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!error && data.user) {
|
||||
// Create profile in profiles table with referral code
|
||||
await supabase.from('profiles').insert({
|
||||
id: data.user.id,
|
||||
username,
|
||||
email,
|
||||
referred_by: referralCode || null,
|
||||
});
|
||||
|
||||
// If there's a referral code, track it
|
||||
if (referralCode) {
|
||||
// You can add logic here to reward the referrer
|
||||
// For example, update their referral count or add rewards
|
||||
console.log(`User registered with referral code: ${referralCode}`);
|
||||
}
|
||||
}
|
||||
|
||||
return { error };
|
||||
} catch (err) {
|
||||
return {
|
||||
error: {
|
||||
message: 'Registration service unavailable. Please try again later.'
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const signOut = async () => {
|
||||
localStorage.removeItem('demo_user');
|
||||
setIsAdmin(false);
|
||||
await supabase.auth.signOut();
|
||||
};
|
||||
|
||||
// Check for demo user on mount
|
||||
useEffect(() => {
|
||||
const demoUser = localStorage.getItem('demo_user');
|
||||
if (demoUser && !user) {
|
||||
const parsedUser = JSON.parse(demoUser);
|
||||
setUser(parsedUser);
|
||||
setIsAdmin(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{
|
||||
user,
|
||||
loading,
|
||||
isAdmin,
|
||||
signIn,
|
||||
signUp,
|
||||
signOut,
|
||||
checkAdminStatus
|
||||
}}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,161 @@
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
import { useWallet } from './WalletContext';
|
||||
import {
|
||||
IdentityProfile,
|
||||
KYCData,
|
||||
Badge,
|
||||
Role,
|
||||
calculateReputationScore,
|
||||
generateZKProof,
|
||||
DEFAULT_BADGES,
|
||||
ROLES
|
||||
} from '@/lib/identity';
|
||||
|
||||
interface IdentityContextType {
|
||||
profile: IdentityProfile | null;
|
||||
isVerifying: boolean;
|
||||
startKYC: (data: KYCData) => Promise<void>;
|
||||
updatePrivacySettings: (settings: any) => void;
|
||||
addBadge: (badge: Badge) => void;
|
||||
assignRole: (role: Role) => void;
|
||||
refreshReputation: () => void;
|
||||
}
|
||||
|
||||
const IdentityContext = createContext<IdentityContextType | undefined>(undefined);
|
||||
|
||||
export function IdentityProvider({ children }: { children: React.ReactNode }) {
|
||||
const { account } = useWallet();
|
||||
const [profile, setProfile] = useState<IdentityProfile | null>(null);
|
||||
const [isVerifying, setIsVerifying] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (account) {
|
||||
// Load or create profile for connected wallet
|
||||
const storedProfile = localStorage.getItem(`identity_${account}`);
|
||||
if (storedProfile) {
|
||||
setProfile(JSON.parse(storedProfile));
|
||||
} else {
|
||||
// Create new profile
|
||||
const newProfile: IdentityProfile = {
|
||||
address: account,
|
||||
verificationLevel: 'none',
|
||||
kycStatus: 'none',
|
||||
reputationScore: 0,
|
||||
badges: [],
|
||||
roles: [],
|
||||
privacySettings: {
|
||||
showRealName: false,
|
||||
showEmail: false,
|
||||
showCountry: true,
|
||||
useZKProof: true
|
||||
}
|
||||
};
|
||||
setProfile(newProfile);
|
||||
localStorage.setItem(`identity_${account}`, JSON.stringify(newProfile));
|
||||
}
|
||||
} else {
|
||||
setProfile(null);
|
||||
}
|
||||
}, [account]);
|
||||
|
||||
const startKYC = async (data: KYCData) => {
|
||||
if (!profile) return;
|
||||
|
||||
setIsVerifying(true);
|
||||
try {
|
||||
// Simulate KYC verification process
|
||||
await new Promise(resolve => setTimeout(resolve, 3000));
|
||||
|
||||
const zkProof = generateZKProof(data);
|
||||
|
||||
const updatedProfile: IdentityProfile = {
|
||||
...profile,
|
||||
kycStatus: 'approved',
|
||||
verificationLevel: data.documentType ? 'verified' : 'basic',
|
||||
verificationDate: new Date(),
|
||||
badges: [...profile.badges, ...DEFAULT_BADGES],
|
||||
roles: [ROLES.verified_user as Role],
|
||||
reputationScore: calculateReputationScore(
|
||||
[],
|
||||
data.documentType ? 'verified' : 'basic',
|
||||
[...profile.badges, ...DEFAULT_BADGES]
|
||||
)
|
||||
};
|
||||
|
||||
setProfile(updatedProfile);
|
||||
localStorage.setItem(`identity_${profile.address}`, JSON.stringify(updatedProfile));
|
||||
} catch (error) {
|
||||
console.error('KYC verification failed:', error);
|
||||
} finally {
|
||||
setIsVerifying(false);
|
||||
}
|
||||
};
|
||||
|
||||
const updatePrivacySettings = (settings: any) => {
|
||||
if (!profile) return;
|
||||
|
||||
const updatedProfile = {
|
||||
...profile,
|
||||
privacySettings: { ...profile.privacySettings, ...settings }
|
||||
};
|
||||
|
||||
setProfile(updatedProfile);
|
||||
localStorage.setItem(`identity_${profile.address}`, JSON.stringify(updatedProfile));
|
||||
};
|
||||
|
||||
const addBadge = (badge: Badge) => {
|
||||
if (!profile) return;
|
||||
|
||||
const updatedProfile = {
|
||||
...profile,
|
||||
badges: [...profile.badges, badge]
|
||||
};
|
||||
|
||||
setProfile(updatedProfile);
|
||||
localStorage.setItem(`identity_${profile.address}`, JSON.stringify(updatedProfile));
|
||||
};
|
||||
|
||||
const assignRole = (role: Role) => {
|
||||
if (!profile) return;
|
||||
|
||||
const updatedProfile = {
|
||||
...profile,
|
||||
roles: [...profile.roles, role]
|
||||
};
|
||||
|
||||
setProfile(updatedProfile);
|
||||
localStorage.setItem(`identity_${profile.address}`, JSON.stringify(updatedProfile));
|
||||
};
|
||||
|
||||
const refreshReputation = () => {
|
||||
if (!profile) return;
|
||||
|
||||
const newScore = calculateReputationScore([], profile.verificationLevel, profile.badges);
|
||||
const updatedProfile = { ...profile, reputationScore: newScore };
|
||||
|
||||
setProfile(updatedProfile);
|
||||
localStorage.setItem(`identity_${profile.address}`, JSON.stringify(updatedProfile));
|
||||
};
|
||||
|
||||
return (
|
||||
<IdentityContext.Provider value={{
|
||||
profile,
|
||||
isVerifying,
|
||||
startKYC,
|
||||
updatePrivacySettings,
|
||||
addBadge,
|
||||
assignRole,
|
||||
refreshReputation
|
||||
}}>
|
||||
{children}
|
||||
</IdentityContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useIdentity = () => {
|
||||
const context = useContext(IdentityContext);
|
||||
if (!context) {
|
||||
throw new Error('useIdentity must be used within IdentityProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
@@ -0,0 +1,162 @@
|
||||
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
||||
import { PEZKUWICHAIN_NETWORK, WALLET_ERRORS, initialWalletState, WalletState } from '@/lib/wallet';
|
||||
|
||||
interface WalletContextType extends WalletState {
|
||||
connectMetaMask: () => Promise<void>;
|
||||
connectWalletConnect: () => Promise<void>;
|
||||
disconnect: () => void;
|
||||
switchNetwork: () => Promise<void>;
|
||||
signTransaction: (tx: any) => Promise<string>;
|
||||
signMessage: (message: string) => Promise<string>;
|
||||
}
|
||||
|
||||
const WalletContext = createContext<WalletContextType | undefined>(undefined);
|
||||
|
||||
export const WalletProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [walletState, setWalletState] = useState<WalletState>(initialWalletState);
|
||||
|
||||
const updateBalance = useCallback(async (address: string, provider: any) => {
|
||||
try {
|
||||
const balance = await provider.request({
|
||||
method: 'eth_getBalance',
|
||||
params: [address, 'latest']
|
||||
});
|
||||
setWalletState(prev => ({ ...prev, balance }));
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch balance:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const connectMetaMask = useCallback(async () => {
|
||||
if (!window.ethereum) {
|
||||
setWalletState(prev => ({ ...prev, error: WALLET_ERRORS.NO_WALLET }));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
|
||||
const chainId = await window.ethereum.request({ method: 'eth_chainId' });
|
||||
|
||||
setWalletState({
|
||||
isConnected: true,
|
||||
address: accounts[0],
|
||||
balance: '0',
|
||||
chainId,
|
||||
provider: window.ethereum,
|
||||
error: null
|
||||
});
|
||||
|
||||
await updateBalance(accounts[0], window.ethereum);
|
||||
} catch (error: any) {
|
||||
setWalletState(prev => ({
|
||||
...prev,
|
||||
error: error.code === 4001 ? WALLET_ERRORS.USER_REJECTED : WALLET_ERRORS.CONNECTION_FAILED
|
||||
}));
|
||||
}
|
||||
}, [updateBalance]);
|
||||
|
||||
const connectWalletConnect = useCallback(async () => {
|
||||
// WalletConnect implementation placeholder
|
||||
setWalletState(prev => ({
|
||||
...prev,
|
||||
error: 'WalletConnect integration coming soon'
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const disconnect = useCallback(() => {
|
||||
setWalletState(initialWalletState);
|
||||
}, []);
|
||||
|
||||
const switchNetwork = useCallback(async () => {
|
||||
if (!walletState.provider) return;
|
||||
|
||||
try {
|
||||
await walletState.provider.request({
|
||||
method: 'wallet_switchEthereumChain',
|
||||
params: [{ chainId: PEZKUWICHAIN_NETWORK.chainId }]
|
||||
});
|
||||
} catch (error: any) {
|
||||
if (error.code === 4902) {
|
||||
try {
|
||||
await walletState.provider.request({
|
||||
method: 'wallet_addEthereumChain',
|
||||
params: [PEZKUWICHAIN_NETWORK]
|
||||
});
|
||||
} catch (addError) {
|
||||
setWalletState(prev => ({ ...prev, error: WALLET_ERRORS.NETWORK_ERROR }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [walletState.provider]);
|
||||
|
||||
const signTransaction = useCallback(async (tx: any): Promise<string> => {
|
||||
if (!walletState.provider || !walletState.address) {
|
||||
throw new Error('Wallet not connected');
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await walletState.provider.request({
|
||||
method: 'eth_sendTransaction',
|
||||
params: [{ ...tx, from: walletState.address }]
|
||||
});
|
||||
return result;
|
||||
} catch (error: any) {
|
||||
throw new Error(error.message || WALLET_ERRORS.TRANSACTION_FAILED);
|
||||
}
|
||||
}, [walletState.provider, walletState.address]);
|
||||
|
||||
const signMessage = useCallback(async (message: string): Promise<string> => {
|
||||
if (!walletState.provider || !walletState.address) {
|
||||
throw new Error('Wallet not connected');
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await walletState.provider.request({
|
||||
method: 'personal_sign',
|
||||
params: [message, walletState.address]
|
||||
});
|
||||
return result;
|
||||
} catch (error: any) {
|
||||
throw new Error(error.message || 'Failed to sign message');
|
||||
}
|
||||
}, [walletState.provider, walletState.address]);
|
||||
|
||||
useEffect(() => {
|
||||
if (window.ethereum) {
|
||||
window.ethereum.on('accountsChanged', (accounts: string[]) => {
|
||||
if (accounts.length === 0) {
|
||||
disconnect();
|
||||
} else {
|
||||
setWalletState(prev => ({ ...prev, address: accounts[0] }));
|
||||
updateBalance(accounts[0], window.ethereum);
|
||||
}
|
||||
});
|
||||
|
||||
window.ethereum.on('chainChanged', (chainId: string) => {
|
||||
setWalletState(prev => ({ ...prev, chainId }));
|
||||
});
|
||||
}
|
||||
}, [disconnect, updateBalance]);
|
||||
|
||||
return (
|
||||
<WalletContext.Provider value={{
|
||||
...walletState,
|
||||
connectMetaMask,
|
||||
connectWalletConnect,
|
||||
disconnect,
|
||||
switchNetwork,
|
||||
signTransaction,
|
||||
signMessage
|
||||
}}>
|
||||
{children}
|
||||
</WalletContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useWallet = () => {
|
||||
const context = useContext(WalletContext);
|
||||
if (!context) {
|
||||
throw new Error('useWallet must be used within WalletProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
@@ -0,0 +1,126 @@
|
||||
import React, { createContext, useContext, useEffect, useState, useCallback, useRef } from 'react';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
|
||||
interface WebSocketMessage {
|
||||
type: 'comment' | 'vote' | 'sentiment' | 'mention' | 'reply' | 'proposal_update';
|
||||
data: any;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
interface WebSocketContextType {
|
||||
isConnected: boolean;
|
||||
subscribe: (event: string, callback: (data: any) => void) => void;
|
||||
unsubscribe: (event: string, callback: (data: any) => void) => void;
|
||||
sendMessage: (message: WebSocketMessage) => void;
|
||||
reconnect: () => void;
|
||||
}
|
||||
|
||||
const WebSocketContext = createContext<WebSocketContextType | null>(null);
|
||||
|
||||
export const useWebSocket = () => {
|
||||
const context = useContext(WebSocketContext);
|
||||
if (!context) {
|
||||
throw new Error('useWebSocket must be used within WebSocketProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const ws = useRef<WebSocket | null>(null);
|
||||
const reconnectTimeout = useRef<NodeJS.Timeout>();
|
||||
const eventListeners = useRef<Map<string, Set<(data: any) => void>>>(new Map());
|
||||
const { toast } = useToast();
|
||||
|
||||
const connect = useCallback(() => {
|
||||
try {
|
||||
// In production, replace with actual WebSocket server URL
|
||||
const wsUrl = import.meta.env.VITE_WS_URL || 'wss://pezkuwichain-ws.example.com';
|
||||
ws.current = new WebSocket(wsUrl);
|
||||
|
||||
ws.current.onopen = () => {
|
||||
setIsConnected(true);
|
||||
toast({
|
||||
title: "Connected",
|
||||
description: "Real-time updates enabled",
|
||||
});
|
||||
};
|
||||
|
||||
ws.current.onmessage = (event) => {
|
||||
try {
|
||||
const message: WebSocketMessage = JSON.parse(event.data);
|
||||
const listeners = eventListeners.current.get(message.type);
|
||||
if (listeners) {
|
||||
listeners.forEach(callback => callback(message.data));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to parse WebSocket message:', error);
|
||||
}
|
||||
};
|
||||
|
||||
ws.current.onerror = (error) => {
|
||||
console.error('WebSocket error:', error);
|
||||
toast({
|
||||
title: "Connection Error",
|
||||
description: "Failed to establish real-time connection",
|
||||
variant: "destructive",
|
||||
});
|
||||
};
|
||||
|
||||
ws.current.onclose = () => {
|
||||
setIsConnected(false);
|
||||
// Attempt to reconnect after 5 seconds
|
||||
reconnectTimeout.current = setTimeout(() => {
|
||||
connect();
|
||||
}, 5000);
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Failed to create WebSocket connection:', error);
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => {
|
||||
connect();
|
||||
|
||||
return () => {
|
||||
if (reconnectTimeout.current) {
|
||||
clearTimeout(reconnectTimeout.current);
|
||||
}
|
||||
if (ws.current) {
|
||||
ws.current.close();
|
||||
}
|
||||
};
|
||||
}, [connect]);
|
||||
|
||||
const subscribe = useCallback((event: string, callback: (data: any) => void) => {
|
||||
if (!eventListeners.current.has(event)) {
|
||||
eventListeners.current.set(event, new Set());
|
||||
}
|
||||
eventListeners.current.get(event)?.add(callback);
|
||||
}, []);
|
||||
|
||||
const unsubscribe = useCallback((event: string, callback: (data: any) => void) => {
|
||||
eventListeners.current.get(event)?.delete(callback);
|
||||
}, []);
|
||||
|
||||
const sendMessage = useCallback((message: WebSocketMessage) => {
|
||||
if (ws.current?.readyState === WebSocket.OPEN) {
|
||||
ws.current.send(JSON.stringify(message));
|
||||
} else {
|
||||
console.warn('WebSocket is not connected');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const reconnect = useCallback(() => {
|
||||
if (ws.current) {
|
||||
ws.current.close();
|
||||
}
|
||||
connect();
|
||||
}, [connect]);
|
||||
|
||||
return (
|
||||
<WebSocketContext.Provider value={{ isConnected, subscribe, unsubscribe, sendMessage, reconnect }}>
|
||||
{children}
|
||||
</WebSocketContext.Provider>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user