'use client'
import {
useState,
useRef,
useCallback,
useEffect,
ChangeEvent,
TextareaHTMLAttributes,
} from 'react'
import { useMutation } from '@tanstack/react-query'
import api from '@/services/api'
import { getErrorMessage } from '@/utils/error'
import {
HashtagSuggestions,
MentionSuggestions,
EmojiPicker,
DropZone,
} from '@/components/composer'
import RepoLinker from '@/components/composer/RepoLinker'
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface LinkedRepo {
owner: string
name: string
fullName: string
description?: string
stars?: number
language?: string
}
type Audience = 'public' | 'followers'
interface CreatePostPayload {
content: string
mediaUrls?: string[]
videoUrl?: string
repoFullName?: string
audience: Audience
scheduledAt?: string
}
interface CreatePostResponse {
id: string
content: string
createdAt: string
}
interface PostPreviewProps {
content: string
imagePreviewUrls: string[]
videoUrl: string
linkedRepo: LinkedRepo | null
audience: Audience
scheduledAt: Date | null
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const MAX_CHARS = 500
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function insertAtCursor(
text: string,
cursorPos: number,
insertion: string,
): { newText: string; newCursor: number } {
const before = text.slice(0, cursorPos)
const after = text.slice(cursorPos)
// Replace the partial token (hashtag/mention) before the cursor
const trimmedBefore = before.replace(/(^|\s)[#@]\w*$/, (match) => {
const prefix = match.match(/^(\s)/)?.[1] ?? ''
return prefix
})
const newText = `${trimmedBefore}${insertion} ${after}`
const newCursor = trimmedBefore.length + insertion.length + 1
return { newText, newCursor }
}
/** Map a create/schedule failure to a user-friendly message. */
function getCreatePostError(err: unknown): string {
const status = (err as { response?: { status?: number } })?.response?.status
const message = getErrorMessage(err)
if (status === 403 && /premium|subscription/i.test(message)) {
return 'Scheduling posts requires a premium subscription. Upgrade to schedule, or post now instead.'
}
return message || 'Failed to create post. Please try again.'
}
function formatScheduleLabel(date: Date): string {
return date.toLocaleString(undefined, {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
}
// ---------------------------------------------------------------------------
// PostPreview
// ---------------------------------------------------------------------------
function PostPreview({
content,
imagePreviewUrls,
videoUrl,
linkedRepo,
audience,
scheduledAt,
}: PostPreviewProps) {
return (
You
{scheduledAt ? `Scheduled: ${formatScheduleLabel(scheduledAt)}` : 'Just now'} ·{' '}
{audience === 'public' ? 'Public' : 'Followers only'}
{content && (
{content.split(/(\s)/).map((token, i) => {
if (token.startsWith('#'))
return (
{token}
)
if (token.startsWith('@'))
return (
{token}
)
return token
})}
)}
{imagePreviewUrls.length > 0 && (
{imagePreviewUrls.map((url, i) => (

))}
)}
{videoUrl && !imagePreviewUrls.length && (
)}
{linkedRepo && (
{linkedRepo.fullName}
{linkedRepo.description && (
{linkedRepo.description}
)}
)}
{!content && !imagePreviewUrls.length && !videoUrl && !linkedRepo && (
Start typing to see a preview…
)}
)
}
// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------
export default function CreatePage() {
const [content, setContent] = useState('')
const [cursorPos, setCursorPos] = useState(0)
const [imageFiles, setImageFiles] = useState([])
const [imagePreviewUrls, setImagePreviewUrls] = useState([])
const [videoUrl, setVideoUrl] = useState('')
const [linkedRepo, setLinkedRepo] = useState(null)
const [showRepoLinker, setShowRepoLinker] = useState(false)
const [audience, setAudience] = useState('public')
const [scheduleEnabled, setScheduleEnabled] = useState(false)
const [scheduledAt, setScheduledAt] = useState(null)
const [showPreview, setShowPreview] = useState(false)
const [errorMsg, setErrorMsg] = useState(null)
const textareaRef = useRef(null)
// Auto-resize textarea
useEffect(() => {
const el = textareaRef.current
if (!el) return
el.style.height = 'auto'
el.style.height = `${el.scrollHeight}px`
}, [content])
// Build object URLs for image previews
useEffect(() => {
const urls = imageFiles.map((f) => URL.createObjectURL(f))
setImagePreviewUrls(urls)
return () => urls.forEach((u) => URL.revokeObjectURL(u))
}, [imageFiles])
// ---------------------------------------------------------------------------
// Mutation
// ---------------------------------------------------------------------------
const mutation = useMutation({
mutationFn: async (payload) => {
let uploadedImageUrls: string[] = []
if (imageFiles.length > 0) {
const form = new FormData()
imageFiles.forEach((f) => form.append('files', f))
const { data } = await api.post<{ urls: string[] }>('/v1/media/upload', form, {
headers: { 'Content-Type': 'multipart/form-data' },
})
uploadedImageUrls = data.urls
}
// Scheduled posts MUST go to the dedicated scheduling endpoint. The
// immediate-post endpoint (/v1/posts) ignores `scheduledAt` and would
// publish straight away, making the "Post scheduled!" screen misleading.
if (payload.scheduledAt) {
const { data } = await api.post<{ scheduledPost: { id: string } }>(
'/v1/scheduled-posts',
{
content: payload.content,
mediaUrls: uploadedImageUrls,
scheduledFor: payload.scheduledAt,
},
)
return {
id: data.scheduledPost?.id ?? '',
content: payload.content,
createdAt: payload.scheduledAt,
}
}
const { data } = await api.post('/v1/posts', {
...payload,
mediaUrls: uploadedImageUrls,
})
return data
},
onError: (err) => {
setErrorMsg(getCreatePostError(err))
},
})
// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------
const handleContentChange = useCallback((e: ChangeEvent) => {
const val = e.target.value
if (val.length <= MAX_CHARS) {
setContent(val)
setCursorPos(e.target.selectionStart ?? val.length)
}
}, [])
const handleTextareaClick = useCallback(() => {
setCursorPos(textareaRef.current?.selectionStart ?? 0)
}, [])
const handleTextareaKeyUp = useCallback(() => {
setCursorPos(textareaRef.current?.selectionStart ?? 0)
}, [])
const handleHashtagInsert = useCallback(
(tag: string) => {
const hashtag = tag.startsWith('#') ? tag : `#${tag}`
const { newText, newCursor } = insertAtCursor(content, cursorPos, hashtag)
setContent(newText)
setCursorPos(newCursor)
requestAnimationFrame(() => {
if (textareaRef.current) {
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursor, newCursor)
}
})
},
[content, cursorPos],
)
const handleMentionInsert = useCallback(
(username: string) => {
const mention = username.startsWith('@') ? username : `@${username}`
const { newText, newCursor } = insertAtCursor(content, cursorPos, mention)
setContent(newText)
setCursorPos(newCursor)
requestAnimationFrame(() => {
if (textareaRef.current) {
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursor, newCursor)
}
})
},
[content, cursorPos],
)
const handleEmojiSelect = useCallback(
(emoji: string) => {
const before = content.slice(0, cursorPos)
const after = content.slice(cursorPos)
const newText = `${before}${emoji}${after}`
if (newText.length <= MAX_CHARS) {
const newCursor = cursorPos + emoji.length
setContent(newText)
setCursorPos(newCursor)
requestAnimationFrame(() => {
if (textareaRef.current) {
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursor, newCursor)
}
})
}
},
[content, cursorPos],
)
const handleImagesDrop = useCallback((files: File[]) => {
const imageFiles = files.filter((f) => f.type.startsWith('image/'))
setImageFiles((prev) => {
const combined = [...prev, ...imageFiles]
return combined.slice(0, 10)
})
}, [])
const removeImage = useCallback((index: number) => {
setImageFiles((prev) => prev.filter((_, i) => i !== index))
}, [])
const handleScheduleChange = useCallback((e: ChangeEvent) => {
const val = e.target.value
setScheduledAt(val ? new Date(val) : null)
}, [])
const handleSubmit = useCallback(() => {
setErrorMsg(null)
if (!content.trim() && imageFiles.length === 0 && !videoUrl.trim()) {
setErrorMsg('Please add some text, media, or a video URL before posting.')
return
}
// When scheduling is toggled on, a future date/time is required — otherwise
// the post would publish immediately despite the "Schedule post" label.
if (scheduleEnabled) {
if (!scheduledAt) {
setErrorMsg('Please pick a date and time to schedule this post.')
return
}
if (scheduledAt.getTime() <= Date.now()) {
setErrorMsg('Scheduled time must be in the future.')
return
}
}
const payload: CreatePostPayload = {
content: content.trim(),
videoUrl: videoUrl.trim() || undefined,
repoFullName: linkedRepo?.fullName,
audience,
scheduledAt: scheduleEnabled ? scheduledAt?.toISOString() : undefined,
}
mutation.mutate(payload)
}, [content, imageFiles, videoUrl, linkedRepo, audience, scheduleEnabled, scheduledAt, mutation])
// ---------------------------------------------------------------------------
// Derived
// ---------------------------------------------------------------------------
const remaining = MAX_CHARS - content.length
const isOverLimit = remaining < 0
const isSubmitDisabled =
mutation.isPending ||
isOverLimit ||
(!content.trim() && imageFiles.length === 0 && !videoUrl.trim())
// Min datetime for schedule input (now + 5 minutes)
const minSchedule = new Date(Date.now() + 5 * 60 * 1000)
.toISOString()
.slice(0, 16)
// ---------------------------------------------------------------------------
// Render
// ---------------------------------------------------------------------------
if (mutation.isSuccess) {
return (
{scheduledAt ? 'Post scheduled!' : 'Post published!'}
{scheduledAt
? `Your post will be published on ${formatScheduleLabel(scheduledAt)}.`
: 'Your post is now live.'}
)
}
return (
{/* Header */}
Create post
{/* Error banner */}
{errorMsg && (
)}
{/* Composer card */}
{/* Text area */}
{/* Inline hashtag suggestions */}
{/* Inline mention suggestions */}
{/* Image previews */}
{imagePreviewUrls.length > 0 && (
{imagePreviewUrls.map((url, i) => (
))}
)}
{/* Linked repo badge */}
{linkedRepo && (
{linkedRepo.fullName}
)}
{/* Toolbar */}
{/* Image upload via DropZone */}
= 10}
ariaLabel="Upload images"
className="inline-flex"
>
{/* Emoji picker */}
{/* Repo linker */}
{/* Char counter */}
{remaining}
{/* Video URL input */}
{/* Audience selector */}
Audience
{(['public', 'followers'] as Audience[]).map((opt) => (
))}
{/* Schedule toggle */}
{scheduleEnabled ? 'Scheduled' : 'Post now'}
{scheduleEnabled && (
)}
{/* Preview */}
{showPreview && (
)}
{/* Submit */}
{/* Repo linker modal */}
{showRepoLinker && (
Link a repository
{
setLinkedRepo(repo)
setShowRepoLinker(false)
}}
onClose={() => setShowRepoLinker(false)}
/>
)}
)
}