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 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 | 83x 83x 83x 83x 1x 83x 42x 1x 5x 34x 41x 5x 1x 2x 2x 36x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 8x 7x 7x 7x 7x 1x 1x 155x 2x 2x 2x 2x 2x 1x 1x 155x 2x 2x 2x 2x 2x 2x 1x 1x 155x 5x 5x 5x 5x 5x 5x 1x 1x 155x 2x 2x 2x 2x 2x 1x 1x 155x 1x 2x 1x 155x 155x 30x 1x 1x 29x 29x 27x 27x 27x 27x 27x 27x 155x 29x 29x 29x 29x 2x 29x 155x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 155x 1x 155x 2x 2x 2x 2x 1x 1x 1x 1x 155x 98x 1x 30x 30x 30x 2x 1x 1x 1x 1x 57x 1x | import { useState, useCallback } from "react";
import { useNavigate } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { ArrowLeft, Loader2 } from "lucide-react";
import { notify } from "../../../lib/notify";
import { BlogProSelector } from "../../../components/admin/blogs/BlogProSelector";
import { BlogProjectSelector } from "../../../components/admin/blogs/BlogProjectSelector";
import { Button } from "../../../components/ui/button";
import { Card } from "../../../components/ui/card";
import { slugify } from "../../../lib/slugify";
import { GENERIC_ERROR_MESSAGE } from "../../../lib/api";
import { adminApi } from "../../../lib/api/admin";
import { queryKeys } from "../../../lib/query-keys";
import { useAdminBlogCategories, useAdminBlogTags } from "../../../hooks/queries/useAdminBlogQueries";
import { useCities } from "../../../hooks/queries/useTaxonomyQueries";
import type { BlogType } from "../../../lib/api/blogs";
import type { Pro, Project } from "../../../lib/api/pro";
import type { AttributionType } from "../../../lib/api/blogs";
import { UnifiedBlogEditor } from "../../../components/blogs/UnifiedBlogEditor";
import { BlogStartChoiceScreen } from "../../../components/blogs/BlogStartChoiceScreen";
import { AdminAIPreStep } from "../../../components/admin/blogs/AdminAIPreStep";
interface SelectedPro {
pro: Pro;
attributionType: AttributionType;
}
export function AdminBlogCreatePage() {
const navigate = useNavigate();
const [view, setView] = useState<"choice" | "ai" | "scratch">("choice");
const [prefill, setPrefill] = useState<{
title?: string;
blogType?: string;
primaryKeyword?: string;
} | null>(null);
const handleDraftCreated = (blogId: string) => {
navigate({ to: "/admin/blogs/$id/edit", params: { id: blogId } });
};
if (view === "choice") {
return (
<div className="max-w-5xl mx-auto">
<div className="flex items-center gap-4 mb-6">
<button
type="button"
onClick={() => navigate({ to: "/admin/blogs" })}
className="p-2 hover:bg-background-muted rounded-md"
>
<ArrowLeft className="h-5 w-5" />
</button>
</div>
<BlogStartChoiceScreen
onStartWithAI={() => setView("ai")}
onStartFromScratch={() => setView("scratch")}
/>
</div>
);
}
if (view === "ai") {
return (
<div className="max-w-5xl mx-auto">
<AdminAIPreStep
onDraftCreated={handleDraftCreated}
onBack={() => setView("choice")}
onUseAsStartingPoint={(suggestion) => {
setPrefill({
title: suggestion.title,
blogType: suggestion.blog_type,
primaryKeyword: suggestion.primary_keyword,
});
setView("scratch");
}}
/>
</div>
);
}
// view === "scratch"
return <AdminBlogCreateScratch prefill={prefill} />;
}
function AdminBlogCreateScratch({ prefill }: { prefill?: { title?: string; blogType?: string; primaryKeyword?: string } | null }) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [saving, setSaving] = useState(false);
const [blogId, setBlogId] = useState<string | null>(null);
// Title+slug step runs before the editor: we persist the draft up front so the
// editor opens with a real blog (image picker works, no "add a title first").
const [creating, setCreating] = useState(false);
const [slugTouched, setSlugTouched] = useState(false);
// Query hooks
const { data: categories = [] } = useAdminBlogCategories();
const { data: availableTags = [] } = useAdminBlogTags();
const { data: cities = [] } = useCities();
// Form state
const [title, setTitle] = useState(prefill?.title ?? "");
const [slug, setSlug] = useState("");
const [metaDescription, setMetaDescription] = useState("");
const [content, setContent] = useState("");
const [blogType, setBlogType] = useState<BlogType>((prefill?.blogType as BlogType) ?? "general");
const [primaryKeyword, setPrimaryKeyword] = useState(prefill?.primaryKeyword ?? "");
const [secondaryKeywords, setSecondaryKeywords] = useState<string[]>([]);
const [categoryId, setCategoryId] = useState("");
const [cityId, setCityId] = useState("");
const [coverImageUrl, setCoverImageUrl] = useState<string | null>(null);
const [coverImageAlt, setCoverImageAlt] = useState("");
const [tagIds, setTagIds] = useState<string[]>([]);
const [selectedPros, setSelectedPros] = useState<SelectedPro[]>([]);
const [selectedProjects, setSelectedProjects] = useState<Project[]>([]);
// Pro/project selections persist immediately once the draft exists (it always
// does by the time these panels are visible — the title step creates it
// first). Optimistic local update with rollback on API failure.
const handleAddPro = async (pro: Pro, attributionType: AttributionType) => {
if (selectedPros.find((sv) => sv.pro.id === pro.id)) return;
setSelectedPros([...selectedPros, { pro, attributionType }]);
Iif (!blogId) return;
try {
await adminApi.addBlogPro(blogId, { proId: pro.id, attributionType });
} catch {
notify.error("Failed to add pro");
setSelectedPros((prev) => prev.filter((sv) => sv.pro.id !== pro.id));
}
};
const handleRemovePro = async (proId: string) => {
const prev = selectedPros;
setSelectedPros(selectedPros.filter((sv) => sv.pro.id !== proId));
Iif (!blogId) return;
try {
await adminApi.removeBlogPro(blogId, proId);
} catch {
notify.error("Failed to remove pro");
setSelectedPros(prev);
}
};
const handleUpdateAttributionType = async (
proId: string,
attributionType: AttributionType,
) => {
const prev = selectedPros;
setSelectedPros(
selectedPros.map((sv) =>
sv.pro.id === proId ? { ...sv, attributionType } : sv,
),
);
Iif (!blogId) return;
try {
await adminApi.updateBlogPro(blogId, proId, { attributionType });
} catch {
notify.error("Failed to update attribution");
setSelectedPros(prev);
}
};
const handleAddProject = async (project: Project) => {
Iif (selectedProjects.find((p) => p.id === project.id)) return;
const displayOrder = selectedProjects.length;
setSelectedProjects([...selectedProjects, project]);
Iif (!blogId) return;
try {
await adminApi.addBlogProject(blogId, { projectId: project.id, displayOrder });
} catch {
notify.error("Failed to add project");
setSelectedProjects((prev) => prev.filter((p) => p.id !== project.id));
}
};
const handleRemoveProject = async (projectId: string) => {
const prev = selectedProjects;
setSelectedProjects(selectedProjects.filter((p) => p.id !== projectId));
Iif (!blogId) return;
try {
await adminApi.removeBlogProject(blogId, projectId);
} catch {
notify.error("Failed to remove project");
setSelectedProjects(prev);
}
};
const handleReorderProjects = (projectIds: string[]) => {
const reordered = projectIds
.map((pid) => selectedProjects.find((p) => p.id === pid))
.filter(Boolean) as Project[];
setSelectedProjects(reordered);
};
// Determine ideaSource based on selected pros
const hasAuthorPro = selectedPros.some((sp) => sp.attributionType === "author");
const createOrUpdateBlog = useCallback(async (): Promise<string> => {
if (blogId) {
// Update existing draft
await adminApi.updateBlog(blogId, {
title,
slug: slug || undefined,
metaDescription: metaDescription || undefined,
content: content || undefined,
blogType,
primaryKeyword: primaryKeyword || undefined,
secondaryKeywords: secondaryKeywords.length > 0 ? secondaryKeywords : undefined,
categoryId: categoryId || undefined,
cityId: cityId || undefined,
featuredImageUrl: coverImageUrl ?? undefined,
featuredImageAlt: coverImageAlt || undefined,
});
return blogId;
}
// Create new blog
const authorPro = selectedPros.find((sp) => sp.attributionType === "author");
const result = await adminApi.createBlog({
title,
slug: slug || undefined,
metaDescription: metaDescription || undefined,
content: content || undefined,
blogType,
primaryKeyword: primaryKeyword || undefined,
secondaryKeywords: secondaryKeywords.length > 0 ? secondaryKeywords : undefined,
categoryId: categoryId || undefined,
cityId: cityId || undefined,
ideaSource: hasAuthorPro ? "pro_request" : "editorial",
ideaSourceProId: authorPro?.pro?.id || undefined,
tagIds: tagIds.length > 0 ? tagIds : undefined,
});
Iif (!result.data) throw new Error("Failed to create blog");
const newId = result.data.id;
setBlogId(newId);
// Add pros
for (const sv of selectedPros) {
await adminApi.addBlogPro(newId, {
proId: sv.pro.id,
attributionType: sv.attributionType,
});
}
// Add projects
for (let i = 0; i < selectedProjects.length; i++) {
await adminApi.addBlogProject(newId, {
projectId: selectedProjects[i].id,
displayOrder: i,
});
}
return newId;
}, [blogId, title, slug, metaDescription, content, blogType, primaryKeyword, secondaryKeywords, categoryId, cityId, coverImageUrl, coverImageAlt, selectedPros, selectedProjects, hasAuthorPro, tagIds]);
// Title+slug step → persist the draft, then the editor renders (blogId set).
const handleContinueMeta = async () => {
Iif (!title.trim()) {
notify.error("Title is required");
return;
}
try {
setCreating(true);
await createOrUpdateBlog();
} catch {
notify.error(GENERIC_ERROR_MESSAGE);
} finally {
setCreating(false);
}
};
const handleSave = async () => {
if (!title.trim()) {
notify.error("Title is required");
return;
}
try {
setSaving(true);
const createdId = await createOrUpdateBlog();
await queryClient.invalidateQueries({ queryKey: queryKeys.admin.blogs.all });
notify.success("Draft saved!");
// Navigate to edit page so auto-save kicks in
navigate({ to: "/admin/blogs/$id/edit", params: { id: createdId } });
} catch {
notify.error(GENERIC_ERROR_MESSAGE);
} finally {
setSaving(false);
}
};
// Persist the draft on demand so the body image gallery (and its local Upload
// tab) can open before the blog has been explicitly saved. Mirrors the lazy
// create in handleUploadCover. Returns null (not throws) when a title is
// still required, so the editor can abort quietly after the toast.
const handleEnsureBlogId = async (): Promise<string | null> => {
Eif (blogId) return blogId;
if (!title.trim()) {
notify.error("Please enter a title before adding images");
return null;
}
return await createOrUpdateBlog();
};
const handleUploadCover = async (file: File): Promise<string> => {
// Need to create blog first if it doesn't exist
let targetBlogId = blogId;
Iif (!targetBlogId) {
if (!title.trim()) {
throw new Error("Please enter a title before uploading a cover image");
}
targetBlogId = await createOrUpdateBlog();
}
const result = await adminApi.uploadBlogCover(targetBlogId, file);
if (result.data) {
const data = result.data as { imageUrl: string };
setCoverImageUrl(data.imageUrl);
return data.imageUrl;
}
throw new Error("Failed to upload cover image");
};
// Title + slug step. Collecting these up front (and persisting the draft)
// means the editor opens ready — adding an image no longer demands a title,
// and the URL slug is settled before writing starts.
if (!blogId) {
return (
<div className="max-w-5xl mx-auto">
<div className="flex items-center gap-4 mb-6">
<button
type="button"
onClick={() => navigate({ to: "/admin/blogs" })}
className="p-2 hover:bg-background-muted rounded-md"
>
<ArrowLeft className="h-5 w-5" />
</button>
<h1 className="text-xl font-bold text-foreground-default">
New Blog Post
</h1>
</div>
<div className="max-w-xl mx-auto space-y-4">
<div>
<h2 className="text-xl font-semibold mb-1">
Give your blog a title
</h2>
<p className="text-sm text-foreground-muted">
The draft is created when you continue. You can change the title,
slug, and everything else in the editor.
</p>
</div>
<label className="block">
<span className="block text-sm font-medium mb-1">
Blog Title <span className="text-error">*</span>
</span>
<input
type="text"
value={title}
onChange={(e) => {
const v = e.target.value;
setTitle(v);
Eif (!slugTouched) setSlug(slugify(v));
}}
onKeyDown={(e) => {
if (e.key === "Enter" && title.trim() && !creating) {
handleContinueMeta();
}
}}
placeholder="Title of your blog post"
className="w-full rounded-md border border-border-default bg-background-elevated px-3 py-2"
/>
</label>
<label className="block">
<span className="block text-sm font-medium mb-1">URL Slug</span>
<div className="flex items-center gap-1 rounded-md border border-border-default bg-background-elevated px-3 py-2 text-sm">
<span className="text-foreground-subtle">/blog/</span>
<input
type="text"
value={slug}
onChange={(e) => {
setSlugTouched(true);
setSlug(slugify(e.target.value));
}}
placeholder="slug"
className="flex-1 bg-transparent focus:outline-none"
/>
</div>
<p className="text-xs text-foreground-muted mt-1">
Auto-filled from the title. Edit if you want a custom URL.
</p>
</label>
<div className="flex items-center gap-3">
<Button
onClick={handleContinueMeta}
disabled={!title.trim() || creating}
>
{creating ? (
<Loader2 className="h-4 w-4 animate-spin mr-1" />
) : null}
Continue
</Button>
<Button
variant="ghost"
onClick={() => navigate({ to: "/admin/blogs" })}
>
Cancel
</Button>
</div>
</div>
</div>
);
}
return (
<UnifiedBlogEditor
mode="admin"
blogId={blogId}
proId={selectedPros[0]?.pro?.id}
title={title}
onTitleChange={setTitle}
slug={slug}
onSlugChange={setSlug}
content={content}
onContentChange={setContent}
metaDescription={metaDescription}
onMetaDescriptionChange={setMetaDescription}
primaryKeyword={primaryKeyword}
onPrimaryKeywordChange={setPrimaryKeyword}
blogType={blogType}
onBlogTypeChange={setBlogType}
coverImageUrl={coverImageUrl}
onCoverImageChange={setCoverImageUrl}
coverImageAlt={coverImageAlt}
onCoverImageAltChange={setCoverImageAlt}
categoryId={categoryId}
onCategoryChange={setCategoryId}
cityId={cityId}
onCityChange={setCityId}
secondaryKeywords={secondaryKeywords}
onSecondaryKeywordsChange={setSecondaryKeywords}
categories={categories}
cities={cities}
tagIds={tagIds}
onTagIdsChange={setTagIds}
availableTags={availableTags}
status="draft"
onSave={handleSave}
saving={saving}
onBack={() => navigate({ to: "/admin/blogs" })}
onUploadCover={handleUploadCover}
onEnsureBlogId={handleEnsureBlogId}
adminPanels={
<div className="mt-6 space-y-6">
<Card>
<div className="p-6">
<h2 className="text-lg font-semibold mb-4">Featured Pros</h2>
<BlogProSelector
selectedPros={selectedPros}
onAdd={handleAddPro}
onRemove={handleRemovePro}
onUpdateAttributionType={handleUpdateAttributionType}
/>
</div>
</Card>
<Card>
<div className="p-6">
<h2 className="text-lg font-semibold mb-4">Featured Projects</h2>
<BlogProjectSelector
selectedProjects={selectedProjects}
onAdd={handleAddProject}
onRemove={handleRemoveProject}
onReorder={handleReorderProjects}
/>
</div>
</Card>
</div>
}
/>
);
}
|