refactor: unify voice user context menus into single VoiceUserContextMenu

Both the channel sidebar (VoiceChannel.tsx) and voice panel (VoiceUser.tsx)
now share one context menu with volume slider + conditional mod items,
eliminating duplicated portal/positioning/click-outside code from VoiceUser.
This commit is contained in:
Jannis Braun
2026-03-10 01:42:53 +01:00
parent f3b3c249ca
commit 3cef9cef32
3 changed files with 68 additions and 134 deletions
@@ -3,7 +3,7 @@ import { useVoiceStore } from '../../stores/voiceStore';
import { useSpaceStore, getChannelOrigin } from '../../stores/spaceStore'; import { useSpaceStore, getChannelOrigin } from '../../stores/spaceStore';
import { useAuthStore } from '../../stores/authStore'; import { useAuthStore } from '../../stores/authStore';
import { Avatar } from '../ui/Avatar'; import { Avatar } from '../ui/Avatar';
import { VoiceModContextMenu } from './VoiceModContextMenu'; import { VoiceUserContextMenu } from './VoiceUserContextMenu';
const EMPTY_VOICE_USERS: string[] = []; const EMPTY_VOICE_USERS: string[] = [];
@@ -160,11 +160,12 @@ export function VoiceChannel({ channelId, channelName, onClick, locked }: VoiceC
{/* Voice moderation context menu (portalled to body) */} {/* Voice moderation context menu (portalled to body) */}
{contextMenu && ( {contextMenu && (
<VoiceModContextMenu <VoiceUserContextMenu
targetUserId={contextMenu.userId} targetUserId={contextMenu.userId}
channelId={channelId} channelId={channelId}
position={{ x: contextMenu.x, y: contextMenu.y }} position={{ x: contextMenu.x, y: contextMenu.y }}
onClose={() => setContextMenu(null)} onClose={() => setContextMenu(null)}
isLocal={false}
/> />
)} )}
</div> </div>
+7 -113
View File
@@ -1,12 +1,9 @@
import React, { useRef, useEffect, useLayoutEffect, useState, useCallback } from 'react'; import React, { useRef, useEffect, useState, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { Avatar } from '../ui/Avatar'; import { Avatar } from '../ui/Avatar';
import { useVoiceStore } from '../../stores/voiceStore'; import { useVoiceStore } from '../../stores/voiceStore';
import { VoiceModMenuItems } from './VoiceModContextMenu'; import { VoiceUserContextMenu } from './VoiceUserContextMenu';
import { useSpaceStore } from '../../stores/spaceStore'; import { useSpaceStore } from '../../stores/spaceStore';
import { hasPermissionBit, PermissionBits } from '../../utils/permissions';
import type { UserTile } from '../../hooks/useLiveKit'; import type { UserTile } from '../../hooks/useLiveKit';
import { getChannelOrigin } from '../../stores/spaceStore';
interface VoiceUserProps { interface VoiceUserProps {
tile: UserTile; tile: UserTile;
@@ -19,7 +16,6 @@ export function VoiceUser({ tile, large }: VoiceUserProps) {
const { participant } = tile; const { participant } = tile;
const isDeafened = useVoiceStore((s) => s.isDeafened); const isDeafened = useVoiceStore((s) => s.isDeafened);
const currentVoiceChannelId = useVoiceStore((s) => s.currentVoiceChannelId); const currentVoiceChannelId = useVoiceStore((s) => s.currentVoiceChannelId);
const participantVolumes = useVoiceStore((s) => s.participantVolumes);
const isSpeaking = useVoiceStore((s) => s.speakingParticipantIds.has(participant.identity)); const isSpeaking = useVoiceStore((s) => s.speakingParticipantIds.has(participant.identity));
const serverMutedUserIds = useVoiceStore((s) => s.serverMutedUserIds); const serverMutedUserIds = useVoiceStore((s) => s.serverMutedUserIds);
const serverDeafenedUserIds = useVoiceStore((s) => s.serverDeafenedUserIds); const serverDeafenedUserIds = useVoiceStore((s) => s.serverDeafenedUserIds);
@@ -27,7 +23,6 @@ export function VoiceUser({ tile, large }: VoiceUserProps) {
const [, forceUpdate] = useState(0); const [, forceUpdate] = useState(0);
const perUserVolume = participantVolumes.get(participant.userId) ?? 100;
const isLocal = participant.isLocal; const isLocal = participant.isLocal;
const avatarUserId = participant.homeUserId ?? participant.userId; const avatarUserId = participant.homeUserId ?? participant.userId;
@@ -59,12 +54,10 @@ export function VoiceUser({ tile, large }: VoiceUserProps) {
}, [tile.lkVideoTrack]); }, [tile.lkVideoTrack]);
// Context Menu // Context Menu
const menuRef = useRef<HTMLDivElement>(null);
const [volumeMenu, setVolumeMenu] = useState<{ const [volumeMenu, setVolumeMenu] = useState<{
x: number; x: number;
y: number; y: number;
} | null>(null); } | null>(null);
const setParticipantVolume = useVoiceStore((s) => s.setParticipantVolume);
const handleContextMenu = useCallback( const handleContextMenu = useCallback(
(e: React.MouseEvent) => { (e: React.MouseEvent) => {
@@ -75,33 +68,6 @@ export function VoiceUser({ tile, large }: VoiceUserProps) {
[isLocal], [isLocal],
); );
// Click-outside dismissal — mousedown + contains check
useEffect(() => {
if (!volumeMenu) return;
const handler = (e: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
setVolumeMenu(null);
}
};
document.addEventListener('mousedown', handler);
return () => document.removeEventListener('mousedown', handler);
}, [volumeMenu]);
// Viewport-aware positioning — direct DOM mutation, no state churn
useLayoutEffect(() => {
const el = menuRef.current;
if (!volumeMenu || !el) return;
const rect = el.getBoundingClientRect();
let x = volumeMenu.x;
let y = volumeMenu.y;
if (rect.right > window.innerWidth) x = window.innerWidth - rect.width - 8;
if (rect.bottom > window.innerHeight) y = window.innerHeight - rect.height - 8;
if (x < 8) x = 8;
if (y < 8) y = 8;
el.style.left = `${x}px`;
el.style.top = `${y}px`;
}, [volumeMenu]);
return ( return (
<div <div
className={`relative bg-surface-base rounded-xl overflow-hidden flex items-center justify-center group transition-all duration-200 ${ className={`relative bg-surface-base rounded-xl overflow-hidden flex items-center justify-center group transition-all duration-200 ${
@@ -194,87 +160,15 @@ export function VoiceUser({ tile, large }: VoiceUserProps) {
</div> </div>
</div> </div>
{volumeMenu && !isLocal && ReactDOM.createPortal( {volumeMenu && currentVoiceChannelId && (
<div <VoiceUserContextMenu
ref={menuRef}
className="fixed z-[200] bg-surface-elevated rounded-md shadow-elevation-high min-w-[200px] animate-fade-in"
style={{ left: volumeMenu.x, top: volumeMenu.y }}
>
{/* Moderation options (renders nothing if no perms) */}
{currentVoiceChannelId && (
<VoiceModSection
targetUserId={participant.userId} targetUserId={participant.userId}
channelId={currentVoiceChannelId} channelId={currentVoiceChannelId}
onAction={() => setVolumeMenu(null)} position={volumeMenu}
onClose={() => setVolumeMenu(null)}
isLocal={isLocal}
/> />
)} )}
{/* Volume slider */}
<div className="p-3">
<div className="text-xs text-txt-tertiary mb-2 font-medium uppercase tracking-wider">
User Volume
</div>
<div className="flex items-center gap-2">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="currentColor"
className="text-txt-tertiary flex-shrink-0"
>
<path d="M3 9v6h4l5 5V4L7 9H3z" />
</svg>
<input
type="range"
min="0"
max="200"
value={perUserVolume}
onChange={(e) =>
setParticipantVolume(
participant.userId,
parseInt(e.target.value),
)
}
className="flex-1 accent-accent-primary h-1"
/>
<span className="text-xs text-txt-secondary min-w-[32px] text-right">
{perUserVolume}%
</span>
</div>
</div>
</div>,
document.body,
)}
</div> </div>
); );
} }
/** Renders moderation items + divider only when the user has mod perms. */
function VoiceModSection({ targetUserId, channelId, onAction }: {
targetUserId: string;
channelId: string;
onAction: () => void;
}) {
const spacePermissions = useSpaceStore((s) => s.spacePermissions);
const currentSpaceId = useSpaceStore((s) => s.currentSpaceId);
const myPerms = currentSpaceId ? spacePermissions.get(currentSpaceId) : undefined;
const hasMod =
hasPermissionBit(myPerms, PermissionBits.MUTE_MEMBERS) ||
hasPermissionBit(myPerms, PermissionBits.DEAFEN_MEMBERS) ||
hasPermissionBit(myPerms, PermissionBits.MOVE_MEMBERS);
if (!hasMod) return null;
return (
<>
<div className="py-1.5">
<VoiceModMenuItems
targetUserId={targetUserId}
channelId={channelId}
onAction={onAction}
/>
</div>
<div className="h-px bg-white/[0.06] mx-1.5" />
</>
);
}
@@ -178,6 +178,7 @@ function MoveToSubmenu({ channels, onMove, btnClass, btnStyle }: MoveToSubmenuPr
style={{ left: -9999, top: -9999 }} style={{ left: -9999, top: -9999 }}
onMouseEnter={cancelCloseTimer} onMouseEnter={cancelCloseTimer}
onMouseLeave={startCloseTimer} onMouseLeave={startCloseTimer}
onMouseDown={(e) => e.stopPropagation()}
> >
{channels.map((ch) => ( {channels.map((ch) => (
<button <button
@@ -201,19 +202,20 @@ function MoveToSubmenu({ channels, onMove, btnClass, btnStyle }: MoveToSubmenuPr
// ─── Standalone portalled context menu ───────────────────────────────────────── // ─── Standalone portalled context menu ─────────────────────────────────────────
interface VoiceModContextMenuProps { interface VoiceUserContextMenuProps {
targetUserId: string; targetUserId: string;
channelId: string; channelId: string;
position: { x: number; y: number }; position: { x: number; y: number };
onClose: () => void; onClose: () => void;
isLocal: boolean;
} }
/** /**
* Full standalone moderation context menu rendered via createPortal to document.body. * Unified voice user context menu rendered via createPortal to document.body.
* Escapes any CSS containing-block / overflow clipping from parent transforms. * Shows moderation items (if perms) + volume slider (always, for remote users).
* Includes viewport-aware positioning and click-outside dismissal. * Includes viewport-aware positioning and click-outside dismissal.
*/ */
export function VoiceModContextMenu({ targetUserId, channelId, position, onClose }: VoiceModContextMenuProps) { export function VoiceUserContextMenu({ targetUserId, channelId, position, onClose, isLocal }: VoiceUserContextMenuProps) {
const menuRef = useRef<HTMLDivElement>(null); const menuRef = useRef<HTMLDivElement>(null);
const spacePermissions = useSpaceStore((s) => s.spacePermissions); const spacePermissions = useSpaceStore((s) => s.spacePermissions);
@@ -224,9 +226,12 @@ export function VoiceModContextMenu({ targetUserId, channelId, position, onClose
const canMoveMembers = hasPermissionBit(myPerms, PermissionBits.MOVE_MEMBERS); const canMoveMembers = hasPermissionBit(myPerms, PermissionBits.MOVE_MEMBERS);
const hasModPerms = canMuteMembers || canDeafenMembers || canMoveMembers; const hasModPerms = canMuteMembers || canDeafenMembers || canMoveMembers;
// Click-outside dismissal — always called (hooks must be unconditional) const participantVolumes = useVoiceStore((s) => s.participantVolumes);
const setParticipantVolume = useVoiceStore((s) => s.setParticipantVolume);
const perUserVolume = participantVolumes.get(targetUserId) ?? 100;
// Click-outside dismissal
useEffect(() => { useEffect(() => {
if (!hasModPerms) return;
const handler = (e: MouseEvent) => { const handler = (e: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(e.target as Node)) { if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
onClose(); onClose();
@@ -234,12 +239,12 @@ export function VoiceModContextMenu({ targetUserId, channelId, position, onClose
}; };
document.addEventListener('mousedown', handler); document.addEventListener('mousedown', handler);
return () => document.removeEventListener('mousedown', handler); return () => document.removeEventListener('mousedown', handler);
}, [hasModPerms, onClose]); }, [onClose]);
// Viewport-aware positioning — direct DOM mutation, no extra state/render // Viewport-aware positioning — direct DOM mutation, no extra state/render
useLayoutEffect(() => { useLayoutEffect(() => {
const el = menuRef.current; const el = menuRef.current;
if (!hasModPerms || !el) return; if (!el) return;
const rect = el.getBoundingClientRect(); const rect = el.getBoundingClientRect();
let x = position.x; let x = position.x;
let y = position.y; let y = position.y;
@@ -249,21 +254,55 @@ export function VoiceModContextMenu({ targetUserId, channelId, position, onClose
if (y < 8) y = 8; if (y < 8) y = 8;
el.style.left = `${x}px`; el.style.left = `${x}px`;
el.style.top = `${y}px`; el.style.top = `${y}px`;
}, [position, hasModPerms]); }, [position]);
if (!hasModPerms) return null; if (isLocal) return null;
return ReactDOM.createPortal( return ReactDOM.createPortal(
<div <div
ref={menuRef} ref={menuRef}
className="fixed z-[200] bg-surface-elevated rounded-md shadow-elevation-high py-1.5 min-w-[180px] max-h-[calc(100vh-16px)] overflow-y-auto scrollbar-thin animate-fade-in" className="fixed z-[200] bg-surface-elevated rounded-md shadow-elevation-high min-w-[200px] max-h-[calc(100vh-16px)] overflow-y-auto scrollbar-thin animate-fade-in"
style={{ left: position.x, top: position.y }} style={{ left: position.x, top: position.y }}
> >
{hasModPerms && (
<>
<div className="py-1.5">
<VoiceModMenuItems <VoiceModMenuItems
targetUserId={targetUserId} targetUserId={targetUserId}
channelId={channelId} channelId={channelId}
onAction={onClose} onAction={onClose}
/> />
</div>
<div className="h-px bg-white/[0.06] mx-1.5" />
</>
)}
<div className="p-3">
<div className="text-xs text-txt-tertiary mb-2 font-medium uppercase tracking-wider">
User Volume
</div>
<div className="flex items-center gap-2">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="currentColor"
className="text-txt-tertiary flex-shrink-0"
>
<path d="M3 9v6h4l5 5V4L7 9H3z" />
</svg>
<input
type="range"
min="0"
max="200"
value={perUserVolume}
onChange={(e) => setParticipantVolume(targetUserId, parseInt(e.target.value))}
className="flex-1 accent-accent-primary h-1"
/>
<span className="text-xs text-txt-secondary min-w-[32px] text-right">
{perUserVolume}%
</span>
</div>
</div>
</div>, </div>,
document.body, document.body,
); );