import { useLingui } from "@lingui/react/macro"; import { useEffect, useState } from "react"; import { type ArtifactTarget, fetchArtifactBytes } from "../lib/artifact-open"; export type ArtifactBytesState = | { status: "loading" } | { status: "ready"; bytes: Uint8Array } | { status: "error"; message: string }; export function useArtifactBytes(target: ArtifactTarget, artifactId: string): ArtifactBytesState { const { t } = useLingui(); const [state, setState] = useState({ status: "loading" }); const targetBotId = "botId" in target ? target.botId : undefined; const targetGroupId = "groupId" in target ? target.groupId : undefined; useEffect(() => { let cancelled = false; setState({ status: "loading" }); const artifactTarget: ArtifactTarget = targetBotId !== undefined ? { botId: targetBotId } : { groupId: targetGroupId! }; void fetchArtifactBytes(artifactTarget, artifactId) .then((bytes) => { if (!cancelled) setState({ status: "ready", bytes }); }) .catch((error) => { if (cancelled) return; setState({ status: "error", message: error instanceof Error ? error.message : t`Could not load this file.`, }); }); return () => { cancelled = true; }; }, [artifactId, targetBotId, targetGroupId, t]); return state; }