Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | "use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import {
Container,
Paper,
Typography,
TextField,
Button,
FormControl,
InputLabel,
Select,
MenuItem,
Box,
Alert,
CircularProgress,
Chip,
Stack,
} from "@mui/material";
import Navbar from "@/components/Navbar";
import { useSession } from "next-auth/react";
interface Category {
_id: string;
name: string;
slug: string;
}
export default function NewPostPage() {
const router = useRouter();
const { status } = useSession();
const [categories, setCategories] = useState<Category[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [tagInput, setTagInput] = useState("");
const [formData, setFormData] = useState({
categoryId: "",
title: "",
summary: "",
body: "",
tags: [] as string[],
visibility: "public",
allowComments: true,
});
useEffect(() => {
if (status === "authenticated") {
fetchCategories();
}
}, [status]);
const fetchCategories = async () => {
try {
const response = await fetch("/anotoki/api/categories");
if (!response.ok) throw new Error("Failed to fetch categories");
const result = await response.json();
setCategories(result.data);
} catch (err) {
console.error("Error fetching categories:", err);
setError("カテゴリの取得に失敗しました");
}
};
const handleChange = (field: string, value: string | boolean) => {
setFormData((prev) => ({ ...prev, [field]: value }));
};
const handleAddTag = () => {
if (tagInput.trim() && !formData.tags.includes(tagInput.trim())) {
setFormData((prev) => ({
...prev,
tags: [...prev.tags, tagInput.trim()],
}));
setTagInput("");
}
};
const handleRemoveTag = (tagToRemove: string) => {
setFormData((prev) => ({
...prev,
tags: prev.tags.filter((tag) => tag !== tagToRemove),
}));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setLoading(true);
try {
const response = await fetch("/anotoki/api/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error?.message || "Failed to create post");
}
const result = await response.json();
router.push(`/posts/${result.data._id}`);
} catch (err) {
setError(err instanceof Error ? err.message : "投稿の作成に失敗しました");
setLoading(false);
}
};
if (status === "loading") {
return (
<Box display="flex" justifyContent="center" alignItems="center" minHeight="100vh">
<CircularProgress />
</Box>
);
}
return (
<>
<Navbar />
<Container maxWidth="md" sx={{ mt: 4, mb: 4 }}>
<Paper sx={{ p: 4 }}>
<Typography variant="h4" component="h1" gutterBottom>
新しい投稿を作成
</Typography>
{error && (
<Alert severity="error" sx={{ mb: 2 }}>
{error}
</Alert>
)}
<form onSubmit={handleSubmit}>
<FormControl fullWidth sx={{ mb: 2 }}>
<InputLabel>カテゴリ *</InputLabel>
<Select
value={formData.categoryId}
label="カテゴリ *"
onChange={(e) => handleChange("categoryId", e.target.value)}
required
>
{categories.map((category) => (
<MenuItem key={category._id} value={category._id}>
{category.name}
</MenuItem>
))}
</Select>
</FormControl>
<TextField
fullWidth
label="タイトル *"
value={formData.title}
onChange={(e) => handleChange("title", e.target.value)}
required
inputProps={{ maxLength: 100 }}
sx={{ mb: 2 }}
/>
<TextField
fullWidth
label="要約 *"
value={formData.summary}
onChange={(e) => handleChange("summary", e.target.value)}
required
multiline
rows={2}
inputProps={{ maxLength: 280 }}
helperText={`${formData.summary.length}/280`}
sx={{ mb: 2 }}
/>
<TextField
fullWidth
label="本文 *"
value={formData.body}
onChange={(e) => handleChange("body", e.target.value)}
required
multiline
rows={10}
sx={{ mb: 2 }}
/>
<Box sx={{ mb: 2 }}>
<TextField
fullWidth
label="タグを追加"
value={tagInput}
onChange={(e) => setTagInput(e.target.value)}
onKeyPress={(e) => {
if (e.key === "Enter") {
e.preventDefault();
handleAddTag();
}
}}
helperText="Enter キーでタグを追加"
/>
<Stack direction="row" spacing={1} sx={{ mt: 1, flexWrap: "wrap", gap: 1 }}>
{formData.tags.map((tag) => (
<Chip key={tag} label={tag} onDelete={() => handleRemoveTag(tag)} />
))}
</Stack>
</Box>
<FormControl fullWidth sx={{ mb: 2 }}>
<InputLabel>公開設定</InputLabel>
<Select
value={formData.visibility}
label="公開設定"
onChange={(e) => handleChange("visibility", e.target.value)}
>
<MenuItem value="public">公開</MenuItem>
<MenuItem value="members">会員のみ</MenuItem>
<MenuItem value="private">非公開</MenuItem>
</Select>
</FormControl>
<Box sx={{ display: "flex", gap: 2 }}>
<Button
type="submit"
variant="contained"
size="large"
disabled={loading}
fullWidth
>
{loading ? <CircularProgress size={24} /> : "投稿する"}
</Button>
<Button
variant="outlined"
size="large"
onClick={() => router.back()}
disabled={loading}
>
キャンセル
</Button>
</Box>
</form>
</Paper>
</Container>
</>
);
}
|