import { useRouter } from 'next/router' import { Select } from './form' import { SSR } from '../lib/constants' import { SUBS } from '../fragments/subs' import { useQuery } from '@apollo/client' import { useEffect, useState } from 'react' import styles from './sub-select.module.css' export function SubSelectInitial ({ sub }) { const router = useRouter() sub = sub || router.query.sub || 'pick territory' return { sub } } export function useSubs ({ prependSubs = [], sub, filterSubs = () => true, appendSubs = [] }) { const { data } = useQuery(SUBS, SSR ? {} : { pollInterval: 300000, nextFetchPolicy: 'cache-and-network' }) const [subs, setSubs] = useState([ ...prependSubs.filter(s => s !== sub), sub, ...appendSubs.filter(s => s !== sub)]) useEffect(() => { if (!data) return const joined = data.subs.filter(filterSubs).filter(s => !s.meMuteSub).map(s => s.name) const muted = data.subs.filter(filterSubs).filter(s => s.meMuteSub).map(s => s.name) const mutedSection = muted.length ? [{ label: 'muted', items: muted }] : [] setSubs([ ...prependSubs, ...joined, ...mutedSection, ...appendSubs]) }, [data]) return subs } export default function SubSelect ({ prependSubs, sub, onChange, large, appendSubs, filterSubs, className, ...props }) { const router = useRouter() const subs = useSubs({ prependSubs, sub, filterSubs, appendSubs }) const valueProps = props.noForm ? { value: sub } : { overrideValue: sub } // If logged out user directly visits a nsfw sub, subs will not contain `sub`, so manually add it // to display the correct sub name in the sub selector const subItems = !sub || subs.find((s) => s === sub) ? subs : [sub].concat(subs) return (