Spaces:
Runtime error
Runtime error
File size: 30,626 Bytes
c7fbc2e | 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 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | "use client";
import { useState, useMemo, useEffect } from "react";
import "react-datepicker/dist/react-datepicker.css";
import DatePicker from "react-datepicker";
import { InstagramAccount, Post } from "@prisma/client";
import CoverFrameSelector from "./CoverFrameSelector";
import TimePicker from "./TimePicker";
import { UploadCloud, Image as ImageIcon, Video, Layers, Calendar, Clock, X, ChevronDown, Smile, Hash, GripVertical, Heart, MessageCircle, Send, Bookmark, MoreHorizontal, ImagePlus, PlusCircle, FileText, User as UserIcon, Tag as TagIcon, LayoutTemplate } from "lucide-react";
import MediaPreview from "./MediaPreview";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { format } from "date-fns";
import TipTapEditor from "@/components/TipTapEditor";
// Styled Components / Token Classes
const PAGE_CONTAINER = "max-w-4xl mx-auto flex flex-col lg:flex-row gap-8 lg:gap-16 pt-8 pb-20";
const EDITOR_COLUMN = "flex-1 min-w-0";
const PREVIEW_COLUMN = "w-[380px] flex-shrink-0 hidden lg:block";
const NOTION_PROPERTY_ROW = "flex items-start py-1.5 min-h-[32px] text-sm group";
const NOTION_PROPERTY_LABEL = "w-[120px] pt-1 text-gray-400 flex items-center gap-2 select-none truncate";
const NOTION_PROPERTY_VALUE = "flex-1 min-w-0 flex flex-wrap items-center gap-2";
const NOTION_TITLE = "text-4xl font-bold text-foreground placeholder-gray-200 outline-none bg-transparent w-full resize-none overflow-hidden h-auto block mb-6";
export default function PostCreator({
accounts,
initialMediaType = "IMAGE",
initialPost
}: {
accounts: InstagramAccount[],
initialMediaType?: string,
initialPost?: Post | null
}) {
const router = useRouter();
// -- State --
const [postType, setPostType] = useState<"FEED" | "REELS">(
initialPost
? (initialPost.mediaType === "REELS" ? "REELS" : "FEED")
: (initialMediaType.toLowerCase() === "video" || initialMediaType === "REELS" ? "REELS" : "FEED")
);
const [selectedAccountIds, setSelectedAccountIds] = useState<string[]>(
initialPost ? [initialPost.instagramAccountId] : (accounts.length > 0 ? [accounts[0].id] : [])
);
const [caption, setCaption] = useState(initialPost?.caption || "");
const [mediaItems, setMediaItems] = useState<(File | string)[]>(
initialPost?.mediaUrl ? initialPost.mediaUrl.split(',') : []
);
const [activeMediaIndex, setActiveMediaIndex] = useState(0);
const [coverItem, setCoverItem] = useState<File | string | null>(initialPost?.coverUrl || null);
const [isCoverModalOpen, setIsCoverModalOpen] = useState(false);
const [scheduledAt, setScheduledAt] = useState<Date | null>(
initialPost?.scheduledAt ? new Date(initialPost.scheduledAt) : null
);
const [isSubmitting, setIsSubmitting] = useState(false);
// For "Notion Page Title" simulation (visual only or internal name?)
// Instagram doesn't have a title. We'll keep it visual.
const [title, setTitle] = useState("Untitled");
// -- Helpers --
const toggleAccount = (id: string) => {
setSelectedAccountIds(prev =>
prev.includes(id) ? prev.filter(accId => accId !== id) : [...prev, id]
);
};
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
const newFiles = Array.from(e.target.files);
if (postType === "REELS") {
setMediaItems([newFiles[0]]);
setCoverItem(null);
setActiveMediaIndex(0);
} else {
setMediaItems(prev => [...prev, ...newFiles]);
}
}
};
const handleReorder = (fromIndex: number, toIndex: number) => {
setMediaItems(prev => {
const newItems = [...prev];
const [movedItem] = newItems.splice(fromIndex, 1);
newItems.splice(toIndex, 0, movedItem);
return newItems;
});
setActiveMediaIndex(toIndex);
};
const coverObjectUrl = useMemo(() => {
if (!coverItem) return null;
if (typeof coverItem === "string") return coverItem;
return URL.createObjectURL(coverItem);
}, [coverItem]);
const primaryAccount = accounts.find(a => a.id === selectedAccountIds[0]);
// -- Submit Handler --
const handleSubmit = async () => {
if (selectedAccountIds.length === 0 || mediaItems.length === 0) {
alert("Please select an account and add media.");
return;
}
setIsSubmitting(true);
try {
// Upload Logic (Similar to before)
const newMediaFiles = mediaItems.filter(item => item instanceof File) as File[];
const newCoverFile = coverItem instanceof File ? coverItem : null;
let uploadedMediaUrls: string[] = [];
let uploadedCoverUrl: string | null = null;
if (newMediaFiles.length > 0 || newCoverFile) {
const formData = new FormData();
newMediaFiles.forEach(file => formData.append("file", file));
if (newCoverFile) formData.append("file", newCoverFile);
const uploadRes = await fetch("/api/upload", { method: "POST", body: formData });
if (!uploadRes.ok) throw new Error("Upload failed");
const { urls } = await uploadRes.json();
const newMediaCount = newMediaFiles.length;
uploadedMediaUrls = urls.slice(0, newMediaCount);
if (newCoverFile) uploadedCoverUrl = urls[newMediaCount];
}
let nextUploadIndex = 0;
const finalMediaUrls = mediaItems.map(item => {
if (typeof item === "string") return item;
return uploadedMediaUrls[nextUploadIndex++];
});
const finalCoverUrl = newCoverFile ? uploadedCoverUrl : (typeof coverItem === "string" ? coverItem : null);
let finalMediaType: string = postType;
if (postType === "FEED") {
if (finalMediaUrls.length > 1) {
finalMediaType = "CAROUSEL";
} else if (finalMediaUrls.length === 1) {
// content checks to discern VIDEO vs IMAGE
// We can check the original item type if it's a File, or extension if string
const originalItem = mediaItems[0];
let isVideo = false;
if (originalItem instanceof File) {
isVideo = originalItem.type.startsWith("video");
} else if (typeof originalItem === 'string') {
isVideo = originalItem.endsWith(".mp4") || originalItem.endsWith(".mov") || originalItem.includes("/video/");
}
finalMediaType = isVideo ? "VIDEO" : "IMAGE";
}
}
const postData = {
caption,
mediaUrl: finalMediaUrls.join(","),
mediaType: finalMediaType,
coverUrl: finalCoverUrl,
scheduledAt: scheduledAt ? scheduledAt.toISOString() : null,
};
if (initialPost) {
await fetch("/api/posts", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: initialPost.id, ...postData }),
});
} else {
for (const accId of selectedAccountIds) {
await fetch("/api/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ instagramAccountId: accId, ...postData }),
});
}
}
router.push(scheduledAt ? "/dashboard/scheduled" : "/dashboard/posted");
router.refresh();
} catch (error) {
console.error(error);
alert("Failed to save post.");
} finally {
setIsSubmitting(false);
}
};
return (
<div className={PAGE_CONTAINER}>
{/* --- EDITOR COLUMN (Notion Page Style) --- */}
<div className={EDITOR_COLUMN}>
{/* Properties Table */}
<div className="mb-6 pl-1">
{/* 1. Account Property */}
<div className={NOTION_PROPERTY_ROW}>
<div className={NOTION_PROPERTY_LABEL}>
<UserIcon size={14} />
<span>Account</span>
</div>
<div className={NOTION_PROPERTY_VALUE}>
{accounts.map(acc => {
const isSelected = selectedAccountIds.includes(acc.id);
return (
<button
key={acc.id}
onClick={() => toggleAccount(acc.id)}
className={`flex items-center gap-1.5 px-2 py-0.5 rounded text-sm transition-colors border ${isSelected ? "bg-primary-green/10 text-primary-green border-primary-green/20" : "bg-transparent text-gray-500 border-transparent hover:bg-gray-100 dark:hover:bg-zinc-800"}`}
>
{(acc as any).profilePictureUrl && (
<div className="w-4 h-4 rounded overflow-hidden relative">
<Image src={(acc as any).profilePictureUrl} alt={acc.username || ""} fill className="object-cover" />
</div>
)}
<span>{acc.username}</span>
</button>
);
})}
</div>
</div>
{/* 3. Date Property */}
<div className={NOTION_PROPERTY_ROW}>
<div className={NOTION_PROPERTY_LABEL}>
<Calendar size={14} />
<span>Date</span>
</div>
<div className={NOTION_PROPERTY_VALUE}>
<DatePicker
selected={scheduledAt}
onChange={(date) => {
const newDate = date || new Date();
if (scheduledAt) newDate.setHours(scheduledAt.getHours(), scheduledAt.getMinutes());
setScheduledAt(newDate);
}}
dateFormat="MMM d, yyyy"
placeholderText="Empty"
className="bg-transparent border-none outline-none text-sm text-foreground p-0 cursor-pointer placeholder-gray-300 hover:text-primary-green transition-colors"
/>
{scheduledAt && (
<div className="text-gray-400 flex items-center">
<span className="mx-1">@</span>
<TimePicker date={scheduledAt} onChange={setScheduledAt} />
<button onClick={() => setScheduledAt(null)} className="ml-2 hover:text-red-500"><X size={12} /></button>
</div>
)}
</div>
</div>
</div>
<div className="h-px bg-border-subtle w-full mb-8"></div>
{/* Content Block: Media */}
<div className="mb-6 group">
{mediaItems.length === 0 ? (
<div className="border border-border-subtle rounded-md p-8 flex flex-col items-center justify-center text-gray-400 hover:bg-gray-50 dark:hover:bg-zinc-900/50 transition-colors relative cursor-pointer">
<input
type="file"
multiple={postType === "FEED"}
accept={postType === "REELS" ? "video/*" : "image/*,video/*"}
onChange={handleFileSelect}
className="absolute inset-0 opacity-0 cursor-pointer"
/>
<ImagePlus size={24} className="mb-2 opacity-50" />
<span className="text-sm">Add an image or video</span>
</div>
) : (
<div className="space-y-2">
<MediaPreview
files={mediaItems}
type={postType}
onRemove={(index) => {
setMediaItems(prev => prev.filter((_, i) => i !== index));
if (activeMediaIndex >= index && activeMediaIndex > 0) setActiveMediaIndex(prev => prev - 1);
}}
activeIndex={activeMediaIndex}
onIndexChange={setActiveMediaIndex}
onReorder={handleReorder}
/>
<div className="flex gap-2">
{postType === "FEED" && (
<button className="text-xs text-gray-400 hover:text-foreground flex items-center gap-1 relative overflow-hidden">
<PlusCircle size={12} />
<span>Add more</span>
<input
type="file" multiple accept="image/*,video/*"
onChange={(e) => { if (e.target.files) setMediaItems(prev => [...prev, ...Array.from(e.target.files!)]) }}
className="absolute inset-0 opacity-0 cursor-pointer"
/>
</button>
)}
{postType === "REELS" && (
<button onClick={() => setIsCoverModalOpen(true)} className="text-xs text-gray-400 hover:text-foreground flex items-center gap-1">
<Layers size={12} />
<span>Set Cover</span>
</button>
)}
</div>
</div>
)}
</div>
{/* Content Block: Caption (TipTap) */}
<div className="mb-6">
<div className="min-h-[150px] text-base mb-2">
<TipTapEditor
content={caption}
onChange={setCaption}
placeholder="Write a caption..."
/>
</div>
{/* Character Count */}
<div className="flex justify-end text-xs text-gray-400 border-t border-border-subtle pt-2">
<div className={`${caption.length > 2200 ? "text-red-500 font-medium" : ""}`}>
{caption.length} / 2200
</div>
</div>
</div>
{/* Footer / Actions - Inline at bottom */}
<div className="flex justify-end pt-4 mb-20">
<button
onClick={handleSubmit}
disabled={isSubmitting}
className={`px-6 py-2 rounded-lg font-medium text-sm transition-all flex items-center gap-2 shadow-sm ${scheduledAt ? "bg-primary-green text-white hover:bg-emerald-600" : "bg-black dark:bg-white text-white dark:text-black hover:opacity-90"}`}
>
{isSubmitting && <div className="w-3 h-3 rounded-full border-2 border-current border-t-transparent animate-spin" />}
{scheduledAt ? "Schedule Post" : "Post Now"}
</button>
</div>
</div>
{/* --- PREVIEW COLUMN --- */}
<div className={PREVIEW_COLUMN}>
<div className="sticky top-8">
<p className="text-xs font-bold text-gray-400 uppercase tracking-widest mb-4 text-center">Preview</p>
{/* Phone Frame */}
<div className="w-[340px] h-[700px] bg-white dark:bg-black rounded-[3rem] shadow-2xl border-[8px] border-zinc-900 dark:border-zinc-800 overflow-hidden relative mx-auto select-none">
{/* Status Bar */}
<div className="h-8 flex items-center justify-between px-6 text-[10px] font-medium opacity-90 z-20 absolute top-0 w-full mix-blend-difference text-white">
<span>9:41</span>
<div className="flex gap-1"><div className="w-3 h-3 bg-current rounded-full" /></div>
</div>
{/* Content Area */}
<div className="h-full bg-white dark:bg-black text-black dark:text-white relative">
{postType === "REELS" ? (
/* --- REELS LAYOUT (Full height media + Overlay UI) --- */
<div className="absolute inset-0 w-full h-full bg-black">
{/* Background Media */}
{mediaItems.length > 0 ? (
<div className="w-full h-full relative">
{(typeof mediaItems[0] === 'string'
? (mediaItems[0].endsWith(".mp4") || mediaItems[0].includes("/video/"))
: mediaItems[0].type.startsWith("video")
) ? (
<video
src={typeof mediaItems[0] === 'string' ? mediaItems[0] : URL.createObjectURL(mediaItems[0] as File)}
className="w-full h-full object-cover"
autoPlay muted loop playsInline
/>
) : (
<img
src={typeof mediaItems[0] === 'string' ? mediaItems[0] : URL.createObjectURL(mediaItems[0] as File)}
className="w-full h-full object-cover opacity-80"
alt="reel preview"
/>
)}
</div>
) : (
<div className="w-full h-full flex items-center justify-center text-gray-700">
<Video size={48} className="opacity-20" />
</div>
)}
{/* Overlay UI */}
<div className="absolute top-8 left-0 w-full p-4 flex justify-between items-center text-white z-10">
<span className="font-bold text-xl drop-shadow-md">Reels</span>
<div className="w-6 h-6 bg-transparent" /> {/* Spacer/Camera icon place */}
</div>
<div className="absolute bottom-0 left-0 w-full p-4 pb-8 bg-gradient-to-t from-black/80 to-transparent pt-20 text-white z-10 flex items-end">
<div className="flex-1 min-w-0 pr-12">
{/* User Info */}
<div className="flex items-center gap-2 mb-3">
<div className="w-8 h-8 rounded-full bg-white relative overflow-hidden">
{(primaryAccount as any)?.profilePictureUrl && <Image src={(primaryAccount as any).profilePictureUrl} alt="" fill className="object-cover" />}
</div>
<span className="font-semibold text-sm drop-shadow-md">{primaryAccount?.username || "username"}</span>
<button className="text-xs border border-white/40 px-2 py-0.5 rounded backdrop-blur-sm">Follow</button>
</div>
{/* Caption */}
<div className="text-sm line-clamp-2 drop-shadow-md mb-2 whitespace-pre-wrap">
{caption || "Caption goes here..."}
</div>
<div className="flex items-center gap-2 text-xs opacity-90">
<div className="flex gap-1 items-center">
<span>♫ Original Audio</span>
</div>
</div>
</div>
{/* Right Side Actions */}
<div className="absolute right-3 bottom-8 flex flex-col items-center gap-6">
<div className="flex flex-col items-center gap-1">
<Heart size={28} strokeWidth={1.5} className="drop-shadow-sm" />
<span className="text-xs font-medium">12.5k</span>
</div>
<div className="flex flex-col items-center gap-1">
<MessageCircle size={28} strokeWidth={1.5} className="drop-shadow-sm -rotate-90" />
<span className="text-xs font-medium">523</span>
</div>
<Send size={28} strokeWidth={1.5} className="drop-shadow-sm rotate-12" />
<MoreHorizontal size={24} className="drop-shadow-sm" />
<div className="w-7 h-7 border-2 border-white rounded-md overflow-hidden relative">
{/* Audio thumb */}
{(primaryAccount as any)?.profilePictureUrl && <Image src={(primaryAccount as any).profilePictureUrl} alt="" fill className="object-cover" />}
</div>
</div>
</div>
</div>
) : (
/* --- FEED LAYOUT (Standard) --- */
<div className="h-full overflow-y-auto scrollbar-none pt-8">
{/* User Info Header */}
<div className="flex items-center gap-3 px-4 py-3">
<div className="w-8 h-8 rounded-full bg-gradient-to-tr from-yellow-400 to-fuchsia-600 p-[2px]">
<div className="w-full h-full rounded-full bg-white dark:bg-black relative overflow-hidden border border-white dark:border-black">
{(primaryAccount as any)?.profilePictureUrl ? <Image src={(primaryAccount as any).profilePictureUrl} alt="" fill className="object-cover" /> : null}
</div>
</div>
<div className="flex flex-col leading-none">
<span className="font-semibold text-xs">{primaryAccount?.username || "username"}</span>
{/* Location or Audio could go here */}
</div>
<MoreHorizontal size={16} className="ml-auto opacity-50" />
</div>
{/* Media - 4:5 Aspect Ratio Standard */}
<div className="aspect-[4/5] bg-gray-100 dark:bg-zinc-900 relative flex items-center justify-center overflow-hidden">
{mediaItems.length > 0 ? (
<>
{(typeof mediaItems[activeMediaIndex] === 'string'
? (mediaItems[activeMediaIndex].endsWith(".mp4") || mediaItems[activeMediaIndex].includes("/video/"))
: mediaItems[activeMediaIndex].type.startsWith("video")
) ? (
<video
src={typeof mediaItems[activeMediaIndex] === 'string' ? mediaItems[activeMediaIndex] : URL.createObjectURL(mediaItems[activeMediaIndex] as File)}
className="w-full h-full object-cover"
autoPlay muted loop playsInline
/>
) : (
<img
src={typeof mediaItems[activeMediaIndex] === 'string' ? mediaItems[activeMediaIndex] : URL.createObjectURL(mediaItems[activeMediaIndex] as File)}
className="w-full h-full object-cover"
alt="preview"
/>
)}
{/* Carousel Indicators if multiple */}
{mediaItems.length > 1 && (
<div className="absolute top-3 right-3 bg-black/60 text-white text-[10px] font-semibold px-2 py-1 rounded-full backdrop-blur-md">
{activeMediaIndex + 1}/{mediaItems.length}
</div>
)}
</>
) : (
<div className="flex flex-col items-center justify-center text-gray-300 gap-2">
<ImageIcon size={48} />
</div>
)}
</div>
{/* Action Bar */}
<div className="px-3 py-3 flex justify-between">
<div className="flex gap-4">
<Heart size={24} strokeWidth={1.5} className="hover:text-gray-500 transition-colors cursor-pointer" />
<MessageCircle size={24} strokeWidth={1.5} className="-rotate-90 hover:text-gray-500 transition-colors cursor-pointer" />
<Send size={24} strokeWidth={1.5} className="hover:text-gray-500 transition-colors cursor-pointer" />
</div>
<Bookmark size={24} strokeWidth={1.5} className="hover:text-gray-500 transition-colors cursor-pointer" />
</div>
{/* Likes & Caption */}
<div className="px-4 text-xs pb-8">
<p className="font-semibold mb-1 cursor-pointer">1,234 likes</p>
<div className="leading-snug">
<span className="font-semibold mr-2 cursor-pointer">{primaryAccount?.username || "username"}</span>
<div className="inline whitespace-pre-wrap">{caption || <span className="text-gray-400 italic">Caption goes here...</span>}</div>
</div>
<p className="text-gray-500 mt-1 text-[10px] uppercase tracking-wide cursor-pointer">2 hours ago</p>
</div>
</div>
)}
</div>
</div>
</div>
</div>
<CoverFrameSelector
isOpen={isCoverModalOpen}
onClose={() => setIsCoverModalOpen(false)}
videoFile={mediaItems.length > 0 && postType === "REELS" ? mediaItems[0] : null}
onSave={(file) => {
setCoverItem(file);
setIsCoverModalOpen(false);
}}
/>
</div>
);
}
|