134 lines · 4.2 KB
import { useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { commitFile } from "~/fns/git-write";
import { useAction } from "~/hooks/use-action";
import { Button } from "./ui/Button";
import { CheckboxField, ErrorBanner, TextField } from "./ui/Field";
import { Panel } from "./ui/Primitives";

type Props = {
  owner: string;
  repo: string;
  branch: string;
  headSha: string | null;
  initialPath: string;
  previousPath: string | null;
  initialContent: string;
  allowDelete: boolean;
};

export function FileEditor({
  owner,
  repo,
  branch,
  headSha,
  initialPath,
  previousPath,
  initialContent,
  allowDelete,
}: Props) {
  const navigate = useNavigate();
  const [path, setPath] = useState(initialPath);
  const [content, setContent] = useState(initialContent);
  const [newBranch, setNewBranch] = useState(false);
  const save = useAction(commitFile, { invalidate: false });
  const verb = previousPath ? "Update" : "Create";

  async function commit(element: HTMLFormElement, deleting: boolean) {
    const form = new FormData(element);
    const message = String(form.get("message") ?? "").trim() || `${deleting ? "Delete" : verb} ${path}`;
    const branchName = String(form.get("branchName") ?? "").trim();