|
| 1 | +import { Avatar, Box, Divider, Group, Stack, Text } from '@mantine/core'; |
| 2 | +import { IconCircleFilled } from '@tabler/icons-react'; |
| 3 | +import { useMemo } from 'react'; |
| 4 | +import { useAllPeers } from '../peersSlice'; |
| 5 | +import { SENDER_ID } from '../realtimeSyncTypes'; |
| 6 | +import { DeviceIdenticon } from './DeviceIdenticon'; |
| 7 | +import classes from './OnlinePeersList.module.css'; |
| 8 | + |
| 9 | +const IDENTICON_SIZE = 14; |
| 10 | + |
| 11 | +export function OnlinePeersList() { |
| 12 | + const peers = useAllPeers(); |
| 13 | + |
| 14 | + const leaderSenderId = useMemo(() => { |
| 15 | + if (peers.length === 0) return null; |
| 16 | + return [...peers.map(p => p.senderId)].sort()[0]; |
| 17 | + }, [peers]); |
| 18 | + |
| 19 | + const groupedByUser = useMemo(() => { |
| 20 | + const groups = new Map< |
| 21 | + string, |
| 22 | + { |
| 23 | + userId: string; |
| 24 | + displayName: string; |
| 25 | + avatarUrl: string | null; |
| 26 | + devices: typeof peers; |
| 27 | + } |
| 28 | + >(); |
| 29 | + for (const p of peers) { |
| 30 | + const existing = groups.get(p.userId); |
| 31 | + if (existing) { |
| 32 | + existing.devices.push(p); |
| 33 | + } else { |
| 34 | + groups.set(p.userId, { |
| 35 | + userId: p.userId, |
| 36 | + displayName: p.displayName, |
| 37 | + avatarUrl: p.avatarUrl, |
| 38 | + devices: [p], |
| 39 | + }); |
| 40 | + } |
| 41 | + } |
| 42 | + return Array.from(groups.values()); |
| 43 | + }, [peers]); |
| 44 | + |
| 45 | + return ( |
| 46 | + <Stack gap="xs" miw={220}> |
| 47 | + {groupedByUser.map((group, idx) => ( |
| 48 | + <Box key={group.userId || group.displayName}> |
| 49 | + {idx > 0 && <Divider mb="xs" />} |
| 50 | + <Group gap="xs" wrap="nowrap" mb={4}> |
| 51 | + <Avatar src={group.avatarUrl} size={22} radius="xl"> |
| 52 | + {group.displayName.charAt(0).toUpperCase()} |
| 53 | + </Avatar> |
| 54 | + <Text size="sm" fw={500}> |
| 55 | + {group.displayName} |
| 56 | + {group.devices.some(d => d.senderId === SENDER_ID) && ( |
| 57 | + <Text span size="xs" c="dimmed"> |
| 58 | + {' '} |
| 59 | + (you) |
| 60 | + </Text> |
| 61 | + )} |
| 62 | + </Text> |
| 63 | + </Group> |
| 64 | + <Stack gap={4} pl={30}> |
| 65 | + {group.devices.map(device => ( |
| 66 | + <Group key={device.senderId} gap={6} wrap="nowrap"> |
| 67 | + <Box className={classes.identiconBadge}> |
| 68 | + <DeviceIdenticon |
| 69 | + seed={device.deviceName} |
| 70 | + size={IDENTICON_SIZE} |
| 71 | + /> |
| 72 | + </Box> |
| 73 | + <Text size="xs" c="dimmed"> |
| 74 | + {device.deviceName || 'Unknown device'} |
| 75 | + </Text> |
| 76 | + {device.senderId === leaderSenderId && ( |
| 77 | + <IconCircleFilled |
| 78 | + size={8} |
| 79 | + color="var(--mantine-color-green-5)" |
| 80 | + title="Leader" |
| 81 | + /> |
| 82 | + )} |
| 83 | + </Group> |
| 84 | + ))} |
| 85 | + </Stack> |
| 86 | + </Box> |
| 87 | + ))} |
| 88 | + </Stack> |
| 89 | + ); |
| 90 | +} |
0 commit comments