export interface VoiceChannelTreeSource { id: string; depth: number; } export interface VoiceChannelTreeNode { channel: T; depth: number; children: VoiceChannelTreeNode[]; } const MAX_NESTED_CHANNEL_DEPTH = 12; /** Rebuilds a nested view from the host's safe, preorder TeamSpeak channel list. */ export function buildVoiceChannelTree( channels: readonly T[], ): VoiceChannelTreeNode[] { const roots: VoiceChannelTreeNode[] = []; const parentStack: VoiceChannelTreeNode[] = []; const seen = new Set(); for (const channel of channels) { if (!channel.id || seen.has(channel.id)) continue; seen.add(channel.id); const requestedDepth = Number.isFinite(channel.depth) ? Math.max(0, Math.floor(channel.depth)) : 0; const depth = Math.min(requestedDepth, MAX_NESTED_CHANNEL_DEPTH, parentStack.length); const node: VoiceChannelTreeNode = { channel, depth, children: [] }; if (depth === 0) roots.push(node); else parentStack[depth - 1].children.push(node); parentStack.length = depth; parentStack.push(node); } return roots; } /** Filters visible channel names while retaining ancestors of matching nested channels. */ export function filterVoiceChannelTree( nodes: readonly VoiceChannelTreeNode[], query: string, ): VoiceChannelTreeNode[] { const needle = query.trim().toLocaleLowerCase(); if (!needle) return [...nodes]; return nodes.flatMap((node) => { const children = filterVoiceChannelTree(node.children, needle); return node.channel.name.toLocaleLowerCase().includes(needle) || children.length ? [{ ...node, children }] : []; }); }