All files / src/components/blogs UnifiedBlogEditor.tsx

96.55% Statements 84/87
91.01% Branches 81/89
100% Functions 19/19
97.53% Lines 79/81

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 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507                                                                                                                                                                                                                                                  94x 94x 94x 94x 94x 94x         94x   94x   2x   2x 2x           94x   1x   1x           1x           94x     14708x   94x   94x 94x 94x 94x     94x 66x 6x 1x   6x 6x     94x 12x 12x 12x 12x   12x 12x         10x   2x   12x       94x 4x 4x 4x 4x   4x 3x   2x 2x 1x 1x 1x     1x               1x         1x 1x 1x       3x     94x 1x 1x     94x 2x 2x 2x           94x 3x 1x   1x 1x   2x 1x 1x   1x     94x                                                                                     6x                                                                                                                               2x                 1x                                                                                             6x                                                             6x               1x                                                                        
import { type ReactNode, useState, useRef, useCallback, useMemo, useEffect } from "react";
import {
	Save,
	Send,
	Loader2,
	ArrowLeft,
	PanelRight,
	Trash2,
	AlertTriangle,
	X,
} from "lucide-react";
import { slugify } from "../../lib/slugify";
import { notify } from "../../lib/notify";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
import { RichTextEditor } from "./RichTextEditor";
import { SEOSidebar } from "./SEOSidebar";
import { AIResultPreview } from "./AIResultPreview";
import { SaveStatusIndicator } from "./SaveStatusIndicator";
import { aiApi } from "../../lib/api/ai";
import { getErrorMessage } from "../../lib/api";
import type { CopilotAction } from "./EditorToolbar";
import type { BlogType, BlogCategory, BlogTag, BlogStatus } from "../../lib/api/blogs";
import type { SaveStatus } from "../../hooks/useAutoSave";
 
interface UnifiedBlogEditorProps {
	mode: "pro" | "admin";
	blogId: string;
	proId?: string;
	// Content state (controlled)
	title: string;
	onTitleChange: (t: string) => void;
	slug: string;
	onSlugChange: (s: string) => void;
	content: string;
	onContentChange: (c: string) => void;
	metaDescription: string;
	onMetaDescriptionChange: (d: string) => void;
	primaryKeyword: string;
	onPrimaryKeywordChange: (k: string) => void;
	blogType: BlogType;
	onBlogTypeChange: (t: BlogType) => void;
	coverImageUrl: string | null;
	onCoverImageChange: (url: string | null) => void;
	coverImageAlt: string;
	onCoverImageAltChange: (a: string) => void;
	// Admin-only metadata
	categoryId?: string;
	onCategoryChange?: (id: string) => void;
	cityId?: string;
	onCityChange?: (id: string) => void;
	secondaryKeywords?: string[];
	onSecondaryKeywordsChange?: (kw: string[]) => void;
	categories?: BlogCategory[];
	cities?: { id: string; name: string }[];
	tagIds?: string[];
	onTagIdsChange?: (ids: string[]) => void;
	availableTags?: BlogTag[];
	// Status
	status: BlogStatus;
	// Auto-save
	saveStatus?: SaveStatus;
	lastSavedAt?: Date | null;
	// Actions
	onSave: () => void;
	onPublish?: () => void;
	onDelete?: () => void;
	saving: boolean;
	// Back navigation
	onBack: () => void;
	// Admin-only slots
	adminPanels?: ReactNode;
	/** Override cover image upload for admin mode */
	onUploadCover?: (file: File) => Promise<string>;
	/** Optional banner rendered below the sticky header (e.g. unpublished profile warning) */
	topBanner?: ReactNode;
}
 
