Skip to content

Instantly share code, notes, and snippets.

@32teeth
Created March 8, 2024 22:24
Show Gist options
  • Save 32teeth/6f37bd607ac1742560eb6588ed45b186 to your computer and use it in GitHub Desktop.
Save 32teeth/6f37bd607ac1742560eb6588ed45b186 to your computer and use it in GitHub Desktop.
const PORTS = new Map();
const CLIENTS = new Map();
onconnect = (e) => {
const port = e.ports[0];
PORTS.set(port, { port: port, uuid: this.uuid, username: null});
port.start();
port.onmessage = (e) => {
const { data } = e;
const { type } = data;
if (type !== null) {
switch (data.type) {
case 'subscribe':
subscribe(port, {...data});
break;
case 'unsubscribe':
unsubscribe(port, {...data});
break;
case 'broadcast':
broadcast(port, {...data});
break;
default:
break;
}
}
}
}
const subscribe = (port, { space, project, username, uuid }) => {
if (!CLIENTS.has(space)) {
CLIENTS.set(space, new Map());
}
if (!CLIENTS.get(space).has(project)) {
CLIENTS.get(space).set(project, new Set());
}
const spaceMap = CLIENTS.get(space);
spaceMap.get(project).add({ port, username, uuid });
spaceMap.get(project).forEach((client) => {
const { port: clientPort } = client;
if (clientPort !== port) {
clientPort.postMessage({
toast: { type: 'info', message: `<strong>${username}</strong><br/> Has joined ${space} ${project}`, dismissable: true, delay: 2500 },
activity : { type: 'subscribe', username, uuid, space, project },
clients: Array.from(spaceMap.get(project)).map((client) => {
return { username: client.username, uuid: client.uuid }
})
});
} else {
clientPort.postMessage({
toast: { type: 'success', message: `<strong>Welcome ${username}</strong><br/>You have been subscribeed to ${space} ${project}`, dismissable: true, delay: 2500 },
clients: Array.from(spaceMap.get(project)).map((client) => {
return { username: client.username, uuid: client.uuid }
})
});
}
});
};
const unsubscribe = (port, { space, project, username, uuid }) => {
PORTS.delete(port);
const notify = (clients) => { // Define notify function before using it
clients.forEach((client) => {
const { port: clientPort } = client;
clientPort.postMessage({
toast: { type: 'warning', message: `<strong>${username}</strong><br/> Has left ${space} ${project}`, dismissable: true, delay: 2500 }
});
});
};
CLIENTS.forEach((projects, space) => {
projects.forEach((clients, project) => {
clients.forEach((client) => {
if (client.port === port) {
clients.delete(client);
notify(clients);
}
});
});
});
};
const broadcast = (port, { space, project, username, uuid, message }) => {
const spaceMap = CLIENTS.get(space);
spaceMap.get(project).forEach((client) => {
if (client.port !== port) {
client.port.postMessage({
toast: { type: 'info', message: `<strong>${message}</strong><br/>${username}`, dismissable: true, delay: 2500 }
});
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment