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.

2.6 KB
Raw Blame
import type { DeviceDirectoryBrowseResult } from '@lobechat/types';
import { useState } from 'react';
import useSWRInfinite from 'swr/infinite';

import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { deviceKeys } from '@/libs/swr/keys';
import { deviceService } from '@/services/device';

/**
 * Each device/path has its own page series, so late responses cannot replace a new location.
 * Listings stay cached per path for fast revisits, so folders created outside the picker
 * only show up after `refresh`. `enabled: false` holds the request, e.g. until a
 * sleeping cloud device is online.
 */
export const useFetchDeviceDirectory = (deviceId: string, path?: string, enabled = true) => {
  const workspaceId = useActiveWorkspaceId();
  const { data, error, isLoading, isValidating, mutate, setSize, size } = useSWRInfinite(
    (_index: number, previous: DeviceDirectoryBrowseResult | null) => {
      if (!enabled) return null;
      if (previous && !previous.nextCursor) return null;
      return deviceKeys.browseDirectory(
        workspaceId,
        deviceId,
        previous?.path ?? path,
        previous?.nextCursor,
      );
    },
    async ([, , targetDeviceId, directoryPath, cursor]: readonly [
      string,
      string | null,
      string,
      string | undefined,
      string | undefined,
    ]) => {
      const result = await deviceService.browseDirectory({
        cursor,
        deviceId: targetDeviceId,
        path: directoryPath,
      });
      // Offline / unsupported RPC is returned as null, never an empty directory.
      if (!result) throw new Error('Device directory unavailable');
      return result;
    },
    {
      revalidateFirstPage: false,
      revalidateOnFocus: false,
      shouldRetryOnError: false,
    },
  );

  const directory = data?.[0];
  const entries = data?.flatMap((page) => page?.entries ?? []) ?? [];
  const lastPage = data?.findLast(Boolean);

  const [refreshingPath, setRefreshingPath] = useState<string>();
  const refresh = async () => {
    if (!directory) return;
    const target = directory.path;
    setRefreshingPath(target);
    try {
      await mutate();
    } finally {
      setRefreshingPath((current) => (current === target ? undefined : current));
    }
  };

  return {
    directory,
    entries,
    error,
    hasMore: !!lastPage?.nextCursor,
    isLoading,
    isLoadingMore: !error && (isValidating || (!!directory && !data?.[size - 1])),
    isRefreshing: !!directory && refreshingPath === directory.path,
    loadMore: () => setSize(size + 1),
    refresh,
    retry: () => mutate(),
  };
};