export function UnifiedBlogEditor({
	mode,
	blogId,
	proId,
	title,
	onTitleChange,
	slug,
	onSlugChange,
	content,
	onContentChange,
	metaDescription,
	onMetaDescriptionChange,
	primaryKeyword,
	onPrimaryKeywordChange,
	blogType,
	onBlogTypeChange,
	coverImageUrl,
	onCoverImageChange,
	coverImageAlt,
	onCoverImageAltChange,
	categoryId,
	onCategoryChange,
	cityId,
	onCityChange,
	secondaryKeywords,
	onSecondaryKeywordsChange,
	categories,
	cities,
	tagIds,
	onTagIdsChange,
	availableTags,
	status,
	saveStatus,
	lastSavedAt,
	onSave,
	onPublish,
	onDelete,
	saving,
	onBack,
	adminPanels,
	onUploadCover,
	topBanner,
}: UnifiedBlogEditorProps) {
	const [showSidebar, setShowSidebar] = useState(false);
	const [aiLoading, setAiLoading] = useState(false);
	const [aiResult, setAiResult] = useState<{ text: string; action: string } | null>(null);
	const [aiError, setAiError] = useState<string | null>(null);
	const lastAiParamsRef = useRef<{ action: CopilotAction; selection: string; from: number; to: number } | null>(null);
	const editorInstanceRef = useRef<import("@tiptap/react").Editor | null>(null);
 
	// Track whether user has manually edited the slug field directly.
	// Starts false so title changes always auto-update the slug until
	// the user explicitly types in the slug input.
	const slugTouchedRef = useRef(false);
 
	const handleTitleChange = useCallback(
		(newTitle: string) => {
			onTitleChange(newTitle);
			// Auto-generate slug from title if slug hasn't been manually edited
			Eif (!slugTouchedRef.current) {
				onSlugChange(slugify(newTitle));
			}
		},
		[onTitleChange, onSlugChange],
	);
 
	const handleSlugChange = useCallback(
		(value: string) => {
			slugTouchedRef.current = true;
			// Real-time slugification so the input always shows the actual slug
			const slugified = value
				.toLowerCase()
				.replace(/[^a-z0-9\s-]/g, '')
				.replace(/\s+/g, '-')
				.replace(/-+/g, '-')
				.replace(/^-|-$/g, '');
			onSlugChange(slugified);
		},
		[onSlugChange],
	);
 
	// Word count and image count from HTML content
	const wordCount = useMemo(() => content
		.replace(/<[^>]*>/g, " ")
		.split(/\s+/)
		.filter((w) => w).length, [content]);
 
	const imageCount = useMemo(() => (content.match(/<img\s/g) || []).length, [content]);
 
	const WORD_LIMIT = 5000;
	const WORD_WARNING_THRESHOLD = 4500;
	const isOverLimit = wordCount > WORD_LIMIT;
	const isNearLimit = wordCount >= WORD_WARNING_THRESHOLD && wordCount <= WORD_LIMIT;
 
	// Close sidebar on Escape key
	useEffect(() => {
		if (!showSidebar) return;
		const handleEscape = (e: KeyboardEvent) => {
			Eif (e.key === "Escape") setShowSidebar(false);
		};
		document.addEventListener("keydown", handleEscape);
		return () => document.removeEventListener("keydown", handleEscape);
	}, [showSidebar]);
 
	const handleAIAction = async (action: CopilotAction, selection: string, from: number, to: number) => {
		lastAiParamsRef.current = { action, selection, from, to };
		setAiLoading(true);
		setAiError(null);
		setAiResult(null);
 
		try {
			const response = await aiApi.copilot({
				action,
				context: content.substring(0, 3000),
				selection: selection || undefined,
			});
			setAiResult({ text: response.result, action });
		} catch (err) {
			setAiError(getErrorMessage(err));
		} finally {
			setAiLoading(false);
		}
	};
 
	const handleAIInsert = () => {
		Iif (!aiResult) return;
		const editor = editorInstanceRef.current;
		const params = lastAiParamsRef.current;
		const isSelectionAction = ["expand", "shorten", "rewrite", "indianize"].includes(aiResult.action);
 
		if (editor) {
			if (isSelectionAction && params && params.from !== params.to) {
				// Verify the document hasn't changed out from under us
				const docLength = editor.state.doc.content.size;
				if (params.to > docLength) {
					notify.error("The document changed while AI was working. Please try the action again.");
					setAiResult(null);
					return;
				}
				// Replace the original selected range with AI result (plain text to prevent XSS)
				editor.chain()
					.focus()
					.setTextSelection({ from: params.from, to: params.to })
					.deleteSelection()
					.insertContent({ type: "text", text: aiResult.text })
					.run();
			} else {
				// Generative actions: append at end (use JSON node to prevent XSS)
				editor.chain().focus("end").insertContent({
					type: "paragraph",
					content: [{ type: "text", text: aiResult.text }],
				}).run();
			}
		} else if (isSelectionAction) {
			notify.error("Could not replace the selected text. The result has been appended at the end.");
			onContentChange(`${content}\n${aiResult.text}`);
		} else E{
			onContentChange(`${content}\n${aiResult.text}`);
		}
		setAiResult(null);
	};
 
	const handleAIDiscard = () => {
		setAiResult(null);
		setAiError(null);
	};
 
	const handleAIRetry = () => {
		if (lastAiParamsRef.current) {
			const { action, selection, from, to } = lastAiParamsRef.current;
			handleAIAction(action, selection, from, to);
		} else E{
			setAiError("Unable to retry. Please try the AI action again from the toolbar.");
		}
	};
 
	const handlePublishClick = () => {
		if (!coverImageUrl) {
			notify.error("A cover image is required to publish. Please add a cover image first.");
			// Open SEO sidebar so user can add cover image
			setShowSidebar(true);
			return;
		}
		if (isOverLimit) {
			notify.error(`Blog content exceeds the ${WORD_LIMIT} word limit. Please shorten your content before publishing.`);
			return;
		}
		onPublish?.();
	};
 
	return (
		<div className="max-w-full mx-auto min-h-full">
			{/* Top Bar — sticky on all screen sizes */}
			<div className="sticky top-0 z-20 bg-background-base/95 backdrop-blur-sm border-b border-border-default px-4 sm:px-6 lg:px-8 min-h-12 flex items-center sm:-mx-6 lg:-mx-8 sm:-mt-6 lg:-mt-8">
			<div className="flex items-center justify-between w-full gap-2 py-2">
				<div className="flex items-center gap-2 min-w-0">
					<button
						type="button"
						onClick={onBack}
						aria-label="Go back"
						className="p-2 -ml-2 hover:bg-background-muted rounded-md flex-shrink-0"
					>
						<ArrowLeft className="h-5 w-5" />
					</button>
					{saveStatus && (
						<div className="hidden sm:block">
							<SaveStatusIndicator
								status={saveStatus}
								lastSavedAt={lastSavedAt ?? null}
							/>
						</div>
					)}
				</div>
 
				<div className="flex items-center gap-1.5 sm:gap-2">
					<Button
						variant={status === "published" ? "default" : "outline"}
						size="sm"
						onClick={onSave}
						disabled={saving || !title.trim() || isOverLimit}
						title={isOverLimit ? "Content exceeds 5000 word limit" : undefined}
					>
						{saving ? (
							<Loader2 className="h-4 w-4 animate-spin" />
						) : (
							<Save className="h-4 w-4" />
						)}
						<span className="hidden sm:inline">{status === "published" ? "Save" : "Save Draft"}</span>
					</Button>
					<Button
						variant="ghost"
						size="sm"
						onClick={() => {
							setShowSidebar(!showSidebar);
						}}
						className={showSidebar ? "bg-background-muted" : ""}
					>
						<PanelRight className="h-4 w-4" />
						<span className="hidden sm:inline">Settings</span>
					</Button>
					{onPublish && status !== "published" && (
						<Button
							size="sm"
							onClick={handlePublishClick}
							disabled={saving || !title.trim() || !content.trim()}
						>
							{saving ? (
								<Loader2 className="h-4 w-4 animate-spin" />
							) : (
								<Send className="h-4 w-4" />
							)}
							<span className="hidden sm:inline">Publish</span>
						</Button>
					)}
					{onDelete && (
						<Button
							variant="ghost"
							size="sm"
							onClick={onDelete}
							disabled={saving}
							className="text-error hover:text-error hover:bg-error-light"
						>
							<Trash2 className="h-4 w-4" />
						</Button>
					)}
				</div>
			</div>
			</div>
 
			{/* Content area with padding */}
			<div className="pt-4 px-4 sm:px-0">
				{/* Top banner (e.g. unpublished profile warning) */}
				{topBanner && <div className="mb-4">{topBanner}</div>}
 
				{/* Published banner */}
				{status === "published" && (
					<div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-800">
						This blog is published and live. Changes will be visible immediately.
					</div>
				)}
 
				{/* Cover image warning — shown once the user has meaningful content */}
				{!coverImageUrl && content.length > 100 && (
					<div className="mb-4 flex items-center gap-1.5 px-3 py-2 bg-warning/10 rounded-md text-xs text-warning">
						<AlertTriangle className="h-3.5 w-3.5 flex-shrink-0" />
						Cover image required to publish. Open Settings to add one.
					</div>
				)}
 
				{/* Main Layout */}
				<div className="flex gap-6 relative">
					{/* Editor Area */}
					<div className="flex-1 min-w-0">
						{/* Title */}
						<input
							type="text"
							value={title}
							onChange={(e) => handleTitleChange(e.target.value)}
							placeholder="Untitled"
							className="w-full text-2xl sm:text-3xl font-bold border-none bg-transparent focus:outline-none mb-1 placeholder:text-foreground-subtle"
						/>
						<div className="flex items-center gap-1 text-sm text-foreground-subtle mb-4">
							<span>/blog/</span>
							<input
								type="text"
								value={slug}
								onChange={(e) => handleSlugChange(e.target.value)}
								className="border-none bg-transparent focus:outline-none text-foreground-subtle hover:text-foreground-default focus:text-foreground-default min-w-0 flex-1"
								placeholder="slug"
							/>
						</div>
 
						{/* Cover image warning */}
						{!coverImageUrl && content.length > 100 && (
							<div className="flex items-center gap-1.5 px-3 py-2 mb-4 text-xs text-warning bg-warning/10 rounded-md">
								<AlertTriangle className="h-3.5 w-3.5 flex-shrink-0" />
								A cover image is required to publish
							</div>
						)}
 
						{/* Rich Text Editor */}
						<RichTextEditor
							content={content}
							onChange={onContentChange}
							placeholder="Start writing your blog..."
							proId={proId}
							blogId={blogId}
							onAIAction={handleAIAction}
							aiLoading={aiLoading}
							editorRef={editorInstanceRef}
						/>
 
						{/* Bottom bar */}
						<div className="flex items-center justify-between mt-3 text-xs px-1">
							<span
								className={cn(
									"text-foreground-subtle",
									isNearLimit && "text-amber-600 font-medium",
									isOverLimit && "text-red-600 font-medium",
								)}
							>
								{wordCount} / {WORD_LIMIT} words
								{isOverLimit && " — over limit"}
								{isNearLimit && " — approaching limit"}
							</span>
						</div>
 
						{/* Admin panels rendered below editor */}
						{adminPanels}
					</div>
 
					{/* SEO Sidebar — desktop: side panel, mobile: full-screen overlay */}
					{showSidebar && (() => {
						const seoSidebarProps = {
							slug,
							onSlugChange: handleSlugChange,
							metaDescription,
							onMetaDescriptionChange,
							primaryKeyword,
							onPrimaryKeywordChange,
							blogType,
							onBlogTypeChange,
							coverImageUrl,
							coverImageAlt,
							onCoverImageAltChange,
							onCoverImageChange,
							proId: proId || "",
							blogId,
							mode,
							categoryId,
							onCategoryChange,
							cityId,
							onCityChange,
							secondaryKeywords,
							onSecondaryKeywordsChange,
							categories,
							cities,
							tagIds,
							onTagIdsChange,
							availableTags,
							onUploadCover,
							wordCount,
							imageCount,
						} as const;
						return (
							<>
								{/* Mobile overlay */}
								<div className="fixed inset-0 z-[65] flex flex-col bg-background-base sm:hidden">
									<div className="flex h-14 items-center justify-between border-b border-border-default bg-background-elevated px-4 flex-shrink-0">
										<h3 className="text-lg font-semibold">Settings</h3>
										<button
											type="button"
											onClick={() => setShowSidebar(false)}
											className="p-2 text-foreground-muted hover:text-foreground-default rounded-md"
										>
											<X className="h-5 w-5" />
										</button>
									</div>
									<div className="flex-1 overflow-y-auto p-4">
										<SEOSidebar {...seoSidebarProps} />
									</div>
								</div>
								{/* Desktop side panel */}
								<div className="hidden sm:block w-72 shrink-0 bg-background-elevated border border-border-default rounded-lg p-4 sticky top-4 max-h-[calc(100vh-2rem)] overflow-y-auto">
									<SEOSidebar {...seoSidebarProps} />
								</div>
							</>
						);
					})()}
 
				</div>
			</div>
 
			{/* AI Result Modal — rendered as overlay on top of everything */}
			{(aiResult || aiLoading || aiError) && (
				<AIResultPreview
					result={aiResult?.text || ""}
					action={aiResult?.action || lastAiParamsRef.current?.action || ""}
					isLoading={aiLoading}
					error={aiError}
					onInsert={handleAIInsert}
					onDiscard={handleAIDiscard}
					onRetry={handleAIRetry}
				/>
			)}
		</div>
	);
}