2025-09-18 17:02:11 +05:30
|
|
|
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
|
|
|
|
import { OpChanClient } from '@opchan/core';
|
|
|
|
|
import { localDatabase, messageManager } from '@opchan/core';
|
2025-09-18 22:04:40 +05:30
|
|
|
import { ClientProvider } from '../contexts/ClientContext';
|
2025-09-18 17:02:11 +05:30
|
|
|
import { AuthProvider } from '../contexts/AuthContext';
|
|
|
|
|
import { ForumProvider } from '../contexts/ForumContext';
|
|
|
|
|
import { ModerationProvider } from '../contexts/ModerationContext';
|
|
|
|
|
|
|
|
|
|
export interface OpChanProviderProps {
|
|
|
|
|
ordiscanApiKey: string;
|
|
|
|
|
debug?: boolean;
|
|
|
|
|
children: React.ReactNode;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const OpChanProvider: React.FC<OpChanProviderProps> = ({
|
|
|
|
|
ordiscanApiKey,
|
|
|
|
|
debug,
|
|
|
|
|
children,
|
|
|
|
|
}) => {
|
|
|
|
|
const [isReady, setIsReady] = useState(false);
|
|
|
|
|
const clientRef = useRef<OpChanClient | null>(null);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
let cancelled = false;
|
|
|
|
|
|
|
|
|
|
const init = async () => {
|
|
|
|
|
if (typeof window === 'undefined') return; // SSR guard
|
|
|
|
|
|
|
|
|
|
// Configure environment and create client
|
|
|
|
|
const client = new OpChanClient({
|
|
|
|
|
ordiscanApiKey,
|
|
|
|
|
debug: !!debug,
|
|
|
|
|
isDevelopment: !!debug,
|
|
|
|
|
});
|
|
|
|
|
clientRef.current = client;
|
|
|
|
|
|
|
|
|
|
// Open local DB early for warm cache
|
|
|
|
|
await localDatabase.open().catch(console.error);
|
|
|
|
|
|
2025-09-19 13:11:27 +05:30
|
|
|
try {
|
|
|
|
|
await client.messageManager.initialize();
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error('Failed to initialize message manager:', e);
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-18 17:02:11 +05:30
|
|
|
|
|
|
|
|
if (!cancelled) setIsReady(true);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
init();
|
|
|
|
|
return () => {
|
|
|
|
|
cancelled = true;
|
|
|
|
|
};
|
|
|
|
|
}, [ordiscanApiKey, debug]);
|
|
|
|
|
|
|
|
|
|
const providers = useMemo(() => {
|
|
|
|
|
if (!isReady || !clientRef.current) return null;
|
|
|
|
|
return (
|
2025-09-18 22:04:40 +05:30
|
|
|
<ClientProvider client={clientRef.current}>
|
|
|
|
|
<AuthProvider client={clientRef.current}>
|
|
|
|
|
<ModerationProvider>
|
|
|
|
|
<ForumProvider client={clientRef.current}>{children}</ForumProvider>
|
|
|
|
|
</ModerationProvider>
|
|
|
|
|
</AuthProvider>
|
|
|
|
|
</ClientProvider>
|
2025-09-18 17:02:11 +05:30
|
|
|
);
|
|
|
|
|
}, [isReady, children]);
|
|
|
|
|
|
|
|
|
|
return providers || null;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|