Skip to content

Commit

Permalink
ops
Browse files Browse the repository at this point in the history
  • Loading branch information
greg-schrammel committed Aug 16, 2023
1 parent 6c36678 commit e4dc3b1
Showing 1 changed file with 27 additions and 13 deletions.
40 changes: 27 additions & 13 deletions packages/partysocket/src/react.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,13 @@ import React, {

const PartySocketContext = createContext<PartySocket | null>(null);

type UsePartySocketListeners = {
onOpen?: (event: WebSocketEventMap["open"]) => void;
onMessage?: (event: WebSocketEventMap["message"]) => void;
onClose?: (event: WebSocketEventMap["close"]) => void;
onError?: (event: WebSocketEventMap["error"]) => void;
};
type UsePartySocketOptions =
| (PartySocketOptions & UsePartySocketListeners)
| (UsePartySocketListeners & { room?: never; host?: never });

const globalPartySockets: {
[host: string]: {
[room: string]: PartySocket;
};
} = {};
const listenersCounter: { [host: string]: { [room: string]: number } } = {};
const getGlobalPartySocket = (options?: PartySocketOptions) => {
if (!options) return;

const getGlobalPartySocket = (options: PartySocketOptions) => {
const { host, room } = options;
globalPartySockets[host] ??= {};
globalPartySockets[host][room] ??= new PartySocket({
Expand All @@ -40,6 +28,29 @@ const getGlobalPartySocket = (options?: PartySocketOptions) => {
return globalPartySockets[host][room];
};

export function PartySocketProvider({
children,
...options
}: PropsWithChildren<PartySocketOptions>) {
const [socket] = useState(() => getGlobalPartySocket(options)!);

return (
<PartySocketContext.Provider value={socket}>
{children}
</PartySocketContext.Provider>
);
}

type UsePartySocketListeners = {
onOpen?: (event: WebSocketEventMap["open"]) => void;
onMessage?: (event: WebSocketEventMap["message"]) => void;
onClose?: (event: WebSocketEventMap["close"]) => void;
onError?: (event: WebSocketEventMap["error"]) => void;
};
type UsePartySocketOptions =
| (PartySocketOptions & UsePartySocketListeners)
| (UsePartySocketListeners & { room?: never; host?: never });

const usePartySocketEvent = <
E extends keyof WebSocketEventMap,
CbArgs extends WebSocketEventMap[E]
Expand All @@ -65,6 +76,8 @@ const usePartySocketEvent = <
}, [socket]);
};

const listenersCounter: { [host: string]: { [room: string]: number } } = {};

/**
*
* @param options when provided the hook will ignore it's context and use a global socket with the provided options
Expand Down Expand Up @@ -94,6 +107,7 @@ export const usePartySocket = ({
listenersCounter[host][room] ??= 0;
listenersCounter[host][room] += 1;

// socket starts closed and reconnects when there are listeners
if (socket.shouldReconnect) socket.reconnect();
return () => {
listenersCounter[host][room] -= 1;
Expand Down

0 comments on commit e4dc3b1

Please sign in to comment.