import { useEffect, useRef, useState } from "react"; import { Link, useNavigate, useParams } from "react-router-dom"; import { createPost, getPost, updateArticle, uploadMedia } from "../api"; import ArticleUploads from "../components/ArticleUploads"; import Icon from "../components/Icon"; import PageHeader from "../components/PageHeader"; import RichTextEditor from "../components/RichTextEditor"; import { ErrorState, LoadingState } from "../components/Status"; import { useAdmin } from "../components/AdminSession"; import { editableDocument, articlePlainText } from "../articleContent"; import { mainTopics as suggestedTopics } from "../topics"; const today = new Date().toISOString().slice(0, 10); const emptyDocument = { type: "doc", content: [{ type: "paragraph" }] }; const initialPost = { title: "", excerpt: "", published_at: today, read_time: 5, tags: ["AI"], accent: "mint", }; export default function JournalAdminPage() { const { slug } = useParams(); return ; } function ArticleForm({ slug }) { const navigate = useNavigate(); const { token, checking, isAdmin, signOut, openSignIn } = useAdmin(); const [loading, setLoading] = useState(Boolean(slug)); const [loadError, setLoadError] = useState(""); const [post, setPost] = useState(initialPost); const [article, setArticle] = useState(emptyDocument); const [articleText, setArticleText] = useState(""); const [banner, setBanner] = useState(null); const [attachments, setAttachments] = useState([]); const discardedUploads = useRef(new Set()); const [uploading, setUploading] = useState(false); const [customTopic, setCustomTopic] = useState(""); const [topicMessage, setTopicMessage] = useState(""); const topicInput = useRef(null); const [status, setStatus] = useState({ type: "idle", message: "" }); useEffect(() => { if (!slug) return; const controller = new AbortController(); getPost(slug, controller.signal) .then((existing) => { if (controller.signal.aborted) return; const document = editableDocument(existing.content); setPost({ title: existing.title, excerpt: existing.excerpt, published_at: existing.published_at, read_time: existing.read_time, tags: existing.tags, accent: existing.accent }); setArticle(document); setArticleText(articlePlainText(document)); setBanner(existing.banner ?? null); setAttachments(existing.attachments ?? []); }) .catch((error) => { if (error.name !== "AbortError") setLoadError(error.message); }) .finally(() => { if (!controller.signal.aborted) setLoading(false); }); return () => controller.abort(); }, [slug]); function updatePost(event) { setPost((current) => ({ ...current, [event.target.name]: event.target.value })); } function toggleTopic(topic) { if (!post.tags.includes(topic) && post.tags.length >= 6) { setTopicMessage("You can select up to six topics. Remove one to add another."); return; } setTopicMessage(""); setPost((current) => ({ ...current, tags: current.tags.includes(topic) ? current.tags.filter((item) => item !== topic) : [...current.tags, topic] })); } function addCustomTopic() { const typed = customTopic.trim(); if (!typed) return; const topic = [...suggestedTopics, ...post.tags].find((item) => item.toLowerCase() === typed.toLowerCase()) ?? typed; if (post.tags.includes(topic)) { setCustomTopic(""); setTopicMessage(`${topic} is already selected.`); topicInput.current?.focus(); return; } if (post.tags.length >= 6) { setTopicMessage("You can select up to six topics. Remove one to add another."); return; } setPost((current) => ({ ...current, tags: [...current.tags, topic] })); setCustomTopic(""); setTopicMessage(`${topic} added and selected.`); topicInput.current?.focus(); } function removeCustomTopic(topic) { setPost((current) => ({ ...current, tags: current.tags.filter((item) => item !== topic) })); setTopicMessage(`${topic} removed.`); topicInput.current?.focus(); } async function publish(event) { event.preventDefault(); if (!isAdmin || uploading || status.type === "sending") return; if (!post.tags.length) { setStatus({ type: "error", message: "Choose at least one topic." }); return; } if (articleText.length < 40) { setStatus({ type: "error", message: "Write at least 40 characters before publishing." }); return; } const payload = { ...post, read_time: Number(post.read_time), content: article, banner, attachments, discarded_uploads: [...discardedUploads.current], }; setStatus({ type: "sending", message: slug ? "Saving changes..." : "Publishing..." }); try { const created = slug ? await updateArticle(slug, payload, token) : await createPost(payload, token); setStatus({ type: "success", message: "Published. Opening the article…" }); navigate(`/blog/${created.slug}`); } catch (error) { setStatus({ type: "error", message: error.message }); } } async function uploadFile(file, purpose, options) { const uploaded = await uploadMedia(file, purpose, token, options); if (options.signal.aborted) return; if (purpose === "banner") setBanner((previous) => { if (previous) discardedUploads.current.add(previous.url); return uploaded; }); else setAttachments((current) => [...current, uploaded]); } function moveAttachment(url, targetUrl) { setAttachments((current) => { const index = current.findIndex((file) => file.url === url); const next = current.findIndex((file) => file.url === targetUrl); if (index < 0 || next < 0 || index === next) return current; const ordered = [...current]; ordered.splice(next, 0, ordered.splice(index, 1)[0]); return ordered; }); } return ( Admin : null} /> {checking && } {!checking && !isAdmin && ( Sign in to manage articles Use your admin password to create or edit a journal article. Sign in )} {isAdmin && loading && } {isAdmin && loadError && } {isAdmin && !loading && !loadError && ( {slug ? "Edit article" : "New article"} Write, format, choose the topics, and publish from one clean workspace. Sign out Title Excerpt Publish date Reading time Color Mint Blue Lavender Peach Yellow Topics {post.tags.length}/6 selected {suggestedTopics.map((topic) => ( toggleTopic(topic)} type="button" > {post.tags.includes(topic) ? "✓ " : "+ "}{topic} ))} {post.tags.filter((topic) => !suggestedTopics.includes(topic)).map((topic) => ( {topic} removeCustomTopic(topic)}> ))} Custom topic { setCustomTopic(event.target.value); setTopicMessage(""); }} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); if (event.nativeEvent.isComposing || event.keyCode === 229) return; addCustomTopic(); } }} placeholder="Add another topic" value={customTopic} /> Enter ↵ Add topic Type a topic and press Enter to add and select it. Use × on a custom topic to remove it. {topicMessage} Article { setArticle(content); setArticleText(text); }} /> {articleText.length} characters · Use headings to break longer pieces into sections. Use + Section to add a heading and a new section. Each section gets a divider and an automatic uppercase drop cap on its opening paragraph. { if (banner) discardedUploads.current.add(banner.url); setBanner(null); }} onRemoveAttachment={(url) => { discardedUploads.current.add(url); setAttachments((current) => current.filter((file) => file.url !== url)); }} /> Removed photos and files are deleted from storage when you {slug ? "save changes" : "publish"}. Cancel {status.type === "sending" ? "Saving..." : slug ? "Save changes" : "Publish article"} {status.message && {status.message}} )} ); }
Use your admin password to create or edit a journal article.
{slug ? "Edit article" : "New article"}
Write, format, choose the topics, and publish from one clean workspace.
Type a topic and press Enter to add and select it. Use × on a custom topic to remove it.
{topicMessage}
Use + Section to add a heading and a new section. Each section gets a divider and an automatic uppercase drop cap on its opening paragraph.
Removed photos and files are deleted from storage when you {slug ? "save changes" : "publish"}.
{status.message}