Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

3.7 KB
Raw Blame
import { AGENT_CHAT_TOPIC_URL, AGENT_CHAT_URL } from '@lobechat/const';
import { useLayoutEffect, useRef } from 'react';
import { useLocation, useParams, useSearchParams } from 'react-router';

import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useQueryState } from '@/hooks/useQueryParam';
import { useChatStore } from '@/store/chat';

const getSearchSuffix = (searchParams: URLSearchParams) => {
  const search = searchParams.toString();

  return search ? `?${search}` : '';
};

interface ChatRouteSyncOptions {
  getConversationPath?: (agentId: string) => string;
  getTopicPath?: (agentId: string, topicId: string) => string;
}

export const useChatRouteSync = (options: ChatRouteSyncOptions = {}) => {
  const location = useLocation();
  const navigate = useWorkspaceAwareNavigate();
  const params = useParams<{ aid?: string; topicId?: string }>();
  const [searchParams] = useSearchParams();
  const [thread, setThread] = useQueryState('thread', { history: 'replace', throttleMs: 500 });
  const routeTopicId = params.topicId;

  useLayoutEffect(() => {
    const target = routeTopicId ?? null;
    if (useChatStore.getState().activeTopicId !== target) {
      useChatStore.setState({ activeTopicId: target! }, false, 'ChatHydration/syncTopicFromUrl');
    }
  }, [routeTopicId]);

  useLayoutEffect(() => {
    const target = thread ?? null;
    if (useChatStore.getState().activeThreadId !== target) {
      useChatStore.setState({ activeThreadId: target! }, false, 'ChatHydration/syncThreadFromUrl');
    }
  }, [thread]);

  const locationRef = useRef(location);
  const paramsRef = useRef(params);
  const searchParamsRef = useRef(searchParams);

  locationRef.current = location;
  paramsRef.current = params;
  searchParamsRef.current = searchParams;

  useLayoutEffect(() => {
    const unsubscribeTopic = useChatStore.subscribe(
      (state) => state.activeTopicId,
      (state) => {
        const { aid, topicId } = paramsRef.current;
        const routeAgentId = aid || useChatStore.getState().activeAgentId;

        if (!routeAgentId || state === topicId) return;

        if (state === undefined && topicId) {
          useChatStore.setState(
            { activeTopicId: topicId },
            false,
            'ChatHydration/restoreTopicAfterScopedReset',
          );
          return;
        }

        const nextSearchParams = new URLSearchParams(searchParamsRef.current);
        nextSearchParams.delete('topic');
        // `?message=` is a one-shot send for the conversation the link opened.
        // Carried onto the topic that send created, a reload would send it again.
        nextSearchParams.delete('message');

        const nextPath = state
          ? options.getTopicPath?.(routeAgentId, state) || AGENT_CHAT_TOPIC_URL(routeAgentId, state)
          : options.getConversationPath?.(routeAgentId) || AGENT_CHAT_URL(routeAgentId);
        const nextUrl = `${nextPath}${getSearchSuffix(nextSearchParams)}${locationRef.current.hash}`;
        const currentUrl = `${locationRef.current.pathname}${locationRef.current.search}${locationRef.current.hash}`;

        if (currentUrl !== nextUrl) navigate(nextUrl, { replace: true });
      },
    );
    const unsubscribeThread = useChatStore.subscribe(
      (state) => state.activeThreadId,
      (state) => {
        // A topic switch clears null to undefined. Avoid a redundant query update
        // against the old pathname, which would undo navigation to the edited topic.
        if ((state || null) === searchParamsRef.current.get('thread')) return;
        setThread(state || null);
      },
    );

    return () => {
      unsubscribeTopic();
      unsubscribeThread();
    };
  }, [navigate, options.getConversationPath, options.getTopicPath, setThread]);
};