import { useEffect, useRef } from "react"; import { Form, Link, redirect, useNavigation } from "react-router"; import type { Route } from "./+types/home"; import { createPost, deletePost, listPosts, listCredentials } from "~/lib/db.server"; import { renderMarkdown } from "~/lib/md.server"; import { getSession, commitSession } from "~/lib/session.server"; export async function loader({ request }: Route.LoaderArgs) { const session = await getSession(request.headers.get("Cookie")); const isAuthenticated = session.get("authenticated") === true; const hasCredentials = listCredentials().length > 0; const posts = listPosts(); return { posts: posts.map((p) => ({ ...p, html: renderMarkdown(p.content) })), isAuthenticated, hasCredentials, }; } export async function action({ request }: Route.ActionArgs) { const session = await getSession(request.headers.get("Cookie")); if (session.get("authenticated") !== true) { throw new Response("Unauthorized", { status: 401 }); } const form = await request.formData(); const intent = String(form.get("intent") ?? "create"); if (intent === "delete") { const id = String(form.get("id") ?? ""); if (id) deletePost(id); return redirect("/", { headers: { "Set-Cookie": await commitSession(session) }, }); } const content = String(form.get("content") ?? "").trim(); if (!content) return { error: "内容を入力してください", content }; if (content.length > 10000) return { error: "投稿が長すぎます(最大10,000文字)", content }; createPost({ id: crypto.randomUUID(), content }); return redirect("/", { headers: { "Set-Cookie": await commitSession(session) }, }); } export default function Home({ loaderData, actionData }: Route.ComponentProps) { const { posts, isAuthenticated, hasCredentials } = loaderData; const navigation = useNavigation(); const isSubmitting = navigation.state === "submitting"; const formRef = useRef(null); const wasSubmitting = useRef(false); useEffect(() => { if (navigation.state === "submitting") wasSubmitting.current = true; if (wasSubmitting.current && navigation.state === "idle" && !actionData?.error) { formRef.current?.reset(); wasSubmitting.current = false; } }, [navigation.state, actionData?.error]); return (

log

{isAuthenticated && (