41 lines · 1.6 KB
import { useState } from "react";

const MAX_FILES_PER_DROP = 5;

type UploadState = { status: "idle" } | { status: "uploading"; count: number } | { status: "error"; message: string };

async function uploadOne(owner: string, repo: string, file: File): Promise<string> {
  const response = await fetch(`/${owner}/${repo}/attachments?name=${encodeURIComponent(file.name)}`, {
    method: "POST",
    headers: { "x-gitfor-csrf": "1", "content-type": file.type || "application/octet-stream" },
    body: file,
  });
  const payload: { markdown?: string; error?: string } = await response.json();
  if (!response.ok || !payload.markdown) throw new Error(payload.error ?? `Upload of ${file.name} failed`);
  return payload.markdown;
}

/** Uploads dropped or pasted files as repo attachments and yields markdown snippets to insert. */
export function useAttachmentUpload(owner: string | undefined, repo: string | undefined) {
  const [state, setState] = useState<UploadState>({ status: "idle" });
  const enabled = Boolean(owner && repo);

  async function upload(files: FileList | File[]): Promise<string[]> {
    if (!owner || !repo) return [];
    const list = [...files].slice(0, MAX_FILES_PER_DROP);
    if (list.length === 0) return [];
    setState({ status: "uploading", count: list.length });
    try {
      const snippets: string[] = [];
      for (const file of list) snippets.push(await uploadOne(owner, repo, file));
      setState({ status: "idle" });
      return snippets;
    } catch (error) {
      setState({ status: "error", message: error instanceof Error ? error.message : "Upload failed" });
      return [];
    }
  }

  return { enabled, state, upload };
}