Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

refactor(publishing): split UploadContent into small modules

spacesdrivec71417abc636
diff --git a/docs/architecture/data-flows/PUBLISHING.md b/docs/architecture/data-flows/PUBLISHING.md
index a51106d..fb31a5f 100644
--- a/docs/architecture/data-flows/PUBLISHING.md
+++ b/docs/architecture/data-flows/PUBLISHING.md
@@ -10,7 +10,7 @@ User selects account + uploads media + fills caption
api.getCloudinaryConfig() -> GET /api/cloudinary-config
-> returns { cloudName, uploadPreset }
- Browser uploads directly to Cloudinary using unsigned preset
+ Browser uploads directly to Cloudinary using unsigned preset (api.uploadToCloudinary)
-> Cloudinary returns public URL (e.g., https://res.cloudinary.com/cloud/image/upload/...)
│
▼
@@ -27,7 +27,8 @@ User selects account + uploads media + fills caption
api.getIGContainerStatus(containerId, accountId)
-> GET /api/ig-container/:containerId/status?accountId=:id
-> Backend: GET https://graph.instagram.com/v25.0/{containerId}?fields=status_code,status
- -> Poll every 3 seconds, timeout at 3 minutes
+ -> Poll every 3 seconds, up to 30 times (about 90 seconds); a single post then fails,
+ the bulk upload goes on to publish
-> Wait for status_code = 'FINISHED'
-> ERROR -> throw error, mark as failed
-> EXPIRED -> throw error
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index 88d5e6f..8d87e0e 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -35,7 +35,22 @@ frontend/src/
│ ├── accounts/
│ │ └── AccountManager.jsx <- Add/remove connected accounts
│ ├── publishing/
-│ │ └── UploadContent.jsx <- Instagram publish + scheduled post queue
+│ │ ├── UploadContent.jsx <- Page: tabs, Cloudinary alert, scheduled posts (default export)
+│ │ ├── SinglePostTab.jsx <- Single post form or its progress view
+│ │ ├── MediaPicker.jsx, CaptionBox.jsx, SinglePostSettings.jsx, ReelOptions.jsx, ScheduleFields.jsx, PostSummary.jsx
+│ │ ├── PublishProgress.jsx, PublishResult.jsx <- Upload, processing, done, scheduled and error states
+│ │ ├── BulkUploadTab.jsx <- Bulk queue, results and settings
+│ │ ├── BulkFileList.jsx, BulkFileItem.jsx, BulkResults.jsx, BulkSettings.jsx, BulkScheduleFields.jsx
+│ │ ├── ScheduledPostsSection.jsx <- Scheduled post table with filters and the overdue alert
+│ │ ├── ScheduledPostRow.jsx, ScheduledPostEditRow.jsx, ScheduledPostDialogs.jsx, OverdueAlert.jsx
+│ │ ├── AccountSelect.jsx, TypePicker.jsx, ScheduleToggle.jsx, ScheduleHint.jsx, IconInput.jsx, StatusBadge.jsx, NoInstagramAccount.jsx
+│ │ ├── useSinglePostForm.js, useSinglePostMedia.js <- Single post fields, file and cover
+│ │ ├── useSinglePublish.js, usePublishProgress.js <- Single post publish or schedule run
+│ │ ├── useBulkSettings.js, useBulkQueue.js, useBulkPublish.js <- Bulk settings, file queue, upload loop
+│ │ ├── useScheduledPosts.js, useScheduledPostEdit.js, useScheduledPostDelete.js
+│ │ ├── igPublishFlow.js <- Cloudinary upload, container polling, single post publish steps
+│ │ ├── publishConstants.js <- Content types, statuses, intervals, caption limit
+│ │ └── publishHelpers.js, scheduleHelpers.js, queueHelpers.js <- Pure helpers with *.test.js
│ ├── settings/
│ │ ├── Settings.jsx <- Theme, server keys, scheduling, platform requirements, links
│ │ └── SchedulingSetupGuide.jsx <- Optional GitHub backup scheduler steps for administrators
diff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.md
index 60d83ae..a7b0b5d 100644
--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md
+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md
@@ -105,7 +105,7 @@ frontend/src/
reddit/ RedditAnalytics, RedditPosts, RedditPostsAll, shared post table
tracked/ TrackedContent.jsx, TrackedCategory.jsx
publishing/
- UploadContent.jsx Instagram publishing + schedule queue
+ UploadContent.jsx Instagram publishing + schedule queue (page; components, hooks and helpers beside it)
accounts/
AccountManager.jsx Add/remove/refresh accounts
settings/
diff --git a/frontend/src/features/publishing/AccountSelect.jsx b/frontend/src/features/publishing/AccountSelect.jsx
new file mode 100644
index 0000000..42ea53a
--- /dev/null
+++ b/frontend/src/features/publishing/AccountSelect.jsx
@@ -0,0 +1,34 @@
+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+import { AccountAvatar } from '@/components/platform';
+
+export default function AccountSelect({ accounts, value, onChange, disabled }) {
+ const selected = accounts.find(account => account.id === value);
+ return (
+ <Select value={value} onValueChange={onChange} disabled={disabled}>
+ <SelectTrigger className="h-(--control-h-lg) w-full" aria-label="Instagram account">
+ {selected ? (
+ <span className="flex min-w-0 items-center gap-2">
+ <AccountAvatar account={selected} size="xs" />
+ <span className="truncate text-sm">{selected.title || selected.username}</span>
+ {selected.username && <span className="shrink-0 text-caption text-ink-faint">@{selected.username}</span>}
+ </span>
+ ) : (
+ <SelectValue placeholder="Choose an account" />
+ )}
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {accounts.map(account => (
+ <SelectItem key={account.id} value={account.id}>
+ <span className="flex items-center gap-2">
+ <AccountAvatar account={account} size="xs" />
+ <span className="truncate text-sm font-medium">{account.title || account.username}</span>
+ {account.username && <span className="shrink-0 text-caption text-ink-faint">@{account.username}</span>}
+ </span>
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ );
+}
diff --git a/frontend/src/features/publishing/BulkFileItem.jsx b/frontend/src/features/publishing/BulkFileItem.jsx
new file mode 100644
index 0000000..12e2d45
--- /dev/null
+++ b/frontend/src/features/publishing/BulkFileItem.jsx
@@ -0,0 +1,44 @@
+import { X } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Progress } from '@/components/ui/progress';
+import { Spinner } from '@/components/ui/spinner';
+import { Textarea } from '@/components/ui/textarea';
+import { cn } from '@/lib/utils';
+import StatusBadge from './StatusBadge';
+import { ACTIVE_BULK, BULK_STATUS } from './publishConstants';
+import { fileSizeMb, isVideoFile } from './queueHelpers.js';
+
+export default function BulkFileItem({ item, position, processing, onCaptionChange, onRemove }) {
+ const isActive = ACTIVE_BULK.includes(item.status);
+ return (
+ <li className={cn('flex items-start gap-3 rounded-field border p-3', isActive ? 'border-brand/40 bg-brand-soft/20' : 'border-line')}>
+ <div className="relative size-14 shrink-0 overflow-hidden rounded-control bg-surface-sunken">
+ {isVideoFile(item.file)
+ ? <video src={item.preview} muted className="size-full object-cover" />
+ : <img src={item.preview} alt="" className="size-full object-cover" />}
+ <span className="absolute top-0.5 left-0.5 rounded-sm bg-[#0C0809]/75 px-1 font-mono text-[0.5625rem] font-semibold text-white">{position}</span>
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="mb-1 flex items-center gap-2">
+ <span className="truncate text-sm font-medium text-ink">{item.file.name}</span>
+ <span className="shrink-0 text-caption text-ink-faint">{fileSizeMb(item.file, 1)} MB</span>
+ </div>
+ {item.status === 'pending' ? (
+ <Textarea value={item.caption} onChange={e => onCaptionChange(item.id, e.target.value)} placeholder={`Caption for file ${position}`} rows={1} className="min-h-9 text-small" aria-label={`Caption for file ${position}`} />
+ ) : (
+ <p className="truncate text-caption text-ink-muted">{item.caption || 'No caption'}</p>
+ )}
+ {item.status === 'uploading' && <Progress value={item.progress} className="mt-1.5" aria-label={`Upload progress for file ${position}`} />}
+ {item.error && <p className="mt-1 text-caption text-danger">Error: {item.error}</p>}
+ {item.mediaId && <p className="mt-1 font-mono text-caption text-success">Media ID {item.mediaId}</p>}
+ </div>
+ <div className="flex shrink-0 items-center gap-1.5">
+ {isActive && <Spinner className="size-3.5 text-brand" />}
+ <StatusBadge status={item.status} map={BULK_STATUS} />
+ {item.status === 'pending' && !processing && (
+ <Button variant="ghost" size="icon-xs" onClick={() => onRemove(item.id)} aria-label={`Remove ${item.file.name}`}><X /></Button>
+ )}
+ </div>
+ </li>
+ );
+}
diff --git a/frontend/src/features/publishing/BulkFileList.jsx b/frontend/src/features/publishing/BulkFileList.jsx
new file mode 100644
index 0000000..b94f75f
--- /dev/null
+++ b/frontend/src/features/publishing/BulkFileList.jsx
@@ -0,0 +1,51 @@
+import { FolderUp, Plus, Trash2 } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import SurfaceBox from '@/components/SurfaceBox';
+import BulkFileItem from './BulkFileItem';
+import { bulkFilesTitle } from './queueHelpers.js';
+
+export default function BulkFileList({ queue, bulkType }) {
+ const { files, processing, fileInputRef } = queue;
+ const openPicker = () => fileInputRef.current?.click();
+ const actions = (
+ <div className="flex gap-2">
+ {files.length > 0 && !processing && (
+ <Button size="sm" variant="ghost" onClick={queue.clearFiles} className="hover:bg-danger-soft hover:text-danger">
+ <Trash2 data-icon="inline-start" />Clear all
+ </Button>
+ )}
+ <Button size="sm" variant="outline" onClick={openPicker} disabled={processing}>
+ <Plus data-icon="inline-start" />Add files
+ </Button>
+ </div>
+ );
+ return (
+ <SurfaceBox title={bulkFilesTitle(files.length)} subheader={bulkType?.desc} secondary={actions}>
+ <input ref={fileInputRef} type="file" hidden multiple accept={bulkType?.accept || '*'} onChange={queue.handleFilesSelect} aria-label="Files to upload" />
+ {files.length === 0 ? (
+ <button
+ type="button"
+ onClick={openPicker}
+ className="flex w-full flex-col items-center gap-2 rounded-card border border-dashed border-line-strong/50 p-10 text-center transition-colors duration-(--duration-fast) hover:border-brand hover:bg-brand-soft/30 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
+ >
+ <FolderUp className="size-8 stroke-[1.5] text-ink-faint" />
+ <span className="text-sm font-medium text-ink">Choose several files</span>
+ <span className="text-caption text-ink-faint">Each file becomes its own post, published or scheduled in order.</span>
+ </button>
+ ) : (
+ <ul className="flex max-h-[34rem] flex-col gap-2 overflow-y-auto pr-1">
+ {files.map((item, index) => (
+ <BulkFileItem
+ key={item.id}
+ item={item}
+ position={index + 1}
+ processing={processing}
+ onCaptionChange={(id, caption) => queue.patchFile(id, { caption })}
+ onRemove={queue.removeFile}
+ />
+ ))}
+ </ul>
+ )}
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/publishing/BulkResults.jsx b/frontend/src/features/publishing/BulkResults.jsx
new file mode 100644
index 0000000..a612bc0
--- /dev/null
+++ b/frontend/src/features/publishing/BulkResults.jsx
@@ -0,0 +1,22 @@
+import { AlertCircle, Calendar, CheckCircle2 } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Progress } from '@/components/ui/progress';
+import SurfaceBox from '@/components/SurfaceBox';
+
+export default function BulkResults({ stats, processing }) {
+ const finished = stats.done + stats.scheduled + stats.errors;
+ return (
+ <SurfaceBox title={processing ? 'Working through the files' : 'Results'}>
+ <div className="flex flex-wrap gap-1.5">
+ <Badge variant="outline">{stats.total} total</Badge>
+ {stats.done > 0 && <Badge variant="success"><CheckCircle2 />{stats.done} published</Badge>}
+ {stats.scheduled > 0 && <Badge variant="warning"><Calendar />{stats.scheduled} scheduled</Badge>}
+ {stats.errors > 0 && <Badge variant="destructive"><AlertCircle />{stats.errors} failed</Badge>}
+ {stats.pending > 0 && <Badge variant="secondary">{stats.pending} pending</Badge>}
+ </div>
+ {processing && (
+ <Progress value={(finished / Math.max(1, stats.total)) * 100} className="mt-3" aria-label="Overall progress" />
+ )}
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/publishing/BulkScheduleFields.jsx b/frontend/src/features/publishing/BulkScheduleFields.jsx
new file mode 100644
index 0000000..b85e85f
--- /dev/null
+++ b/frontend/src/features/publishing/BulkScheduleFields.jsx
@@ -0,0 +1,67 @@
+import { Info } from 'lucide-react';
+import { Alert, AlertDescription } from '@/components/ui/alert';
+import { Input } from '@/components/ui/input';
+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+import { FieldRow } from '@/components/DetailPanel';
+import ScheduleHint from './ScheduleHint';
+import ScheduleToggle from './ScheduleToggle';
+import { BULK_INTERVAL_OPTIONS } from './publishConstants';
+import { bulkScheduledTime } from './publishHelpers.js';
+import { intervalLabel } from './queueHelpers.js';
+import { utcDateInput } from './scheduleHelpers.js';
+
+const INTERVAL_ITEMS = BULK_INTERVAL_OPTIONS.map(option => ({ value: String(option.value), label: option.label }));
+
+function SpreadOutFields({ settings, setSetting, pending, processing }) {
+ const { startDate, startTime, interval } = settings;
+ const firstPost = new Date(`${startDate}T${startTime}`);
+ return (
+ <>
+ <div className="grid grid-cols-2 gap-2">
+ <Input type="date" value={startDate} onChange={e => setSetting('startDate', e.target.value)} min={utcDateInput()} disabled={processing} aria-label="Start date" />
+ <Input type="time" value={startTime} onChange={e => setSetting('startTime', e.target.value)} disabled={processing} aria-label="Start time" />
+ </div>
+ <ScheduleHint />
+ <Select value={String(interval)} onValueChange={value => setSetting('interval', Number(value))} disabled={processing} items={INTERVAL_ITEMS}>
+ <SelectTrigger className="w-full" aria-label="Interval"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {BULK_INTERVAL_OPTIONS.map(option => <SelectItem key={option.value} value={String(option.value)}>{option.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ {startDate && startTime && pending > 0 && (
+ <Alert variant="info">
+ <Info />
+ <AlertDescription>
+ {pending} posts from {firstPost.toLocaleString()}, {intervalLabel(interval)} apart. The last one goes out {bulkScheduledTime(firstPost, pending - 1, interval).toLocaleString()}.
+ </AlertDescription>
+ </Alert>
+ )}
+ </>
+ );
+}
+
+export default function BulkScheduleFields({ settings, setSetting, pending, processing }) {
+ const { scheduleMode } = settings;
+ return (
+ <div className="flex flex-col gap-4 border-t border-divider pt-5">
+ <FieldRow label="When">
+ <ScheduleToggle
+ scheduled={scheduleMode}
+ onChange={scheduled => setSetting('scheduleMode', scheduled)}
+ disabled={processing}
+ nowLabel="Publish all now"
+ laterLabel="Spread out"
+ />
+ </FieldRow>
+ {scheduleMode && <SpreadOutFields settings={settings} setSetting={setSetting} pending={pending} processing={processing} />}
+ {!scheduleMode && pending > 0 && (
+ <Alert>
+ <Info />
+ <AlertDescription>{pending} files upload and publish one at a time. Instagram allows 100 posts per account every 24 hours.</AlertDescription>
+ </Alert>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/features/publishing/BulkSettings.jsx b/frontend/src/features/publishing/BulkSettings.jsx
new file mode 100644
index 0000000..2d4b7e2
--- /dev/null
+++ b/frontend/src/features/publishing/BulkSettings.jsx
@@ -0,0 +1,70 @@
+import { AtSign, Calendar, Copy, MapPin, Send, Square, UserPlus } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Switch } from '@/components/ui/switch';
+import { Textarea } from '@/components/ui/textarea';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import DetailPanel, { FieldRow } from '@/components/DetailPanel';
+import AccountSelect from './AccountSelect';
+import BulkScheduleFields from './BulkScheduleFields';
+import IconInput from './IconInput';
+import TypePicker from './TypePicker';
+import { bulkActionLabel } from './queueHelpers.js';
+
+function BulkFooter({ settings, pending, processing, onStart, onStop }) {
+ if (processing) {
+ return (
+ <Button variant="destructive" size="lg" className="w-full" onClick={onStop}>
+ <Square data-icon="inline-start" />Stop after this file
+ </Button>
+ );
+ }
+ return (
+ <Button size="lg" className="w-full" onClick={onStart} disabled={pending === 0 || !settings.account || !settings.contentType}>
+ {settings.scheduleMode ? <Calendar data-icon="inline-start" /> : <Send data-icon="inline-start" />}
+ {bulkActionLabel(settings.scheduleMode, pending)}
+ </Button>
+ );
+}
+
+export default function BulkSettings({ bulk, igAccounts, pending, processing, onStart, onStop, onApplyCaption }) {
+ const { settings, setSetting } = bulk;
+ const footer = <BulkFooter settings={settings} pending={pending} processing={processing} onStart={onStart} onStop={onStop} />;
+ return (
+ <DetailPanel title="Bulk settings" footer={footer}>
+ <FieldRow label="Account">
+ <AccountSelect accounts={igAccounts} value={settings.account} onChange={value => setSetting('account', value)} disabled={processing} />
+ </FieldRow>
+ <FieldRow label="Content type">
+ <TypePicker value={settings.contentType} onChange={value => setSetting('contentType', value)} disabled={processing} />
+ </FieldRow>
+ <FieldRow label="Shared caption" hint="Copies this caption onto every pending file." htmlFor="bulk-caption">
+ <div className="flex gap-2">
+ <Textarea id="bulk-caption" value={settings.sharedCaption} onChange={e => setSetting('sharedCaption', e.target.value)} placeholder="Caption for all files" rows={2} disabled={processing} className="flex-1" />
+ <Tooltip>
+ <TooltipTrigger render={<Button variant="outline" size="icon" onClick={onApplyCaption} disabled={!settings.sharedCaption || processing} aria-label="Apply caption to all pending files" />}>
+ <Copy />
+ </TooltipTrigger>
+ <TooltipContent>Apply to all pending files</TooltipContent>
+ </Tooltip>
+ </div>
+ </FieldRow>
+ <FieldRow label="Collaborators" hint="Applied to every post." htmlFor="bulk-collaborators">
+ <IconInput id="bulk-collaborators" icon={UserPlus} value={settings.collaborators} onChange={e => setSetting('collaborators', e.target.value)} placeholder="username1, username2" disabled={processing} />
+ </FieldRow>
+ <FieldRow label="Tagged people" hint="Applied to every post." htmlFor="bulk-tags">
+ <IconInput id="bulk-tags" icon={AtSign} value={settings.userTags} onChange={e => setSetting('userTags', e.target.value)} placeholder="@username1, @username2" disabled={processing} />
+ </FieldRow>
+ <FieldRow label="Location" hint="Facebook Page ID, applied to every post." htmlFor="bulk-location">
+ <IconInput id="bulk-location" icon={MapPin} value={settings.locationId} onChange={e => setSetting('locationId', e.target.value)} placeholder="Location ID" disabled={processing} />
+ </FieldRow>
+ {settings.contentType === 'REELS' && (
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-sm font-medium text-ink">Share Reels to feed</p>
+ <Switch checked={settings.shareToFeed} onCheckedChange={checked => setSetting('shareToFeed', checked)} disabled={processing} aria-label="Share Reels to feed" />
+ </div>
+ )}
+
+ <BulkScheduleFields settings={settings} setSetting={setSetting} pending={pending} processing={processing} />
+ </DetailPanel>
+ );
+}
diff --git a/frontend/src/features/publishing/BulkUploadTab.jsx b/frontend/src/features/publishing/BulkUploadTab.jsx
new file mode 100644
index 0000000..7942a0d
--- /dev/null
+++ b/frontend/src/features/publishing/BulkUploadTab.jsx
@@ -0,0 +1,28 @@
+import BulkFileList from './BulkFileList';
+import BulkResults from './BulkResults';
+import BulkSettings from './BulkSettings';
+import { contentTypeOf } from './publishConstants';
+import { bulkStatsOf } from './queueHelpers.js';
+
+export default function BulkUploadTab({ bulk, queue, bulkPublish, igAccounts }) {
+ const stats = bulkStatsOf(queue.files);
+ const bulkType = contentTypeOf(bulk.settings.contentType);
+ const showResults = queue.processing || stats.done > 0 || stats.scheduled > 0 || stats.errors > 0;
+ return (
+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,1fr)_28rem]">
+ <div className="flex min-w-0 flex-col gap-4">
+ <BulkFileList queue={queue} bulkType={bulkType} />
+ {showResults && <BulkResults stats={stats} processing={queue.processing} />}
+ </div>
+ <BulkSettings
+ bulk={bulk}
+ igAccounts={igAccounts}
+ pending={stats.pending}
+ processing={queue.processing}
+ onStart={bulkPublish.handleBulkProcess}
+ onStop={bulkPublish.stopBulk}
+ onApplyCaption={queue.applySharedCaption}
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/features/publishing/CaptionBox.jsx b/frontend/src/features/publishing/CaptionBox.jsx
new file mode 100644
index 0000000..cc819c6
--- /dev/null
+++ b/frontend/src/features/publishing/CaptionBox.jsx
@@ -0,0 +1,24 @@
+import { Textarea } from '@/components/ui/textarea';
+import SurfaceBox from '@/components/SurfaceBox';
+import { cn } from '@/lib/utils';
+import { CAPTION_LIMIT } from './publishConstants';
+
+export default function CaptionBox({ caption, onChange }) {
+ const nearLimit = caption.length > CAPTION_LIMIT * 0.9;
+ return (
+ <SurfaceBox title="Caption">
+ <Textarea
+ value={caption}
+ onChange={e => onChange(e.target.value)}
+ placeholder="Write a caption. Add #hashtags and @mentions."
+ rows={7}
+ maxLength={CAPTION_LIMIT}
+ aria-label="Caption"
+ className="min-h-40 border-0 bg-transparent px-0 text-base leading-6 shadow-none hover:border-0 focus-visible:outline-none md:text-base"
+ />
+ <p className={cn('mt-2 text-right text-caption tabular-nums', nearLimit ? 'text-warning' : 'text-ink-faint')}>
+ {caption.length.toLocaleString()} / {CAPTION_LIMIT.toLocaleString()}
+ </p>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/publishing/IconInput.jsx b/frontend/src/features/publishing/IconInput.jsx
new file mode 100644
index 0000000..7d2970e
--- /dev/null
+++ b/frontend/src/features/publishing/IconInput.jsx
@@ -0,0 +1,11 @@
+import { Input } from '@/components/ui/input';
+
+export default function IconInput({ icon, ...props }) {
+ const Icon = icon;
+ return (
+ <div className="relative">
+ <Icon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 stroke-[1.75] text-ink-faint" />
+ <Input className="pl-9" {...props} />
+ </div>
+ );
+}
diff --git a/frontend/src/features/publishing/MediaPicker.jsx b/frontend/src/features/publishing/MediaPicker.jsx
new file mode 100644
index 0000000..e970e0c
--- /dev/null
+++ b/frontend/src/features/publishing/MediaPicker.jsx
@@ -0,0 +1,63 @@
+import { Upload, X } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import SurfaceBox from '@/components/SurfaceBox';
+import { cn } from '@/lib/utils';
+import TypePicker from './TypePicker';
+import { fileSizeMb, isVideoFile } from './queueHelpers.js';
+
+function MediaPreview({ file, filePreview, selectedType, onClear }) {
+ return (
+ <div className="flex flex-col gap-4 sm:flex-row sm:items-start">
+ <div className="relative w-full shrink-0 overflow-hidden rounded-control bg-surface-sunken sm:w-52">
+ {isVideoFile(file) ? (
+ <video src={filePreview} controls muted className="max-h-72 w-full bg-black object-contain" />
+ ) : (
+ <img src={filePreview} alt="Selected media preview" className="max-h-72 w-full object-contain" />
+ )}
+ <button
+ type="button"
+ onClick={onClear}
+ aria-label="Remove file"
+ className="absolute top-2 right-2 flex size-7 items-center justify-center rounded-full bg-[#0C0809]/75 text-white transition-colors hover:bg-brand"
+ >
+ <X className="size-3.5" />
+ </button>
+ </div>
+ <div className="min-w-0">
+ <p className="truncate text-sm font-semibold text-ink">{file.name}</p>
+ <p className="text-small text-ink-muted">{fileSizeMb(file, 2)} MB, {file.type}</p>
+ <Badge variant="default" className="mt-2">{selectedType?.label}</Badge>
+ </div>
+ </div>
+ );
+}
+
+export default function MediaPicker({ form, selectedType }) {
+ const { contentType, file, fileInputRef } = form;
+ return (
+ <SurfaceBox title="Media" subheader={selectedType ? selectedType.desc : 'Choose what you are posting, then add the file.'}>
+ <div className="flex flex-col gap-4">
+ <TypePicker value={contentType} onChange={form.changeContentType} />
+ {file ? (
+ <MediaPreview file={file} filePreview={form.filePreview} selectedType={selectedType} onClear={form.clearFile} />
+ ) : (
+ <button
+ type="button"
+ onClick={() => contentType && fileInputRef.current?.click()}
+ disabled={!contentType}
+ className={cn(
+ 'flex w-full flex-col items-center gap-2 rounded-card border border-dashed p-10 text-center transition-colors duration-(--duration-fast)',
+ 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
+ contentType ? 'border-line-strong/50 hover:border-brand hover:bg-brand-soft/30' : 'cursor-not-allowed border-line opacity-60',
+ )}
+ >
+ <Upload className="size-8 stroke-[1.5] text-ink-faint" />
+ <span className="text-sm font-medium text-ink">{contentType ? 'Choose a file' : 'Choose a content type first'}</span>
+ {selectedType && <span className="text-caption text-ink-faint">{selectedType.desc}</span>}
+ </button>
+ )}
+ <input ref={fileInputRef} type="file" hidden accept={selectedType?.accept || '*'} onChange={form.handleFileSelect} aria-label="Media file" />
+ </div>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/publishing/NoInstagramAccount.jsx b/frontend/src/features/publishing/NoInstagramAccount.jsx
new file mode 100644
index 0000000..4d64333
--- /dev/null
+++ b/frontend/src/features/publishing/NoInstagramAccount.jsx
@@ -0,0 +1,23 @@
+import { Link } from 'react-router-dom';
+import { Plus } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import PageHeader from '@/components/PageHeader';
+import SurfaceBox from '@/components/SurfaceBox';
+import { EmptyState } from '@/components/StateViews';
+import { InstagramIcon } from '@/components/brand/platform-icons';
+
+export default function NoInstagramAccount() {
+ return (
+ <div className="flex flex-col gap-6">
+ <PageHeader title="Publish" description="Post and schedule photos, Reels and Stories to Instagram." />
+ <SurfaceBox>
+ <EmptyState
+ icon={<InstagramIcon />}
+ title="Connect an Instagram account to publish"
+ description="Publishing works with Instagram Business and Creator accounts. YouTube publishing is not available yet."
+ action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add an account</Button>}
+ />
+ </SurfaceBox>
+ </div>
+ );
+}
diff --git a/frontend/src/features/publishing/OverdueAlert.jsx b/frontend/src/features/publishing/OverdueAlert.jsx
new file mode 100644
index 0000000..b8c47e2
--- /dev/null
+++ b/frontend/src/features/publishing/OverdueAlert.jsx
@@ -0,0 +1,18 @@
+import { Link } from 'react-router-dom';
+import { AlertCircle } from 'lucide-react';
+import { Alert, AlertDescription } from '@/components/ui/alert';
+import { ADMIN_EMAIL, adminMailto } from '@/lib/contact';
+import { overdueLead } from './scheduleHelpers.js';
+
+export default function OverdueAlert({ count }) {
+ return (
+ <Alert variant="warning">
+ <AlertCircle />
+ <AlertDescription>
+ {overdueLead(count)} more than 30 minutes past their time and still pending, so the scheduler on this server is not running. Email the administrator at{' '}
+ <a href={adminMailto('Scheduled posts are not publishing on Twiligent')} className="font-semibold underline underline-offset-4">{ADMIN_EMAIL}</a>.
+ If you run this instance, follow the checks in <Link to="/settings#scheduling" className="font-semibold underline underline-offset-4">Settings, Scheduled publishing</Link>.
+ </AlertDescription>
+ </Alert>
+ );
+}
diff --git a/frontend/src/features/publishing/PostSummary.jsx b/frontend/src/features/publishing/PostSummary.jsx
new file mode 100644
index 0000000..91a8749
--- /dev/null
+++ b/frontend/src/features/publishing/PostSummary.jsx
@@ -0,0 +1,22 @@
+import { fileSizeMb } from './queueHelpers.js';
+import { goesLiveLabel } from './scheduleHelpers.js';
+
+function SummaryRow({ label, children }) {
+ return (
+ <div className="flex items-center justify-between gap-3 text-small">
+ <span className="text-ink-faint">{label}</span>
+ <span className="min-w-0 truncate font-medium text-ink">{children}</span>
+ </div>
+ );
+}
+
+export default function PostSummary({ selectedAcct, selectedType, file, fields }) {
+ return (
+ <div className="flex flex-col gap-2 rounded-control bg-surface-sunken/60 p-3">
+ <SummaryRow label="Account">{selectedAcct ? `@${selectedAcct.username || selectedAcct.title}` : '-'}</SummaryRow>
+ <SummaryRow label="Type">{selectedType?.label || '-'}</SummaryRow>
+ <SummaryRow label="File">{file ? `${fileSizeMb(file, 1)} MB` : '-'}</SummaryRow>
+ <SummaryRow label="Goes live">{goesLiveLabel(fields)}</SummaryRow>
+ </div>
+ );
+}
diff --git a/frontend/src/features/publishing/PublishProgress.jsx b/frontend/src/features/publishing/PublishProgress.jsx
new file mode 100644
index 0000000..733c398
--- /dev/null
+++ b/frontend/src/features/publishing/PublishProgress.jsx
@@ -0,0 +1,35 @@
+import { Upload } from 'lucide-react';
+import { Progress } from '@/components/ui/progress';
+import { Spinner } from '@/components/ui/spinner';
+import SurfaceBox from '@/components/SurfaceBox';
+import PublishResult from './PublishResult';
+import { progressHeading } from './queueHelpers.js';
+
+const WORKING_STATUSES = ['creating-container', 'publishing', 'scheduling', 'processing'];
+
+export default function PublishProgress({ progress, ...resultProps }) {
+ const { publishStatus, statusMessage, uploadProgress } = progress;
+ return (
+ <SurfaceBox>
+ <div role="status" className="flex flex-col items-center gap-3 py-10 text-center">
+ {publishStatus === 'uploading-cloudinary' && (
+ <>
+ <Upload className="size-10 stroke-[1.5] text-ink-muted" />
+ <h2 className="font-heading text-section font-semibold text-ink">Uploading media</h2>
+ <Progress value={uploadProgress} className="w-72 max-w-full" aria-label="Upload progress" />
+ <p className="text-small text-ink-muted tabular-nums">{uploadProgress}% uploaded</p>
+ </>
+ )}
+ {WORKING_STATUSES.includes(publishStatus) && (
+ <>
+ <Spinner className="size-10 text-brand" />
+ <h2 className="font-heading text-section font-semibold text-ink">{progressHeading(publishStatus)}</h2>
+ <p className="text-small text-ink-muted">{statusMessage}</p>
+ {publishStatus === 'processing' && <p className="text-caption text-ink-faint">Videos can take a minute.</p>}
+ </>
+ )}
+ <PublishResult progress={progress} {...resultProps} />
+ </div>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/publishing/PublishResult.jsx b/frontend/src/features/publishing/PublishResult.jsx
new file mode 100644
index 0000000..f61939a
--- /dev/null
+++ b/frontend/src/features/publishing/PublishResult.jsx
@@ -0,0 +1,52 @@
+import { AlertCircle, Calendar, CheckCircle2, ExternalLink, Plus } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+
+export default function PublishResult({ progress, selectedType, selectedAcct, scheduleMode, onReset }) {
+ const { publishStatus, statusMessage, publishedMediaId } = progress;
+
+ if (publishStatus === 'done') {
+ return (
+ <>
+ <span className="flex size-12 items-center justify-center rounded-full bg-success-soft text-success"><CheckCircle2 className="size-6" /></span>
+ <h2 className="font-heading text-page-title font-semibold text-ink">Published</h2>
+ <p className="text-sm text-ink-muted">Your {selectedType?.label?.toLowerCase()} is live on Instagram.</p>
+ {publishedMediaId && <Badge variant="outline" className="font-mono">Media ID {publishedMediaId}</Badge>}
+ <div className="mt-2 flex gap-2">
+ <Button onClick={onReset}><Plus data-icon="inline-start" />Publish another</Button>
+ {selectedAcct?.username && (
+ <Button variant="outline" render={<a href={`https://instagram.com/${selectedAcct.username}`} target="_blank" rel="noopener noreferrer" />}>
+ <ExternalLink data-icon="inline-start" />View profile
+ </Button>
+ )}
+ </div>
+ </>
+ );
+ }
+
+ if (publishStatus === 'scheduled') {
+ return (
+ <>
+ <span className="flex size-12 items-center justify-center rounded-full bg-warning-soft text-warning"><Calendar className="size-6" /></span>
+ <h2 className="font-heading text-page-title font-semibold text-ink">Post scheduled</h2>
+ <p className="text-sm text-ink-muted">{statusMessage}</p>
+ <p className="max-w-md text-small text-ink-faint">The server publishes it within 15 minutes after that time, even when this browser is closed. Track it under Scheduled posts below.</p>
+ <Button onClick={onReset} className="mt-2"><Plus data-icon="inline-start" />Schedule another</Button>
+ </>
+ );
+ }
+
+ if (publishStatus !== 'error') return null;
+
+ return (
+ <>
+ <span className="flex size-12 items-center justify-center rounded-full bg-danger-soft text-danger"><AlertCircle className="size-6" /></span>
+ <h2 className="font-heading text-page-title font-semibold text-ink"><span className="sr-only">Error: </span>{scheduleMode ? 'Scheduling failed' : 'Publishing failed'}</h2>
+ <p className="max-w-md text-sm text-ink-muted">{statusMessage}</p>
+ <div className="mt-2 flex gap-2">
+ <Button onClick={progress.retry}>Try again</Button>
+ <Button variant="outline" onClick={onReset}>Start over</Button>
+ </div>
+ </>
+ );
+}
diff --git a/frontend/src/features/publishing/ReelOptions.jsx b/frontend/src/features/publishing/ReelOptions.jsx
new file mode 100644
index 0000000..39691da
--- /dev/null
+++ b/frontend/src/features/publishing/ReelOptions.jsx
@@ -0,0 +1,47 @@
+import { Camera, Clock, Music, X } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Switch } from '@/components/ui/switch';
+import { FieldRow } from '@/components/DetailPanel';
+import IconInput from './IconInput';
+
+function CoverPicker({ form }) {
+ const { coverFile, coverInputRef } = form;
+ return (
+ <FieldRow label="Cover image" hint="Optional JPEG.">
+ {coverFile ? (
+ <div className="flex items-center gap-3 rounded-control border border-line p-2">
+ <img src={form.coverPreview} alt="Cover preview" className="size-10 rounded-sm object-cover" />
+ <span className="min-w-0 flex-1 truncate text-small text-ink">{coverFile.name}</span>
+ <Button variant="ghost" size="icon-xs" onClick={form.clearCover} aria-label="Remove cover"><X /></Button>
+ </div>
+ ) : (
+ <Button variant="outline" onClick={() => coverInputRef.current?.click()} className="justify-start">
+ <Camera data-icon="inline-start" />Choose a cover
+ </Button>
+ )}
+ <input ref={coverInputRef} type="file" hidden accept="image/jpeg" onChange={form.handleCoverSelect} aria-label="Cover image" />
+ </FieldRow>
+ );
+}
+
+export default function ReelOptions({ form }) {
+ const { fields, setField } = form;
+ return (
+ <div className="flex flex-col gap-5 border-t border-divider pt-5">
+ <div className="flex items-center justify-between gap-3">
+ <div>
+ <p className="text-sm font-medium text-ink">Share to feed</p>
+ <p className="text-caption text-ink-faint">Show the Reel on the profile grid as well.</p>
+ </div>
+ <Switch checked={fields.shareToFeed} onCheckedChange={checked => setField('shareToFeed', checked)} aria-label="Share to feed" />
+ </div>
+ <FieldRow label="Audio name" hint="Optional" htmlFor="audio-name">
+ <IconInput id="audio-name" icon={Music} value={fields.audioName} onChange={e => setField('audioName', e.target.value)} placeholder="Original audio" />
+ </FieldRow>
+ <FieldRow label="Thumbnail offset" hint="Milliseconds into the video to use as the thumbnail." htmlFor="thumb-offset">
+ <IconInput id="thumb-offset" icon={Clock} type="number" min="0" value={fields.thumbOffset} onChange={e => setField('thumbOffset', e.target.value)} placeholder="0" />
+ </FieldRow>
+ <CoverPicker form={form} />
+ </div>
+ );
+}
diff --git a/frontend/src/features/publishing/ScheduleFields.jsx b/frontend/src/features/publishing/ScheduleFields.jsx
new file mode 100644
index 0000000..3e477a2
--- /dev/null
+++ b/frontend/src/features/publishing/ScheduleFields.jsx
@@ -0,0 +1,24 @@
+import { Input } from '@/components/ui/input';
+import { FieldRow } from '@/components/DetailPanel';
+import ScheduleHint from './ScheduleHint';
+import ScheduleToggle from './ScheduleToggle';
+import { utcDateInput } from './scheduleHelpers.js';
+
+export default function ScheduleFields({ fields, setField }) {
+ return (
+ <div className="flex flex-col gap-4 border-t border-divider pt-5">
+ <FieldRow label="When">
+ <ScheduleToggle scheduled={fields.scheduleMode} onChange={scheduled => setField('scheduleMode', scheduled)} />
+ </FieldRow>
+ {fields.scheduleMode && (
+ <>
+ <div className="grid grid-cols-2 gap-2">
+ <Input type="date" value={fields.scheduleDate} onChange={e => setField('scheduleDate', e.target.value)} min={utcDateInput()} aria-label="Schedule date" />
+ <Input type="time" value={fields.scheduleTime} onChange={e => setField('scheduleTime', e.target.value)} aria-label="Schedule time" />
+ </div>
+ <ScheduleHint />
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/features/publishing/ScheduleHint.jsx b/frontend/src/features/publishing/ScheduleHint.jsx
new file mode 100644
index 0000000..2754610
--- /dev/null
+++ b/frontend/src/features/publishing/ScheduleHint.jsx
@@ -0,0 +1,10 @@
+import { Link } from 'react-router-dom';
+
+export default function ScheduleHint() {
+ return (
+ <p className="text-caption text-ink-faint">
+ The server publishes the post within 15 minutes after this time, even with this page closed. Keep the account connected until then.{' '}
+ <Link to="/settings#scheduling" className="font-medium text-brand-text underline-offset-4 hover:underline">How scheduling works</Link>
+ </p>
+ );
+}
diff --git a/frontend/src/features/publishing/ScheduleToggle.jsx b/frontend/src/features/publishing/ScheduleToggle.jsx
new file mode 100644
index 0000000..07da4c8
--- /dev/null
+++ b/frontend/src/features/publishing/ScheduleToggle.jsx
@@ -0,0 +1,13 @@
+import { Calendar, Send } from 'lucide-react';
+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
+
+export default function ScheduleToggle({ scheduled, onChange, disabled, nowLabel = 'Publish now', laterLabel = 'Schedule' }) {
+ return (
+ <Tabs value={scheduled ? 'later' : 'now'} onValueChange={value => onChange(value === 'later')}>
+ <TabsList variant="segmented" className="w-full">
+ <TabsTrigger value="now" disabled={disabled}><Send />{nowLabel}</TabsTrigger>
+ <TabsTrigger value="later" disabled={disabled}><Calendar />{laterLabel}</TabsTrigger>
+ </TabsList>
+ </Tabs>
+ );
+}
diff --git a/frontend/src/features/publishing/ScheduledPostDialogs.jsx b/frontend/src/features/publishing/ScheduledPostDialogs.jsx
new file mode 100644
index 0000000..0a139b5
--- /dev/null
+++ b/frontend/src/features/publishing/ScheduledPostDialogs.jsx
@@ -0,0 +1,33 @@
+import ConfirmDialog from '@/components/ConfirmDialog';
+
+export default function ScheduledPostDialogs({ removal }) {
+ const { pendingDelete, deleting } = removal;
+ const isPublished = pendingDelete?.status === 'published';
+ return (
+ <>
+ <ConfirmDialog
+ open={removal.confirmDeleteAll}
+ onOpenChange={removal.setConfirmDeleteAll}
+ title="Delete all scheduled posts?"
+ description="Every record is removed: pending, published and failed. Pending posts will not go out. Posts already on Instagram stay live; only Twiligent's records are deleted. Posts that are publishing right now are kept."
+ confirmLabel="Delete all"
+ onConfirm={removal.handleDeleteAll}
+ busy={deleting}
+ hold
+ />
+
+ <ConfirmDialog
+ open={!!pendingDelete}
+ onOpenChange={open => { if (!open) removal.setPendingDelete(null); }}
+ title={isPublished ? 'Remove this record?' : 'Delete this scheduled post?'}
+ description={isPublished
+ ? 'The post stays live on Instagram. Only the record in Twiligent is removed.'
+ : 'It will not be published. The uploaded media stays in Cloudinary.'}
+ confirmLabel={isPublished ? 'Remove' : 'Delete'}
+ onConfirm={removal.handleDeleteScheduled}
+ busy={deleting}
+ hold
+ />
+ </>
+ );
+}
diff --git a/frontend/src/features/publishing/ScheduledPostEditRow.jsx b/frontend/src/features/publishing/ScheduledPostEditRow.jsx
new file mode 100644
index 0000000..36e7b81
--- /dev/null
+++ b/frontend/src/features/publishing/ScheduledPostEditRow.jsx
@@ -0,0 +1,33 @@
+import { CheckCircle2 } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Spinner } from '@/components/ui/spinner';
+import { TableCell, TableRow } from '@/components/ui/table';
+import { Textarea } from '@/components/ui/textarea';
+import { CAPTION_LIMIT } from './publishConstants';
+import { utcDateInput } from './scheduleHelpers.js';
+
+export default function ScheduledPostEditRow({ editor }) {
+ const { draft, setDraftField, savingEdit } = editor;
+ return (
+ <TableRow className="hover:bg-transparent">
+ <TableCell colSpan={9} className="whitespace-normal bg-surface-sunken/40 p-0">
+ <div className="flex flex-col gap-3 p-4">
+ <Textarea value={draft.caption} onChange={e => setDraftField('caption', e.target.value)} rows={3} aria-label="Caption" maxLength={CAPTION_LIMIT} />
+ <p className="text-caption text-ink-faint tabular-nums">{draft.caption.length.toLocaleString()} / {CAPTION_LIMIT.toLocaleString()}</p>
+ <div className="flex flex-wrap gap-2">
+ <Input type="date" value={draft.date} onChange={e => setDraftField('date', e.target.value)} min={utcDateInput()} className="w-44" aria-label="Date" />
+ <Input type="time" value={draft.time} onChange={e => setDraftField('time', e.target.value)} className="w-36" aria-label="Time" />
+ </div>
+ <div className="flex justify-end gap-2">
+ <Button size="sm" variant="outline" onClick={editor.cancelEdit}>Cancel</Button>
+ <Button size="sm" onClick={editor.handleSaveEdit} disabled={savingEdit}>
+ {savingEdit ? <Spinner className="size-3.5" /> : <CheckCircle2 data-icon="inline-start" />}
+ {savingEdit ? 'Saving' : 'Save changes'}
+ </Button>
+ </div>
+ </div>
+ </TableCell>
+ </TableRow>
+ );
+}
diff --git a/frontend/src/features/publishing/ScheduledPostRow.jsx b/frontend/src/features/publishing/ScheduledPostRow.jsx
new file mode 100644
index 0000000..239d9d6
--- /dev/null
+++ b/frontend/src/features/publishing/ScheduledPostRow.jsx
@@ -0,0 +1,88 @@
+import { CheckCircle2, Image as ImageIcon, Pencil, Trash2, X } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { TableCell, TableRow } from '@/components/ui/table';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { AccountAvatar } from '@/components/platform';
+import { cn } from '@/lib/utils';
+import ScheduledPostEditRow from './ScheduledPostEditRow';
+import StatusBadge from './StatusBadge';
+import { POST_STATUS, contentTypeOf } from './publishConstants';
+import { formatScheduleDate, isPastDue } from './scheduleHelpers.js';
+
+function PostActions({ post, isEditing, editor, onDelete }) {
+ // the publish flow never sets a 'scheduled' status, the check is kept as it was
+ const canEdit = post.status === 'pending' || post.status === 'scheduled';
+ const deleteLabel = post.status === 'published' ? 'Remove record' : 'Delete scheduled post';
+ return (
+ <TableCell className="text-right whitespace-nowrap">
+ {canEdit && !isEditing && (
+ <Tooltip>
+ <TooltipTrigger render={<Button variant="ghost" size="icon-xs" onClick={() => editor.startEditPost(post)} aria-label="Edit scheduled post" />}><Pencil /></TooltipTrigger>
+ <TooltipContent>Edit</TooltipContent>
+ </Tooltip>
+ )}
+ {isEditing && <Button variant="ghost" size="icon-xs" onClick={editor.cancelEdit} aria-label="Cancel editing"><X /></Button>}
+ {post.status !== 'publishing' && (
+ <Tooltip>
+ <TooltipTrigger render={<Button variant="ghost" size="icon-xs" onClick={() => onDelete(post)} aria-label={deleteLabel} className="hover:bg-danger-soft hover:text-danger" />}><Trash2 /></TooltipTrigger>
+ <TooltipContent>{post.status === 'published' ? 'Remove record' : 'Delete'}</TooltipContent>
+ </Tooltip>
+ )}
+ </TableCell>
+ );
+}
+
+export default function ScheduledPostRow({ post, position, account, editor, onDelete }) {
+ const typeInfo = contentTypeOf(post.mediaType);
+ const TypeIcon = typeInfo?.icon || ImageIcon;
+ const isEditing = editor.draft.postId === post.id;
+ const pastDue = isPastDue(post);
+ return (
+ <>
+ <TableRow data-state={isEditing ? 'selected' : undefined}>
+ <TableCell className="text-right font-mono text-caption text-ink-faint">{position}</TableCell>
+ <TableCell>
+ <span className="flex items-center gap-2">
+ {account && <AccountAvatar account={account} size="xs" />}
+ <span className="text-small font-medium text-ink">{account?.username ? `@${account.username}` : post.accountId}</span>
+ </span>
+ </TableCell>
+ <TableCell>
+ <span className="flex items-center gap-1.5 text-small text-ink-muted"><TypeIcon className="size-3.5" />{typeInfo?.label || post.mediaType}</span>
+ </TableCell>
+ <TableCell>
+ <Tooltip>
+ <TooltipTrigger render={<p className="max-w-48 cursor-default truncate text-small text-ink-muted" />}>{post.caption || 'No caption'}</TooltipTrigger>
+ <TooltipContent className="max-w-sm">{post.caption || 'No caption'}</TooltipContent>
+ </Tooltip>
+ </TableCell>
+ <TableCell>
+ <span className={cn('text-small', pastDue ? 'text-warning' : 'text-ink-muted')}>{formatScheduleDate(post.scheduledAt)}</span>
+ {pastDue && <p className="text-caption text-warning">Overdue</p>}
+ </TableCell>
+ <TableCell>
+ <span className="flex items-center gap-1 text-small text-ink-muted">
+ {formatScheduleDate(post.publishedAt)}
+ {post.publishedMediaId && (
+ <Tooltip>
+ <TooltipTrigger render={<span className="text-success" />}><CheckCircle2 className="size-3.5" /></TooltipTrigger>
+ <TooltipContent>Media ID {post.publishedMediaId}</TooltipContent>
+ </Tooltip>
+ )}
+ </span>
+ </TableCell>
+ <TableCell><StatusBadge status={post.status} map={POST_STATUS} /></TableCell>
+ <TableCell>
+ {post.error ? (
+ <Tooltip>
+ <TooltipTrigger render={<p className="max-w-40 cursor-help truncate text-small text-danger" />}>{post.error}</TooltipTrigger>
+ <TooltipContent className="max-w-sm">{post.error}</TooltipContent>
+ </Tooltip>
+ ) : <span className="text-ink-faint">-</span>}
+ </TableCell>
+ <PostActions post={post} isEditing={isEditing} editor={editor} onDelete={onDelete} />
+ </TableRow>
+ {isEditing && <ScheduledPostEditRow editor={editor} />}
+ </>
+ );
+}
diff --git a/frontend/src/features/publishing/ScheduledPostsSection.jsx b/frontend/src/features/publishing/ScheduledPostsSection.jsx
new file mode 100644
index 0000000..089352a
--- /dev/null
+++ b/frontend/src/features/publishing/ScheduledPostsSection.jsx
@@ -0,0 +1,73 @@
+import { Calendar, RefreshCw, Trash2 } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import SurfaceBox from '@/components/SurfaceBox';
+import FilterChips from '@/components/FilterChips';
+import { EmptyState } from '@/components/StateViews';
+import OverdueAlert from './OverdueAlert';
+import ScheduledPostRow from './ScheduledPostRow';
+import { filterScheduledPosts, overduePostsOf, scheduledStatusChips } from './scheduleHelpers.js';
+
+function ScheduledPostsHeader() {
+ return (
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-10 text-right">#</TableHead>
+ <TableHead>Account</TableHead>
+ <TableHead>Type</TableHead>
+ <TableHead className="min-w-48">Caption</TableHead>
+ <TableHead className="min-w-40">Scheduled for</TableHead>
+ <TableHead className="min-w-40">Published</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead className="min-w-40">Error</TableHead>
+ <TableHead className="text-right"><span className="sr-only">Actions</span></TableHead>
+ </TableRow>
+ </TableHeader>
+ );
+}
+
+export default function ScheduledPostsSection({ schedule, editor, removal, igAccounts }) {
+ const { scheduledPosts, statusFilter } = schedule;
+ const filteredScheduled = filterScheduledPosts(scheduledPosts, statusFilter);
+ const overdueCount = overduePostsOf(scheduledPosts).length;
+ return (
+ <section className="flex flex-col gap-3">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div>
+ <h2 className="font-heading text-section font-semibold text-ink">Scheduled posts</h2>
+ <p className="text-small text-ink-muted">Posts waiting to go out, and the history of ones that already did.</p>
+ </div>
+ <div className="flex gap-2">
+ <Button size="sm" variant="ghost" onClick={schedule.loadScheduledPosts}><RefreshCw data-icon="inline-start" />Refresh</Button>
+ <Button size="sm" variant="outline" onClick={() => removal.setConfirmDeleteAll(true)} className="hover:bg-danger-soft hover:text-danger"><Trash2 data-icon="inline-start" />Delete all</Button>
+ </div>
+ </div>
+ {overdueCount > 0 && <OverdueAlert count={overdueCount} />}
+ <FilterChips label="Status" options={scheduledStatusChips(scheduledPosts)} value={statusFilter} onChange={schedule.setStatusFilter} />
+ <SurfaceBox content={false} className="overflow-hidden">
+ <Table>
+ <ScheduledPostsHeader />
+ <TableBody>
+ {filteredScheduled.map((post, index) => (
+ <ScheduledPostRow
+ key={post.id}
+ post={post}
+ position={index + 1}
+ account={igAccounts.find(account => account.id === post.accountId)}
+ editor={editor}
+ onDelete={removal.setPendingDelete}
+ />
+ ))}
+ {filteredScheduled.length === 0 && (
+ <TableRow className="hover:bg-transparent">
+ <TableCell colSpan={9}>
+ <EmptyState compact icon={<Calendar />} title={`No ${statusFilter} posts`} description="Choose a different status to see other posts." />
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </SurfaceBox>
+ </section>
+ );
+}
diff --git a/frontend/src/features/publishing/SinglePostSettings.jsx b/frontend/src/features/publishing/SinglePostSettings.jsx
new file mode 100644
index 0000000..9a2c863
--- /dev/null
+++ b/frontend/src/features/publishing/SinglePostSettings.jsx
@@ -0,0 +1,53 @@
+import { AtSign, Calendar, Image as ImageIcon, MapPin, Send, UserPlus } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
+import DetailPanel, { FieldRow } from '@/components/DetailPanel';
+import AccountSelect from './AccountSelect';
+import IconInput from './IconInput';
+import PostSummary from './PostSummary';
+import ReelOptions from './ReelOptions';
+import ScheduleFields from './ScheduleFields';
+
+function PublishButtonIcon({ uploading, scheduleMode }) {
+ if (uploading) return <Spinner className="size-4" />;
+ if (scheduleMode) return <Calendar data-icon="inline-start" />;
+ return <Send data-icon="inline-start" />;
+}
+
+export default function SinglePostSettings({ form, publish, igAccounts, selectedAcct, selectedType }) {
+ const { fields, setField, contentType } = form;
+ const footer = (
+ <Button size="lg" className="w-full" onClick={publish.handlePublish} disabled={publish.uploading || !form.canPublish}>
+ <PublishButtonIcon uploading={publish.uploading} scheduleMode={fields.scheduleMode} />
+ {fields.scheduleMode ? 'Schedule post' : 'Publish now'}
+ </Button>
+ );
+ return (
+ <DetailPanel title="Post settings" footer={footer}>
+ <FieldRow label="Account">
+ <AccountSelect accounts={igAccounts} value={form.selectedAccount} onChange={form.setSelectedAccount} />
+ </FieldRow>
+
+ {contentType === 'IMAGE' && (
+ <FieldRow label="Alt text" hint="Describes the photo for people using screen readers." htmlFor="alt-text">
+ <IconInput id="alt-text" icon={ImageIcon} value={fields.altText} onChange={e => setField('altText', e.target.value)} placeholder="A short description of the photo" />
+ </FieldRow>
+ )}
+ <FieldRow label="Collaborators" hint="Separate usernames with commas." htmlFor="collaborators">
+ <IconInput id="collaborators" icon={UserPlus} value={fields.collaborators} onChange={e => setField('collaborators', e.target.value)} placeholder="username1, username2" />
+ </FieldRow>
+ <FieldRow label="Tagged people" hint="Separate with commas. Add x and y after a name to position the tag." htmlFor="user-tags">
+ <IconInput id="user-tags" icon={AtSign} value={fields.userTags} onChange={e => setField('userTags', e.target.value)} placeholder="@username1, @username2" />
+ </FieldRow>
+ <FieldRow label="Location" hint="The Facebook Page ID of the place." htmlFor="location-id">
+ <IconInput id="location-id" icon={MapPin} value={fields.locationId} onChange={e => setField('locationId', e.target.value)} placeholder="Location ID" />
+ </FieldRow>
+
+ {contentType === 'REELS' && <ReelOptions form={form} />}
+
+ <ScheduleFields fields={fields} setField={setField} />
+
+ <PostSummary selectedAcct={selectedAcct} selectedType={selectedType} file={form.file} fields={fields} />
+ </DetailPanel>
+ );
+}
diff --git a/frontend/src/features/publishing/SinglePostTab.jsx b/frontend/src/features/publishing/SinglePostTab.jsx
new file mode 100644
index 0000000..13b159c
--- /dev/null
+++ b/frontend/src/features/publishing/SinglePostTab.jsx
@@ -0,0 +1,38 @@
+import CaptionBox from './CaptionBox';
+import MediaPicker from './MediaPicker';
+import PublishProgress from './PublishProgress';
+import SinglePostSettings from './SinglePostSettings';
+import { contentTypeOf } from './publishConstants';
+
+export default function SinglePostTab({ form, publish, igAccounts, onReset }) {
+ const selectedAcct = igAccounts.find(account => account.id === form.selectedAccount);
+ const selectedType = contentTypeOf(form.contentType);
+
+ if (publish.activeStep === 2) {
+ return (
+ <PublishProgress
+ progress={publish}
+ selectedType={selectedType}
+ selectedAcct={selectedAcct}
+ scheduleMode={form.fields.scheduleMode}
+ onReset={onReset}
+ />
+ );
+ }
+
+ return (
+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,1fr)_28rem]">
+ <div className="flex min-w-0 flex-col gap-4">
+ <MediaPicker form={form} selectedType={selectedType} />
+ <CaptionBox caption={form.fields.caption} onChange={caption => form.setField('caption', caption)} />
+ </div>
+ <SinglePostSettings
+ form={form}
+ publish={publish}
+ igAccounts={igAccounts}
+ selectedAcct={selectedAcct}
+ selectedType={selectedType}
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/features/publishing/StatusBadge.jsx b/frontend/src/features/publishing/StatusBadge.jsx
new file mode 100644
index 0000000..ab0d2c9
--- /dev/null
+++ b/frontend/src/features/publishing/StatusBadge.jsx
@@ -0,0 +1,7 @@
+import { Badge } from '@/components/ui/badge';
+
+// an unknown status shows as the first entry of the map
+export default function StatusBadge({ status, map }) {
+ const entry = map[status] || Object.values(map)[0];
+ return <Badge variant={entry.variant}>{entry.label}</Badge>;
+}
diff --git a/frontend/src/features/publishing/TypePicker.jsx b/frontend/src/features/publishing/TypePicker.jsx
new file mode 100644
index 0000000..9f4b528
--- /dev/null
+++ b/frontend/src/features/publishing/TypePicker.jsx
@@ -0,0 +1,31 @@
+import { cn } from '@/lib/utils';
+import { CONTENT_TYPES } from './publishConstants';
+
+export default function TypePicker({ value, onChange, disabled }) {
+ return (
+ <div role="radiogroup" aria-label="Content type" className="grid grid-cols-3 gap-2">
+ {CONTENT_TYPES.map(type => {
+ const Icon = type.icon;
+ const active = value === type.value;
+ return (
+ <button
+ key={type.value}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ disabled={disabled}
+ onClick={() => onChange(type.value)}
+ className={cn(
+ 'flex flex-col items-center gap-1.5 rounded-field border px-2 py-3 text-center transition-colors duration-(--duration-fast)',
+ 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50',
+ active ? 'border-brand bg-brand-soft/50 text-brand-text' : 'border-line-control text-ink-muted hover:bg-surface-hover hover:text-ink',
+ )}
+ >
+ <Icon className="size-5 stroke-[1.75]" />
+ <span className="text-small font-semibold">{type.label}</span>
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/frontend/src/features/publishing/UploadContent.jsx b/frontend/src/features/publishing/UploadContent.jsx
index 7f1cdde..d18fb7b 100644
--- a/frontend/src/features/publishing/UploadContent.jsx
+++ b/frontend/src/features/publishing/UploadContent.jsx
@@ -1,553 +1,64 @@
-import React, { useState, useEffect, useRef } from 'react';
+import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
-import {
- Upload, Image as ImageIcon, Film, BookOpen, Trash2, CheckCircle2, AlertCircle, Calendar, Send, X, Plus,
- Copy, Square, UserPlus, MapPin, AtSign, Music, Clock, FolderUp, ExternalLink, Pencil, RefreshCw, Info, Camera,
-} from 'lucide-react';
-import { Button } from '@/components/ui/button';
-import { Input } from '@/components/ui/input';
-import { Badge } from '@/components/ui/badge';
-import { Textarea } from '@/components/ui/textarea';
-import { Progress } from '@/components/ui/progress';
+import { AlertCircle, FolderUp, Plus, Upload } from 'lucide-react';
import { Alert, AlertDescription } from '@/components/ui/alert';
-import { Switch } from '@/components/ui/switch';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
-import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
-import { Spinner } from '@/components/ui/spinner';
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import PageHeader from '@/components/PageHeader';
-import SurfaceBox from '@/components/SurfaceBox';
-import DetailPanel, { FieldRow } from '@/components/DetailPanel';
-import FilterChips from '@/components/FilterChips';
-import ConfirmDialog from '@/components/ConfirmDialog';
-import { EmptyState } from '@/components/StateViews';
-import { AccountAvatar } from '@/components/platform';
-import { InstagramIcon } from '@/components/brand/platform-icons';
-import { ADMIN_EMAIL, adminMailto } from '@/lib/contact';
import { useAppContext } from '../../context/AppContext';
-import { api } from '../../services/api';
-import { cn } from '@/lib/utils';
-
-const BULK_INTERVAL_OPTIONS = [
- { value: 720, label: 'Every 12 hours' },
- { value: 1440, label: 'Once a day' },
- { value: 2880, label: 'Every 2 days' },
- { value: 4320, label: 'Every 3 days' },
- { value: 10080, label: 'Once a week' },
-];
-
-const CONTENT_TYPES = [
- { value: 'IMAGE', label: 'Photo', icon: ImageIcon, accept: 'image/jpeg', desc: 'JPEG, 4:5 to 1.91:1, up to 8MB' },
- { value: 'REELS', label: 'Reel', icon: Film, accept: 'video/mp4,video/quicktime', desc: 'MP4 or MOV, 9:16, 3 seconds to 15 minutes, up to 300MB' },
- { value: 'STORIES', label: 'Story', icon: BookOpen, accept: 'image/jpeg,video/mp4,video/quicktime', desc: 'Image or video, 9:16, up to 60 seconds' },
-];
-
-const POST_STATUS = {
- published: { label: 'Published', variant: 'success' },
- failed: { label: 'Failed', variant: 'destructive' },
- publishing: { label: 'Publishing', variant: 'info' },
- pending: { label: 'Pending', variant: 'warning' },
-};
-
-const BULK_STATUS = {
- pending: { label: 'Pending', variant: 'secondary' },
- uploading: { label: 'Uploading', variant: 'info' },
- creating: { label: 'Creating', variant: 'info' },
- processing: { label: 'Processing', variant: 'info' },
- publishing: { label: 'Publishing', variant: 'info' },
- scheduling: { label: 'Scheduling', variant: 'info' },
- done: { label: 'Published', variant: 'success' },
- scheduled: { label: 'Scheduled', variant: 'warning' },
- error: { label: 'Failed', variant: 'destructive' },
-};
-
-const ACTIVE_BULK = ['uploading', 'creating', 'processing', 'publishing', 'scheduling'];
-const CAPTION_LIMIT = 2200;
-const OVERDUE_MS = 30 * 60 * 1000;
-
-function ScheduleHint() {
- return (
- <p className="text-caption text-ink-faint">
- The server publishes the post within 15 minutes after this time, even with this page closed. Keep the account connected until then.{' '}
- <Link to="/settings#scheduling" className="font-medium text-brand-text underline-offset-4 hover:underline">How scheduling works</Link>
- </p>
- );
-}
-
-function StatusBadge({ status, map }) {
- const s = map[status] || Object.values(map)[0];
- return <Badge variant={s.variant}>{s.label}</Badge>;
-}
-
-function IconInput({ icon, ...props }) {
- const Icon = icon;
- return (
- <div className="relative">
- <Icon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 stroke-[1.75] text-ink-faint" />
- <Input className="pl-9" {...props} />
- </div>
- );
-}
-
-function AccountSelect({ accounts, value, onChange, disabled }) {
- const selected = accounts.find(a => a.id === value);
- return (
- <Select value={value} onValueChange={onChange} disabled={disabled}>
- <SelectTrigger className="h-(--control-h-lg) w-full" aria-label="Instagram account">
- {selected ? (
- <span className="flex min-w-0 items-center gap-2">
- <AccountAvatar account={selected} size="xs" />
- <span className="truncate text-sm">{selected.title || selected.username}</span>
- {selected.username && <span className="shrink-0 text-caption text-ink-faint">@{selected.username}</span>}
- </span>
- ) : (
- <SelectValue placeholder="Choose an account" />
- )}
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {accounts.map(a => (
- <SelectItem key={a.id} value={a.id}>
- <span className="flex items-center gap-2">
- <AccountAvatar account={a} size="xs" />
- <span className="truncate text-sm font-medium">{a.title || a.username}</span>
- {a.username && <span className="shrink-0 text-caption text-ink-faint">@{a.username}</span>}
- </span>
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- );
-}
-
-function TypePicker({ value, onChange, disabled }) {
- return (
- <div role="radiogroup" aria-label="Content type" className="grid grid-cols-3 gap-2">
- {CONTENT_TYPES.map(t => {
- const Icon = t.icon;
- const active = value === t.value;
- return (
- <button
- key={t.value}
- type="button"
- role="radio"
- aria-checked={active}
- disabled={disabled}
- onClick={() => onChange(t.value)}
- className={cn(
- 'flex flex-col items-center gap-1.5 rounded-field border px-2 py-3 text-center transition-colors duration-(--duration-fast)',
- 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50',
- active ? 'border-brand bg-brand-soft/50 text-brand-text' : 'border-line-control text-ink-muted hover:bg-surface-hover hover:text-ink',
- )}
- >
- <Icon className="size-5 stroke-[1.75]" />
- <span className="text-small font-semibold">{t.label}</span>
- </button>
- );
- })}
- </div>
- );
-}
-
-function ScheduleToggle({ scheduled, onChange, disabled, nowLabel = 'Publish now', laterLabel = 'Schedule' }) {
- return (
- <Tabs value={scheduled ? 'later' : 'now'} onValueChange={v => onChange(v === 'later')}>
- <TabsList variant="segmented" className="w-full">
- <TabsTrigger value="now" disabled={disabled}><Send />{nowLabel}</TabsTrigger>
- <TabsTrigger value="later" disabled={disabled}><Calendar />{laterLabel}</TabsTrigger>
- </TabsList>
- </Tabs>
- );
-}
-
-function SummaryRow({ label, children }) {
- return (
- <div className="flex items-center justify-between gap-3 text-small">
- <span className="text-ink-faint">{label}</span>
- <span className="min-w-0 truncate font-medium text-ink">{children}</span>
- </div>
- );
-}
+import { useCloudinaryConfig } from '../../hooks/use-cloudinary-config';
+import BulkUploadTab from './BulkUploadTab';
+import NoInstagramAccount from './NoInstagramAccount';
+import ScheduledPostDialogs from './ScheduledPostDialogs';
+import ScheduledPostsSection from './ScheduledPostsSection';
+import SinglePostTab from './SinglePostTab';
+import { useBulkPublish } from './useBulkPublish';
+import { useBulkQueue } from './useBulkQueue';
+import { useBulkSettings } from './useBulkSettings';
+import { useScheduledPostDelete } from './useScheduledPostDelete';
+import { useScheduledPostEdit } from './useScheduledPostEdit';
+import { useScheduledPosts } from './useScheduledPosts';
+import { useSinglePostForm } from './useSinglePostForm';
+import { useSinglePublish } from './useSinglePublish';
export default function UploadContent() {
const { accounts, showToast } = useAppContext();
+ const cloudConfig = useCloudinaryConfig(accounts);
const [igAccounts, setIgAccounts] = useState([]);
- const [selectedAccount, setSelectedAccount] = useState('');
- const [contentType, setContentType] = useState('');
- const [file, setFile] = useState(null);
- const [filePreview, setFilePreview] = useState(null);
- const [cloudConfig, setCloudConfig] = useState(null);
-
- const [caption, setCaption] = useState('');
- const [shareToFeed, setShareToFeed] = useState(true);
- const [coverFile, setCoverFile] = useState(null);
- const [coverPreview, setCoverPreview] = useState(null);
- const [audioName, setAudioName] = useState('');
- const [thumbOffset, setThumbOffset] = useState('');
- const [locationId, setLocationId] = useState('');
- const [collaborators, setCollaborators] = useState('');
- const [userTags, setUserTags] = useState('');
- const [altText, setAltText] = useState('');
-
- const [scheduleMode, setScheduleMode] = useState(false);
- const [scheduleDate, setScheduleDate] = useState('');
- const [scheduleTime, setScheduleTime] = useState('');
- const [scheduledPosts, setScheduledPosts] = useState([]);
- const [statusFilter, setStatusFilter] = useState('all');
-
- const [editingPostId, setEditingPostId] = useState(null);
- const [editCaption, setEditCaption] = useState('');
- const [editDate, setEditDate] = useState('');
- const [editTime, setEditTime] = useState('');
- const [savingEdit, setSavingEdit] = useState(false);
-
- const [pendingDelete, setPendingDelete] = useState(null);
- const [confirmDeleteAll, setConfirmDeleteAll] = useState(false);
- const [deleting, setDeleting] = useState(false);
-
- const [activeStep, setActiveStep] = useState(0);
- const [uploading, setUploading] = useState(false);
- const [uploadProgress, setUploadProgress] = useState(0);
- const [publishStatus, setPublishStatus] = useState('');
- const [statusMessage, setStatusMessage] = useState('');
- const [publishedMediaId, setPublishedMediaId] = useState(null);
-
- const fileInputRef = useRef(null);
- const coverInputRef = useRef(null);
- const bulkFileInputRef = useRef(null);
- const bulkIdCounter = useRef(0);
- const bulkCancelRef = useRef(false);
-
const [uploadMode, setUploadMode] = useState('single');
- const [bulkFiles, setBulkFiles] = useState([]);
- const [bulkAccount, setBulkAccount] = useState('');
- const [bulkContentType, setBulkContentType] = useState('REELS');
- const [bulkSharedCaption, setBulkSharedCaption] = useState('');
- const [bulkCollaborators, setBulkCollaborators] = useState('');
- const [bulkUserTags, setBulkUserTags] = useState('');
- const [bulkLocationId, setBulkLocationId] = useState('');
- const [bulkShareToFeed, setBulkShareToFeed] = useState(true);
- const [bulkScheduleMode, setBulkScheduleMode] = useState(false);
- const [bulkStartDate, setBulkStartDate] = useState('');
- const [bulkStartTime, setBulkStartTime] = useState('');
- const [bulkInterval, setBulkInterval] = useState(1440);
- const [bulkProcessing, setBulkProcessing] = useState(false);
+ const schedule = useScheduledPosts();
+ const { loadScheduledPosts } = schedule;
+ const editor = useScheduledPostEdit({ showToast, loadScheduledPosts });
+ const removal = useScheduledPostDelete({ showToast, loadScheduledPosts });
+ const form = useSinglePostForm();
+ const { setSelectedAccount } = form;
+ const publish = useSinglePublish({ form, cloudConfig, showToast, onScheduled: loadScheduledPosts });
+ const bulk = useBulkSettings();
+ const queue = useBulkQueue({ sharedCaption: bulk.settings.sharedCaption, onFirstFiles: bulk.applyFirstBatchDefaults });
+ const bulkPublish = useBulkPublish({ queue, settings: bulk.settings, cloudConfig, showToast, onScheduled: loadScheduledPosts });
useEffect(() => {
- const ig = (accounts || []).filter(a => a.platform === 'instagram');
- setIgAccounts(ig);
- if (ig.length === 1) setSelectedAccount(ig[0].id);
- loadCloudinaryConfig();
+ const instagramAccounts = (accounts || []).filter(account => account.platform === 'instagram');
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- keeps the original first render
+ setIgAccounts(instagramAccounts);
+ if (instagramAccounts.length === 1) setSelectedAccount(instagramAccounts[0].id);
loadScheduledPosts();
- }, [accounts]);
-
- const loadScheduledPosts = async () => {
- try {
- const res = await api.getScheduledPosts();
- if (res.success) setScheduledPosts(res.posts || []);
- } catch {
- // the schedule list is optional, publishing still works
- return;
- }
- };
-
- const loadCloudinaryConfig = async () => {
- try {
- const res = await api.getCloudinaryConfig();
- if (res.success) setCloudConfig(res);
- } catch {
- // a missing config already shows as an alert on the page
- return;
- }
- };
-
- const handleFileSelect = e => {
- const f = e.target.files?.[0];
- if (!f) return;
- setFile(f);
- setFilePreview(URL.createObjectURL(f));
- };
-
- const handleCoverSelect = e => {
- const f = e.target.files?.[0];
- if (!f) return;
- setCoverFile(f);
- setCoverPreview(URL.createObjectURL(f));
- };
-
- const clearFile = () => { setFile(null); setFilePreview(null); if (fileInputRef.current) fileInputRef.current.value = ''; };
- const clearCover = () => { setCoverFile(null); setCoverPreview(null); if (coverInputRef.current) coverInputRef.current.value = ''; };
+ }, [accounts, setSelectedAccount, loadScheduledPosts]);
const resetAll = () => {
- clearFile(); clearCover();
- setCaption(''); setShareToFeed(true); setAudioName(''); setThumbOffset('');
- setLocationId(''); setCollaborators(''); setUserTags(''); setAltText('');
- setContentType(''); setActiveStep(0); setPublishStatus(''); setStatusMessage('');
- setPublishedMediaId(null); setUploadProgress(0); setScheduleMode(false);
- setScheduleDate(''); setScheduleTime('');
- };
-
- const uploadToCloudinary = async fileToUpload => {
- if (!cloudConfig) throw new Error('Cloudinary is not set up on the server. Check Settings.');
- const formData = new FormData();
- formData.append('file', fileToUpload);
- formData.append('upload_preset', cloudConfig.uploadPreset);
- const resourceType = fileToUpload.type.startsWith('video/') ? 'video' : 'image';
- const xhr = new XMLHttpRequest();
- return new Promise((resolve, reject) => {
- xhr.upload.addEventListener('progress', e => { if (e.lengthComputable) setUploadProgress(Math.round((e.loaded / e.total) * 100)); });
- xhr.addEventListener('load', () => {
- if (xhr.status >= 200 && xhr.status < 300) { resolve(JSON.parse(xhr.responseText).secure_url); }
- else { try { reject(new Error(JSON.parse(xhr.responseText).error?.message || 'Upload failed')); } catch { reject(new Error('Upload failed')); } }
- });
- xhr.addEventListener('error', () => reject(new Error('The upload lost its network connection. Check your connection and try again.')));
- xhr.open('POST', `https://api.cloudinary.com/v1_1/${cloudConfig.cloudName}/${resourceType}/upload`);
- xhr.send(formData);
- });
- };
-
- const waitForContainer = async (containerId, accountId, maxAttempts = 30) => {
- for (let i = 0; i < maxAttempts; i++) {
- await new Promise(r => setTimeout(r, 3000));
- try {
- const status = await api.getIGContainerStatus(containerId, accountId);
- setStatusMessage(`Instagram status: ${status.statusCode || 'IN_PROGRESS'}`);
- if (status.statusCode === 'FINISHED' || status.statusCode === 'PUBLISHED') return true;
- if (status.statusCode === 'ERROR') throw new Error('Container processing failed: ' + (status.status || 'Unknown'));
- if (status.statusCode === 'EXPIRED') throw new Error('Container expired');
- } catch (err) { if (err.message.includes('processing failed') || err.message.includes('expired')) throw err; }
- }
- throw new Error('Instagram took too long to process the media. Try again in a few minutes.');
- };
-
- const parseUserTags = str => str.split(',').map(s => {
- const parts = s.trim().replace(/^@/, '').split(/\s+/);
- return { username: parts[0], x: parts[1] ? parseFloat(parts[1]) : 0.5, y: parts[2] ? parseFloat(parts[2]) : 0.5 };
- }).filter(t => t.username);
-
- const handlePublish = async () => {
- if (!selectedAccount || !file || !contentType) { showToast('Choose an account, a content type and a file before publishing.', 'error'); return; }
- if (!cloudConfig) { showToast('Cloudinary is not set up on the server. Check Settings.', 'error'); return; }
- if (scheduleMode) {
- if (!scheduleDate || !scheduleTime) { showToast('Set a date and time for the scheduled post.', 'error'); return; }
- const scheduledAt = new Date(`${scheduleDate}T${scheduleTime}`);
- if (scheduledAt <= new Date()) { showToast('Pick a time in the future.', 'error'); return; }
- setUploading(true); setPublishStatus('uploading-cloudinary'); setActiveStep(2);
- try {
- const mediaUrl = await uploadToCloudinary(file);
- let coverUrl = null;
- if (coverFile && contentType === 'REELS') { setStatusMessage('Uploading cover'); coverUrl = await uploadToCloudinary(coverFile); }
- setPublishStatus('scheduling'); setStatusMessage('Saving the scheduled post');
- const res = await api.createScheduledPost({
- accountId: selectedAccount, platform: 'instagram', mediaType: contentType, mediaUrl, caption: caption || '',
- coverUrl: coverUrl || null, shareToFeed: contentType === 'REELS' ? shareToFeed : true,
- collaborators: collaborators ? collaborators.split(',').map(s => s.trim()).filter(Boolean) : [],
- audioName: audioName || '', thumbOffset: thumbOffset ? parseInt(thumbOffset, 10) : null,
- locationId: locationId || '', userTags: userTags ? parseUserTags(userTags) : [],
- altText: (contentType === 'IMAGE' && altText) ? altText : '', scheduledAt: scheduledAt.toISOString(),
- });
- if (!res.success) throw new Error(res.message || 'Failed to schedule');
- setPublishStatus('scheduled'); setStatusMessage(`Scheduled for ${scheduledAt.toLocaleString()}`);
- showToast('Post scheduled'); loadScheduledPosts();
- } catch (err) { setPublishStatus('error'); setStatusMessage(err.message); showToast(`Scheduling failed. ${err.message}`, 'error'); }
- finally { setUploading(false); }
- return;
- }
-
- setUploading(true); setPublishStatus('uploading-cloudinary'); setStatusMessage('Uploading media'); setActiveStep(2);
- try {
- const mediaUrl = await uploadToCloudinary(file);
- let coverUrl = null;
- if (coverFile && contentType === 'REELS') { setStatusMessage('Uploading cover'); coverUrl = await uploadToCloudinary(coverFile); }
- setPublishStatus('creating-container'); setStatusMessage('Creating the Instagram media container');
- const containerRes = await api.createIGContainer(selectedAccount, {
- mediaType: contentType, mediaUrl, caption: caption || undefined, coverUrl: coverUrl || undefined,
- shareToFeed: contentType === 'REELS' ? shareToFeed : undefined,
- collaborators: collaborators ? collaborators.split(',').map(s => s.trim()).filter(Boolean) : undefined,
- audioName: audioName || undefined, thumbOffset: thumbOffset ? parseInt(thumbOffset, 10) : undefined,
- locationId: locationId || undefined, userTags: userTags ? parseUserTags(userTags) : undefined,
- altText: (contentType === 'IMAGE' && altText) ? altText : undefined,
- });
- if (!containerRes.success || !containerRes.containerId) throw new Error(containerRes.message || 'Failed to create container');
- if (contentType === 'REELS' || contentType === 'STORIES') { setPublishStatus('processing'); setStatusMessage('Instagram is processing the media'); await waitForContainer(containerRes.containerId, selectedAccount); }
- else { await new Promise(r => setTimeout(r, 2000)); }
- setPublishStatus('publishing'); setStatusMessage('Publishing to Instagram');
- const publishRes = await api.publishIGContainer(selectedAccount, containerRes.containerId);
- if (!publishRes.success || !publishRes.mediaId) throw new Error(publishRes.message || 'Publish failed');
- setPublishStatus('done'); setPublishedMediaId(publishRes.mediaId); setStatusMessage('Published');
- showToast('Published to Instagram');
- } catch (err) { setPublishStatus('error'); setStatusMessage(err.message); showToast(`Publishing failed. ${err.message}`, 'error'); }
- finally { setUploading(false); }
+ form.resetForm();
+ publish.resetProgress();
};
- const handleBulkFilesSelect = e => {
- const files = Array.from(e.target.files || []);
- if (!files.length) return;
- const newItems = files.map(f => ({ id: ++bulkIdCounter.current, file: f, preview: URL.createObjectURL(f), caption: '', status: 'pending', progress: 0, error: null, mediaId: null }));
- setBulkFiles(prev => {
- const updated = [...prev, ...newItems];
- if (prev.length === 0) { setBulkScheduleMode(true); setBulkInterval(1440); setBulkStartTime('08:00'); const t = new Date(); t.setDate(t.getDate() + 1); setBulkStartDate(t.toISOString().split('T')[0]); }
- return updated;
- });
- if (bulkFileInputRef.current) bulkFileInputRef.current.value = '';
- };
-
- const removeBulkFile = id => {
- setBulkFiles(prev => { const item = prev.find(f => f.id === id); if (item?.preview) URL.revokeObjectURL(item.preview); return prev.filter(f => f.id !== id); });
- };
-
- const updateBulkFileCaption = (id, cap) => setBulkFiles(prev => prev.map(f => f.id === id ? { ...f, caption: cap } : f));
-
- const applySharedCaption = () => { if (!bulkSharedCaption) return; setBulkFiles(prev => prev.map(f => f.status === 'pending' ? { ...f, caption: bulkSharedCaption } : f)); };
-
- const clearBulkFiles = () => { bulkFiles.forEach(f => { if (f.preview) URL.revokeObjectURL(f.preview); }); setBulkFiles([]); setBulkProcessing(false); bulkCancelRef.current = false; };
-
- const handleBulkProcess = async () => {
- if (!bulkAccount || bulkFiles.length === 0 || !bulkContentType) { showToast('Choose an account, a content type and at least one file.', 'error'); return; }
- if (!cloudConfig) { showToast('Cloudinary is not set up on the server. Check Settings.', 'error'); return; }
- if (bulkScheduleMode && (!bulkStartDate || !bulkStartTime)) { showToast('Set a start date and time for the schedule.', 'error'); return; }
- const baseTime = bulkScheduleMode ? new Date(`${bulkStartDate}T${bulkStartTime}`) : null;
- if (baseTime && baseTime <= new Date()) { showToast('Pick a start time in the future.', 'error'); return; }
- setBulkProcessing(true); bulkCancelRef.current = false;
- const pendingFiles = bulkFiles.filter(f => f.status === 'pending');
- let scheduleOffset = 0, successCount = 0, failCount = 0;
- for (let i = 0; i < pendingFiles.length; i++) {
- if (bulkCancelRef.current) break;
- const item = pendingFiles[i];
- try {
- setBulkFiles(prev => prev.map(f => f.id === item.id ? { ...f, status: 'uploading', progress: 0 } : f));
- const xhr = new XMLHttpRequest();
- const formData = new FormData(); formData.append('file', item.file); formData.append('upload_preset', cloudConfig.uploadPreset);
- const rtype = item.file.type.startsWith('video/') ? 'video' : 'image';
- const mediaUrl = await new Promise((resolve, reject) => {
- xhr.upload.addEventListener('progress', e => { if (e.lengthComputable) setBulkFiles(prev => prev.map(f => f.id === item.id ? { ...f, progress: Math.round(e.loaded / e.total * 100) } : f)); });
- xhr.addEventListener('load', () => { if (xhr.status >= 200 && xhr.status < 300) resolve(JSON.parse(xhr.responseText).secure_url); else reject(new Error('Upload failed')); });
- xhr.addEventListener('error', () => reject(new Error('The upload lost its network connection')));
- xhr.open('POST', `https://api.cloudinary.com/v1_1/${cloudConfig.cloudName}/${rtype}/upload`); xhr.send(formData);
- });
- if (bulkCancelRef.current) break;
- if (bulkScheduleMode) {
- setBulkFiles(prev => prev.map(f => f.id === item.id ? { ...f, status: 'scheduling', progress: 100 } : f));
- const scheduledAt = new Date(baseTime.getTime() + scheduleOffset * bulkInterval * 60000);
- const res = await api.createScheduledPost({ accountId: bulkAccount, platform: 'instagram', mediaType: bulkContentType, mediaUrl, caption: item.caption || '', coverUrl: null, shareToFeed: bulkContentType === 'REELS' ? bulkShareToFeed : true, collaborators: bulkCollaborators ? bulkCollaborators.split(',').map(s => s.trim()).filter(Boolean) : [], audioName: '', thumbOffset: null, locationId: bulkLocationId || '', userTags: bulkUserTags ? parseUserTags(bulkUserTags) : [], altText: '', scheduledAt: scheduledAt.toISOString() });
- if (!res.success) throw new Error(res.message || 'Failed to schedule');
- setBulkFiles(prev => prev.map(f => f.id === item.id ? { ...f, status: 'scheduled', progress: 100 } : f));
- scheduleOffset++; successCount++;
- } else {
- setBulkFiles(prev => prev.map(f => f.id === item.id ? { ...f, status: 'creating', progress: 100 } : f));
- const containerRes = await api.createIGContainer(bulkAccount, { mediaType: bulkContentType, mediaUrl, caption: item.caption || undefined, shareToFeed: bulkContentType === 'REELS' ? bulkShareToFeed : undefined, collaborators: bulkCollaborators ? bulkCollaborators.split(',').map(s => s.trim()).filter(Boolean) : undefined, locationId: bulkLocationId || undefined, userTags: bulkUserTags ? parseUserTags(bulkUserTags) : undefined });
- if (!containerRes.success || !containerRes.containerId) throw new Error(containerRes.message || 'Container creation failed');
- if (bulkCancelRef.current) break;
- if (bulkContentType === 'REELS' || bulkContentType === 'STORIES') {
- setBulkFiles(prev => prev.map(f => f.id === item.id ? { ...f, status: 'processing' } : f));
- for (let j = 0; j < 30; j++) { await new Promise(r => setTimeout(r, 3000)); const s = await api.getIGContainerStatus(containerRes.containerId, bulkAccount); if (s.statusCode === 'FINISHED' || s.statusCode === 'PUBLISHED') break; if (s.statusCode === 'ERROR') throw new Error('Processing failed'); if (s.statusCode === 'EXPIRED') throw new Error('Container expired'); }
- } else { await new Promise(r => setTimeout(r, 2000)); }
- if (bulkCancelRef.current) break;
- setBulkFiles(prev => prev.map(f => f.id === item.id ? { ...f, status: 'publishing' } : f));
- const publishRes = await api.publishIGContainer(bulkAccount, containerRes.containerId);
- if (!publishRes.success || !publishRes.mediaId) throw new Error(publishRes.message || 'Publish failed');
- setBulkFiles(prev => prev.map(f => f.id === item.id ? { ...f, status: 'done', mediaId: publishRes.mediaId } : f));
- successCount++;
- }
- } catch (err) { setBulkFiles(prev => prev.map(f => f.id === item.id ? { ...f, status: 'error', error: err.message } : f)); failCount++; }
- if (i < pendingFiles.length - 1 && !bulkCancelRef.current) await new Promise(r => setTimeout(r, 2000));
- }
- setBulkProcessing(false);
- if (bulkCancelRef.current) { showToast('Bulk upload stopped. Files already processed keep their status.', 'warning'); }
- else { showToast(`Bulk upload finished: ${successCount} succeeded, ${failCount} failed`, successCount > 0 ? 'success' : 'error'); if (bulkScheduleMode) loadScheduledPosts(); }
- };
-
- const handleDeleteScheduled = async () => {
- if (!pendingDelete) return;
- setDeleting(true);
- try { await api.deleteScheduledPost(pendingDelete.id); showToast(pendingDelete.status === 'published' ? 'Record removed' : 'Scheduled post deleted'); loadScheduledPosts(); }
- catch (err) { showToast(`Couldn't delete the post. ${err.message}`, 'error'); }
- finally { setDeleting(false); setPendingDelete(null); }
- };
-
- const handleDeleteAll = async () => {
- setDeleting(true);
- try { const res = await api.deleteAllScheduledPosts(); showToast(`Deleted ${res.deleted} post${res.deleted === 1 ? '' : 's'}`); loadScheduledPosts(); }
- catch (err) { showToast(`Couldn't delete the posts. ${err.message}`, 'error'); }
- finally { setDeleting(false); setConfirmDeleteAll(false); }
- };
-
- const startEditPost = post => {
- setEditingPostId(post.id); setEditCaption(post.caption || '');
- const dt = new Date(post.scheduledAt);
- setEditDate(`${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}`);
- setEditTime(`${String(dt.getHours()).padStart(2, '0')}:${String(dt.getMinutes()).padStart(2, '0')}`);
- };
- const cancelEdit = () => { setEditingPostId(null); setEditCaption(''); setEditDate(''); setEditTime(''); };
-
- const handleSaveEdit = async () => {
- if (!editingPostId || !editDate || !editTime) { showToast('Set a date and time.', 'error'); return; }
- const scheduledAt = new Date(`${editDate}T${editTime}`);
- if (scheduledAt <= new Date()) { showToast('Pick a time in the future.', 'error'); return; }
- setSavingEdit(true);
- try {
- const res = await api.updateScheduledPost(editingPostId, { caption: editCaption, scheduledAt: scheduledAt.toISOString() });
- if (!res.success) throw new Error(res.message || 'Update failed');
- showToast('Scheduled post updated'); cancelEdit(); loadScheduledPosts();
- } catch (err) { showToast(`Couldn't update the post. ${err.message}`, 'error'); }
- finally { setSavingEdit(false); }
- };
-
- const canPublish = !!file && !!contentType && !!selectedAccount && !(scheduleMode && (!scheduleDate || !scheduleTime));
- const selectedAcct = igAccounts.find(a => a.id === selectedAccount);
- const selectedType = CONTENT_TYPES.find(t => t.value === contentType);
- const bulkType = CONTENT_TYPES.find(t => t.value === bulkContentType);
-
- const bulkStats = {
- total: bulkFiles.length,
- pending: bulkFiles.filter(f => f.status === 'pending').length,
- done: bulkFiles.filter(f => f.status === 'done').length,
- scheduled: bulkFiles.filter(f => f.status === 'scheduled').length,
- errors: bulkFiles.filter(f => f.status === 'error').length,
- };
-
- const fmtLocalDate = iso => iso ? new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : '-';
- const today = new Date().toISOString().split('T')[0];
-
- const statusChips = [
- { value: 'all', label: 'All', count: scheduledPosts.length },
- { value: 'pending', label: 'Pending', count: scheduledPosts.filter(p => p.status === 'pending').length },
- { value: 'publishing', label: 'Publishing', count: scheduledPosts.filter(p => p.status === 'publishing').length },
- { value: 'published', label: 'Published', count: scheduledPosts.filter(p => p.status === 'published').length },
- { value: 'failed', label: 'Failed', count: scheduledPosts.filter(p => p.status === 'failed').length },
- ];
- const filteredScheduled = scheduledPosts
- .filter(p => statusFilter === 'all' || p.status === statusFilter)
- .sort((a, b) => new Date(b.scheduledAt) - new Date(a.scheduledAt));
-
- const overduePosts = scheduledPosts.filter(p => p.status === 'pending' && Date.now() - new Date(p.scheduledAt).getTime() > OVERDUE_MS);
-
- const intervalText = bulkInterval >= 1440 ? `${bulkInterval / 1440} day${bulkInterval > 1440 ? 's' : ''}` : `${bulkInterval / 60} hours`;
-
- if (igAccounts.length === 0) {
- return (
- <div className="flex flex-col gap-6">
- <PageHeader title="Publish" description="Post and schedule photos, Reels and Stories to Instagram." />
- <SurfaceBox>
- <EmptyState
- icon={<InstagramIcon />}
- title="Connect an Instagram account to publish"
- description="Publishing works with Instagram Business and Creator accounts. YouTube publishing is not available yet."
- action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add an account</Button>}
- />
- </SurfaceBox>
- </div>
- );
- }
+ if (igAccounts.length === 0) return <NoInstagramAccount />;
return (
<div className="flex flex-col gap-6">
<PageHeader
title="Publish"
description="Post and schedule photos, Reels and Stories to Instagram."
- actions={publishStatus === 'done' && uploadMode === 'single' && (
+ actions={publish.publishStatus === 'done' && uploadMode === 'single' && (
<Button onClick={resetAll}><Plus data-icon="inline-start" />Publish another</Button>
)}
/>
@@ -566,564 +77,28 @@ export default function UploadContent() {
<TabsTrigger value="single"><Upload />Single post</TabsTrigger>
<TabsTrigger value="bulk">
<FolderUp />Bulk upload
- {bulkFiles.length > 0 && <Badge variant="solid" className="h-4 px-1.5">{bulkFiles.length}</Badge>}
+ {queue.files.length > 0 && <Badge variant="solid" className="h-4 px-1.5">{queue.files.length}</Badge>}
</TabsTrigger>
</TabsList>
<TabsContent value="single">
- {activeStep === 2 ? (
- <SurfaceBox>
- <div role="status" className="flex flex-col items-center gap-3 py-10 text-center">
- {publishStatus === 'uploading-cloudinary' && (
- <>
- <Upload className="size-10 stroke-[1.5] text-ink-muted" />
- <h2 className="font-heading text-section font-semibold text-ink">Uploading media</h2>
- <Progress value={uploadProgress} className="w-72 max-w-full" aria-label="Upload progress" />
- <p className="text-small text-ink-muted tabular-nums">{uploadProgress}% uploaded</p>
- </>
- )}
- {['creating-container', 'publishing', 'scheduling', 'processing'].includes(publishStatus) && (
- <>
- <Spinner className="size-10 text-brand" />
- <h2 className="font-heading text-section font-semibold text-ink">
- {publishStatus === 'creating-container' ? 'Preparing the post' : publishStatus === 'scheduling' ? 'Saving the schedule' : publishStatus === 'processing' ? 'Instagram is processing the media' : 'Publishing'}
- </h2>
- <p className="text-small text-ink-muted">{statusMessage}</p>
- {publishStatus === 'processing' && <p className="text-caption text-ink-faint">Videos can take a minute.</p>}
- </>
- )}
- {publishStatus === 'done' && (
- <>
- <span className="flex size-12 items-center justify-center rounded-full bg-success-soft text-success"><CheckCircle2 className="size-6" /></span>
- <h2 className="font-heading text-page-title font-semibold text-ink">Published</h2>
- <p className="text-sm text-ink-muted">Your {selectedType?.label?.toLowerCase()} is live on Instagram.</p>
- {publishedMediaId && <Badge variant="outline" className="font-mono">Media ID {publishedMediaId}</Badge>}
- <div className="mt-2 flex gap-2">
- <Button onClick={resetAll}><Plus data-icon="inline-start" />Publish another</Button>
- {selectedAcct?.username && (
- <Button variant="outline" render={<a href={`https://instagram.com/${selectedAcct.username}`} target="_blank" rel="noopener noreferrer" />}>
- <ExternalLink data-icon="inline-start" />View profile
- </Button>
- )}
- </div>
- </>
- )}
- {publishStatus === 'scheduled' && (
- <>
- <span className="flex size-12 items-center justify-center rounded-full bg-warning-soft text-warning"><Calendar className="size-6" /></span>
- <h2 className="font-heading text-page-title font-semibold text-ink">Post scheduled</h2>
- <p className="text-sm text-ink-muted">{statusMessage}</p>
- <p className="max-w-md text-small text-ink-faint">The server publishes it within 15 minutes after that time, even when this browser is closed. Track it under Scheduled posts below.</p>
- <Button onClick={resetAll} className="mt-2"><Plus data-icon="inline-start" />Schedule another</Button>
- </>
- )}
- {publishStatus === 'error' && (
- <>
- <span className="flex size-12 items-center justify-center rounded-full bg-danger-soft text-danger"><AlertCircle className="size-6" /></span>
- <h2 className="font-heading text-page-title font-semibold text-ink"><span className="sr-only">Error: </span>{scheduleMode ? 'Scheduling failed' : 'Publishing failed'}</h2>
- <p className="max-w-md text-sm text-ink-muted">{statusMessage}</p>
- <div className="mt-2 flex gap-2">
- <Button onClick={() => { setActiveStep(0); setPublishStatus(''); }}>Try again</Button>
- <Button variant="outline" onClick={resetAll}>Start over</Button>
- </div>
- </>
- )}
- </div>
- </SurfaceBox>
- ) : (
- <div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,1fr)_28rem]">
- <div className="flex min-w-0 flex-col gap-4">
- <SurfaceBox title="Media" subheader={selectedType ? selectedType.desc : 'Choose what you are posting, then add the file.'}>
- <div className="flex flex-col gap-4">
- <TypePicker value={contentType} onChange={v => { setContentType(v); clearFile(); }} />
- {!file ? (
- <button
- type="button"
- onClick={() => contentType && fileInputRef.current?.click()}
- disabled={!contentType}
- className={cn(
- 'flex w-full flex-col items-center gap-2 rounded-card border border-dashed p-10 text-center transition-colors duration-(--duration-fast)',
- 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
- contentType ? 'border-line-strong/50 hover:border-brand hover:bg-brand-soft/30' : 'cursor-not-allowed border-line opacity-60',
- )}
- >
- <Upload className="size-8 stroke-[1.5] text-ink-faint" />
- <span className="text-sm font-medium text-ink">{contentType ? 'Choose a file' : 'Choose a content type first'}</span>
- {selectedType && <span className="text-caption text-ink-faint">{selectedType.desc}</span>}
- </button>
- ) : (
- <div className="flex flex-col gap-4 sm:flex-row sm:items-start">
- <div className="relative w-full shrink-0 overflow-hidden rounded-control bg-surface-sunken sm:w-52">
- {file.type.startsWith('video/') ? (
- <video src={filePreview} controls muted className="max-h-72 w-full bg-black object-contain" />
- ) : (
- <img src={filePreview} alt="Selected media preview" className="max-h-72 w-full object-contain" />
- )}
- <button
- type="button"
- onClick={clearFile}
- aria-label="Remove file"
- className="absolute top-2 right-2 flex size-7 items-center justify-center rounded-full bg-[#0C0809]/75 text-white transition-colors hover:bg-brand"
- >
- <X className="size-3.5" />
- </button>
- </div>
- <div className="min-w-0">
- <p className="truncate text-sm font-semibold text-ink">{file.name}</p>
- <p className="text-small text-ink-muted">{(file.size / (1024 * 1024)).toFixed(2)} MB, {file.type}</p>
- <Badge variant="default" className="mt-2">{selectedType?.label}</Badge>
- </div>
- </div>
- )}
- <input ref={fileInputRef} type="file" hidden accept={selectedType?.accept || '*'} onChange={handleFileSelect} aria-label="Media file" />
- </div>
- </SurfaceBox>
-
- <SurfaceBox title="Caption">
- <Textarea
- value={caption}
- onChange={e => setCaption(e.target.value)}
- placeholder="Write a caption. Add #hashtags and @mentions."
- rows={7}
- maxLength={CAPTION_LIMIT}
- aria-label="Caption"
- className="min-h-40 border-0 bg-transparent px-0 text-base leading-6 shadow-none hover:border-0 focus-visible:outline-none md:text-base"
- />
- <p className={cn('mt-2 text-right text-caption tabular-nums', caption.length > CAPTION_LIMIT * 0.9 ? 'text-warning' : 'text-ink-faint')}>
- {caption.length.toLocaleString()} / {CAPTION_LIMIT.toLocaleString()}
- </p>
- </SurfaceBox>
- </div>
-
- <DetailPanel
- title="Post settings"
- footer={
- <Button size="lg" className="w-full" onClick={handlePublish} disabled={uploading || !canPublish}>
- {uploading ? <Spinner className="size-4" /> : scheduleMode ? <Calendar data-icon="inline-start" /> : <Send data-icon="inline-start" />}
- {scheduleMode ? 'Schedule post' : 'Publish now'}
- </Button>
- }
- >
- <FieldRow label="Account">
- <AccountSelect accounts={igAccounts} value={selectedAccount} onChange={setSelectedAccount} />
- </FieldRow>
-
- {contentType === 'IMAGE' && (
- <FieldRow label="Alt text" hint="Describes the photo for people using screen readers." htmlFor="alt-text">
- <IconInput id="alt-text" icon={ImageIcon} value={altText} onChange={e => setAltText(e.target.value)} placeholder="A short description of the photo" />
- </FieldRow>
- )}
- <FieldRow label="Collaborators" hint="Separate usernames with commas." htmlFor="collaborators">
- <IconInput id="collaborators" icon={UserPlus} value={collaborators} onChange={e => setCollaborators(e.target.value)} placeholder="username1, username2" />
- </FieldRow>
- <FieldRow label="Tagged people" hint="Separate with commas. Add x and y after a name to position the tag." htmlFor="user-tags">
- <IconInput id="user-tags" icon={AtSign} value={userTags} onChange={e => setUserTags(e.target.value)} placeholder="@username1, @username2" />
- </FieldRow>
- <FieldRow label="Location" hint="The Facebook Page ID of the place." htmlFor="location-id">
- <IconInput id="location-id" icon={MapPin} value={locationId} onChange={e => setLocationId(e.target.value)} placeholder="Location ID" />
- </FieldRow>
-
- {contentType === 'REELS' && (
- <div className="flex flex-col gap-5 border-t border-divider pt-5">
- <div className="flex items-center justify-between gap-3">
- <div>
- <p className="text-sm font-medium text-ink">Share to feed</p>
- <p className="text-caption text-ink-faint">Show the Reel on the profile grid as well.</p>
- </div>
- <Switch checked={shareToFeed} onCheckedChange={setShareToFeed} aria-label="Share to feed" />
- </div>
- <FieldRow label="Audio name" hint="Optional" htmlFor="audio-name">
- <IconInput id="audio-name" icon={Music} value={audioName} onChange={e => setAudioName(e.target.value)} placeholder="Original audio" />
- </FieldRow>
- <FieldRow label="Thumbnail offset" hint="Milliseconds into the video to use as the thumbnail." htmlFor="thumb-offset">
- <IconInput id="thumb-offset" icon={Clock} type="number" min="0" value={thumbOffset} onChange={e => setThumbOffset(e.target.value)} placeholder="0" />
- </FieldRow>
- <FieldRow label="Cover image" hint="Optional JPEG.">
- {!coverFile ? (
- <Button variant="outline" onClick={() => coverInputRef.current?.click()} className="justify-start">
- <Camera data-icon="inline-start" />Choose a cover
- </Button>
- ) : (
- <div className="flex items-center gap-3 rounded-control border border-line p-2">
- <img src={coverPreview} alt="Cover preview" className="size-10 rounded-sm object-cover" />
- <span className="min-w-0 flex-1 truncate text-small text-ink">{coverFile.name}</span>
- <Button variant="ghost" size="icon-xs" onClick={clearCover} aria-label="Remove cover"><X /></Button>
- </div>
- )}
- <input ref={coverInputRef} type="file" hidden accept="image/jpeg" onChange={handleCoverSelect} aria-label="Cover image" />
- </FieldRow>
- </div>
- )}
-
- <div className="flex flex-col gap-4 border-t border-divider pt-5">
- <FieldRow label="When">
- <ScheduleToggle scheduled={scheduleMode} onChange={setScheduleMode} />
- </FieldRow>
- {scheduleMode && (
- <>
- <div className="grid grid-cols-2 gap-2">
- <Input type="date" value={scheduleDate} onChange={e => setScheduleDate(e.target.value)} min={today} aria-label="Schedule date" />
- <Input type="time" value={scheduleTime} onChange={e => setScheduleTime(e.target.value)} aria-label="Schedule time" />
- </div>
- <ScheduleHint />
- </>
- )}
- </div>
-
- <div className="flex flex-col gap-2 rounded-control bg-surface-sunken/60 p-3">
- <SummaryRow label="Account">{selectedAcct ? `@${selectedAcct.username || selectedAcct.title}` : '-'}</SummaryRow>
- <SummaryRow label="Type">{selectedType?.label || '-'}</SummaryRow>
- <SummaryRow label="File">{file ? `${(file.size / (1024 * 1024)).toFixed(1)} MB` : '-'}</SummaryRow>
- <SummaryRow label="Goes live">
- {scheduleMode ? (scheduleDate && scheduleTime ? new Date(`${scheduleDate}T${scheduleTime}`).toLocaleString() : 'Pick a time') : 'Right away'}
- </SummaryRow>
- </div>
- </DetailPanel>
- </div>
- )}
+ <SinglePostTab form={form} publish={publish} igAccounts={igAccounts} onReset={resetAll} />
</TabsContent>
<TabsContent value="bulk">
- <div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,1fr)_28rem]">
- <div className="flex min-w-0 flex-col gap-4">
- <SurfaceBox
- title={`Files${bulkFiles.length ? ` (${bulkFiles.length})` : ''}`}
- subheader={bulkType?.desc}
- secondary={
- <div className="flex gap-2">
- {bulkFiles.length > 0 && !bulkProcessing && (
- <Button size="sm" variant="ghost" onClick={clearBulkFiles} className="hover:bg-danger-soft hover:text-danger">
- <Trash2 data-icon="inline-start" />Clear all
- </Button>
- )}
- <Button size="sm" variant="outline" onClick={() => bulkFileInputRef.current?.click()} disabled={bulkProcessing}>
- <Plus data-icon="inline-start" />Add files
- </Button>
- </div>
- }
- >
- <input ref={bulkFileInputRef} type="file" hidden multiple accept={bulkType?.accept || '*'} onChange={handleBulkFilesSelect} aria-label="Files to upload" />
- {bulkFiles.length === 0 ? (
- <button
- type="button"
- onClick={() => bulkFileInputRef.current?.click()}
- className="flex w-full flex-col items-center gap-2 rounded-card border border-dashed border-line-strong/50 p-10 text-center transition-colors duration-(--duration-fast) hover:border-brand hover:bg-brand-soft/30 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
- >
- <FolderUp className="size-8 stroke-[1.5] text-ink-faint" />
- <span className="text-sm font-medium text-ink">Choose several files</span>
- <span className="text-caption text-ink-faint">Each file becomes its own post, published or scheduled in order.</span>
- </button>
- ) : (
- <ul className="flex max-h-[34rem] flex-col gap-2 overflow-y-auto pr-1">
- {bulkFiles.map((item, idx) => {
- const isActive = ACTIVE_BULK.includes(item.status);
- return (
- <li key={item.id} className={cn('flex items-start gap-3 rounded-field border p-3', isActive ? 'border-brand/40 bg-brand-soft/20' : 'border-line')}>
- <div className="relative size-14 shrink-0 overflow-hidden rounded-control bg-surface-sunken">
- {item.file.type.startsWith('video/')
- ? <video src={item.preview} muted className="size-full object-cover" />
- : <img src={item.preview} alt="" className="size-full object-cover" />}
- <span className="absolute top-0.5 left-0.5 rounded-sm bg-[#0C0809]/75 px-1 font-mono text-[0.5625rem] font-semibold text-white">{idx + 1}</span>
- </div>
- <div className="min-w-0 flex-1">
- <div className="mb-1 flex items-center gap-2">
- <span className="truncate text-sm font-medium text-ink">{item.file.name}</span>
- <span className="shrink-0 text-caption text-ink-faint">{(item.file.size / (1024 * 1024)).toFixed(1)} MB</span>
- </div>
- {item.status === 'pending' ? (
- <Textarea value={item.caption} onChange={e => updateBulkFileCaption(item.id, e.target.value)} placeholder={`Caption for file ${idx + 1}`} rows={1} className="min-h-9 text-small" aria-label={`Caption for file ${idx + 1}`} />
- ) : (
- <p className="truncate text-caption text-ink-muted">{item.caption || 'No caption'}</p>
- )}
- {item.status === 'uploading' && <Progress value={item.progress} className="mt-1.5" aria-label={`Upload progress for file ${idx + 1}`} />}
- {item.error && <p className="mt-1 text-caption text-danger">Error: {item.error}</p>}
- {item.mediaId && <p className="mt-1 font-mono text-caption text-success">Media ID {item.mediaId}</p>}
- </div>
- <div className="flex shrink-0 items-center gap-1.5">
- {isActive && <Spinner className="size-3.5 text-brand" />}
- <StatusBadge status={item.status} map={BULK_STATUS} />
- {item.status === 'pending' && !bulkProcessing && (
- <Button variant="ghost" size="icon-xs" onClick={() => removeBulkFile(item.id)} aria-label={`Remove ${item.file.name}`}><X /></Button>
- )}
- </div>
- </li>
- );
- })}
- </ul>
- )}
- </SurfaceBox>
-
- {(bulkProcessing || bulkStats.done > 0 || bulkStats.scheduled > 0 || bulkStats.errors > 0) && (
- <SurfaceBox title={bulkProcessing ? 'Working through the files' : 'Results'}>
- <div className="flex flex-wrap gap-1.5">
- <Badge variant="outline">{bulkStats.total} total</Badge>
- {bulkStats.done > 0 && <Badge variant="success"><CheckCircle2 />{bulkStats.done} published</Badge>}
- {bulkStats.scheduled > 0 && <Badge variant="warning"><Calendar />{bulkStats.scheduled} scheduled</Badge>}
- {bulkStats.errors > 0 && <Badge variant="destructive"><AlertCircle />{bulkStats.errors} failed</Badge>}
- {bulkStats.pending > 0 && <Badge variant="secondary">{bulkStats.pending} pending</Badge>}
- </div>
- {bulkProcessing && (
- <Progress value={((bulkStats.done + bulkStats.scheduled + bulkStats.errors) / Math.max(1, bulkStats.total)) * 100} className="mt-3" aria-label="Overall progress" />
- )}
- </SurfaceBox>
- )}
- </div>
-
- <DetailPanel
- title="Bulk settings"
- footer={bulkProcessing ? (
- <Button variant="destructive" size="lg" className="w-full" onClick={() => { bulkCancelRef.current = true; }}>
- <Square data-icon="inline-start" />Stop after this file
- </Button>
- ) : (
- <Button size="lg" className="w-full" onClick={handleBulkProcess} disabled={bulkStats.pending === 0 || !bulkAccount || !bulkContentType}>
- {bulkScheduleMode ? <Calendar data-icon="inline-start" /> : <Send data-icon="inline-start" />}
- {bulkScheduleMode ? `Schedule ${bulkStats.pending} post${bulkStats.pending === 1 ? '' : 's'}` : `Publish ${bulkStats.pending} post${bulkStats.pending === 1 ? '' : 's'} now`}
- </Button>
- )}
- >
- <FieldRow label="Account">
- <AccountSelect accounts={igAccounts} value={bulkAccount} onChange={setBulkAccount} disabled={bulkProcessing} />
- </FieldRow>
- <FieldRow label="Content type">
- <TypePicker value={bulkContentType} onChange={setBulkContentType} disabled={bulkProcessing} />
- </FieldRow>
- <FieldRow label="Shared caption" hint="Copies this caption onto every pending file." htmlFor="bulk-caption">
- <div className="flex gap-2">
- <Textarea id="bulk-caption" value={bulkSharedCaption} onChange={e => setBulkSharedCaption(e.target.value)} placeholder="Caption for all files" rows={2} disabled={bulkProcessing} className="flex-1" />
- <Tooltip>
- <TooltipTrigger render={<Button variant="outline" size="icon" onClick={applySharedCaption} disabled={!bulkSharedCaption || bulkProcessing} aria-label="Apply caption to all pending files" />}>
- <Copy />
- </TooltipTrigger>
- <TooltipContent>Apply to all pending files</TooltipContent>
- </Tooltip>
- </div>
- </FieldRow>
- <FieldRow label="Collaborators" hint="Applied to every post." htmlFor="bulk-collaborators">
- <IconInput id="bulk-collaborators" icon={UserPlus} value={bulkCollaborators} onChange={e => setBulkCollaborators(e.target.value)} placeholder="username1, username2" disabled={bulkProcessing} />
- </FieldRow>
- <FieldRow label="Tagged people" hint="Applied to every post." htmlFor="bulk-tags">
- <IconInput id="bulk-tags" icon={AtSign} value={bulkUserTags} onChange={e => setBulkUserTags(e.target.value)} placeholder="@username1, @username2" disabled={bulkProcessing} />
- </FieldRow>
- <FieldRow label="Location" hint="Facebook Page ID, applied to every post." htmlFor="bulk-location">
- <IconInput id="bulk-location" icon={MapPin} value={bulkLocationId} onChange={e => setBulkLocationId(e.target.value)} placeholder="Location ID" disabled={bulkProcessing} />
- </FieldRow>
- {bulkContentType === 'REELS' && (
- <div className="flex items-center justify-between gap-3">
- <p className="text-sm font-medium text-ink">Share Reels to feed</p>
- <Switch checked={bulkShareToFeed} onCheckedChange={setBulkShareToFeed} disabled={bulkProcessing} aria-label="Share Reels to feed" />
- </div>
- )}
-
- <div className="flex flex-col gap-4 border-t border-divider pt-5">
- <FieldRow label="When">
- <ScheduleToggle scheduled={bulkScheduleMode} onChange={setBulkScheduleMode} disabled={bulkProcessing} nowLabel="Publish all now" laterLabel="Spread out" />
- </FieldRow>
- {bulkScheduleMode ? (
- <>
- <div className="grid grid-cols-2 gap-2">
- <Input type="date" value={bulkStartDate} onChange={e => setBulkStartDate(e.target.value)} min={today} disabled={bulkProcessing} aria-label="Start date" />
- <Input type="time" value={bulkStartTime} onChange={e => setBulkStartTime(e.target.value)} disabled={bulkProcessing} aria-label="Start time" />
- </div>
- <ScheduleHint />
- <Select value={String(bulkInterval)} onValueChange={v => setBulkInterval(Number(v))} disabled={bulkProcessing} items={BULK_INTERVAL_OPTIONS.map(o => ({ value: String(o.value), label: o.label }))}>
- <SelectTrigger className="w-full" aria-label="Interval"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {BULK_INTERVAL_OPTIONS.map(o => <SelectItem key={o.value} value={String(o.value)}>{o.label}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
- {bulkStartDate && bulkStartTime && bulkStats.pending > 0 && (
- <Alert variant="info">
- <Info />
- <AlertDescription>
- {bulkStats.pending} posts from {new Date(`${bulkStartDate}T${bulkStartTime}`).toLocaleString()}, {intervalText} apart. The last one goes out {new Date(new Date(`${bulkStartDate}T${bulkStartTime}`).getTime() + (bulkStats.pending - 1) * bulkInterval * 60000).toLocaleString()}.
- </AlertDescription>
- </Alert>
- )}
- </>
- ) : bulkStats.pending > 0 && (
- <Alert>
- <Info />
- <AlertDescription>{bulkStats.pending} files upload and publish one at a time. Instagram allows 100 posts per account every 24 hours.</AlertDescription>
- </Alert>
- )}
- </div>
- </DetailPanel>
- </div>
+ <BulkUploadTab bulk={bulk} queue={queue} bulkPublish={bulkPublish} igAccounts={igAccounts} />
</TabsContent>
</Tabs>
- {scheduledPosts.length > 0 && (
- <section className="flex flex-col gap-3">
- <div className="flex flex-wrap items-end justify-between gap-3">
- <div>
- <h2 className="font-heading text-section font-semibold text-ink">Scheduled posts</h2>
- <p className="text-small text-ink-muted">Posts waiting to go out, and the history of ones that already did.</p>
- </div>
- <div className="flex gap-2">
- <Button size="sm" variant="ghost" onClick={loadScheduledPosts}><RefreshCw data-icon="inline-start" />Refresh</Button>
- <Button size="sm" variant="outline" onClick={() => setConfirmDeleteAll(true)} className="hover:bg-danger-soft hover:text-danger"><Trash2 data-icon="inline-start" />Delete all</Button>
- </div>
- </div>
- {overduePosts.length > 0 && (
- <Alert variant="warning">
- <AlertCircle />
- <AlertDescription>
- {overduePosts.length === 1 ? '1 post is' : `${overduePosts.length} posts are`} more than 30 minutes past their time and still pending, so the scheduler on this server is not running. Email the administrator at{' '}
- <a href={adminMailto('Scheduled posts are not publishing on Twiligent')} className="font-semibold underline underline-offset-4">{ADMIN_EMAIL}</a>.
- If you run this instance, follow the checks in <Link to="/settings#scheduling" className="font-semibold underline underline-offset-4">Settings, Scheduled publishing</Link>.
- </AlertDescription>
- </Alert>
- )}
- <FilterChips label="Status" options={statusChips} value={statusFilter} onChange={setStatusFilter} />
- <SurfaceBox content={false} className="overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead>Account</TableHead>
- <TableHead>Type</TableHead>
- <TableHead className="min-w-48">Caption</TableHead>
- <TableHead className="min-w-40">Scheduled for</TableHead>
- <TableHead className="min-w-40">Published</TableHead>
- <TableHead>Status</TableHead>
- <TableHead className="min-w-40">Error</TableHead>
- <TableHead className="text-right"><span className="sr-only">Actions</span></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {filteredScheduled.map((post, idx) => {
- const acct = igAccounts.find(a => a.id === post.accountId);
- const typeInfo = CONTENT_TYPES.find(t => t.value === post.mediaType);
- const TypeIcon = typeInfo?.icon || ImageIcon;
- const isEditing = editingPostId === post.id;
- const canEdit = post.status === 'pending' || post.status === 'scheduled';
- const isPastDue = post.status === 'pending' && new Date(post.scheduledAt) < new Date();
- return (
- <React.Fragment key={post.id}>
- <TableRow data-state={isEditing ? 'selected' : undefined}>
- <TableCell className="text-right font-mono text-caption text-ink-faint">{idx + 1}</TableCell>
- <TableCell>
- <span className="flex items-center gap-2">
- {acct && <AccountAvatar account={acct} size="xs" />}
- <span className="text-small font-medium text-ink">{acct?.username ? `@${acct.username}` : post.accountId}</span>
- </span>
- </TableCell>
- <TableCell>
- <span className="flex items-center gap-1.5 text-small text-ink-muted"><TypeIcon className="size-3.5" />{typeInfo?.label || post.mediaType}</span>
- </TableCell>
- <TableCell>
- <Tooltip>
- <TooltipTrigger render={<p className="max-w-48 cursor-default truncate text-small text-ink-muted" />}>{post.caption || 'No caption'}</TooltipTrigger>
- <TooltipContent className="max-w-sm">{post.caption || 'No caption'}</TooltipContent>
- </Tooltip>
- </TableCell>
- <TableCell>
- <span className={cn('text-small', isPastDue ? 'text-warning' : 'text-ink-muted')}>{fmtLocalDate(post.scheduledAt)}</span>
- {isPastDue && <p className="text-caption text-warning">Overdue</p>}
- </TableCell>
- <TableCell>
- <span className="flex items-center gap-1 text-small text-ink-muted">
- {fmtLocalDate(post.publishedAt)}
- {post.publishedMediaId && (
- <Tooltip>
- <TooltipTrigger render={<span className="text-success" />}><CheckCircle2 className="size-3.5" /></TooltipTrigger>
- <TooltipContent>Media ID {post.publishedMediaId}</TooltipContent>
- </Tooltip>
- )}
- </span>
- </TableCell>
- <TableCell><StatusBadge status={post.status} map={POST_STATUS} /></TableCell>
- <TableCell>
- {post.error ? (
- <Tooltip>
- <TooltipTrigger render={<p className="max-w-40 cursor-help truncate text-small text-danger" />}>{post.error}</TooltipTrigger>
- <TooltipContent className="max-w-sm">{post.error}</TooltipContent>
- </Tooltip>
- ) : <span className="text-ink-faint">-</span>}
- </TableCell>
- <TableCell className="text-right whitespace-nowrap">
- {canEdit && !isEditing && (
- <Tooltip>
- <TooltipTrigger render={<Button variant="ghost" size="icon-xs" onClick={() => startEditPost(post)} aria-label="Edit scheduled post" />}><Pencil /></TooltipTrigger>
- <TooltipContent>Edit</TooltipContent>
- </Tooltip>
- )}
- {isEditing && <Button variant="ghost" size="icon-xs" onClick={cancelEdit} aria-label="Cancel editing"><X /></Button>}
- {post.status !== 'publishing' && (
- <Tooltip>
- <TooltipTrigger render={<Button variant="ghost" size="icon-xs" onClick={() => setPendingDelete(post)} aria-label={post.status === 'published' ? 'Remove record' : 'Delete scheduled post'} className="hover:bg-danger-soft hover:text-danger" />}><Trash2 /></TooltipTrigger>
- <TooltipContent>{post.status === 'published' ? 'Remove record' : 'Delete'}</TooltipContent>
- </Tooltip>
- )}
- </TableCell>
- </TableRow>
- {isEditing && (
- <TableRow className="hover:bg-transparent">
- <TableCell colSpan={9} className="whitespace-normal bg-surface-sunken/40 p-0">
- <div className="flex flex-col gap-3 p-4">
- <Textarea value={editCaption} onChange={e => setEditCaption(e.target.value)} rows={3} aria-label="Caption" maxLength={CAPTION_LIMIT} />
- <p className="text-caption text-ink-faint tabular-nums">{editCaption.length.toLocaleString()} / {CAPTION_LIMIT.toLocaleString()}</p>
- <div className="flex flex-wrap gap-2">
- <Input type="date" value={editDate} onChange={e => setEditDate(e.target.value)} min={today} className="w-44" aria-label="Date" />
- <Input type="time" value={editTime} onChange={e => setEditTime(e.target.value)} className="w-36" aria-label="Time" />
- </div>
- <div className="flex justify-end gap-2">
- <Button size="sm" variant="outline" onClick={cancelEdit}>Cancel</Button>
- <Button size="sm" onClick={handleSaveEdit} disabled={savingEdit}>
- {savingEdit ? <Spinner className="size-3.5" /> : <CheckCircle2 data-icon="inline-start" />}
- {savingEdit ? 'Saving' : 'Save changes'}
- </Button>
- </div>
- </div>
- </TableCell>
- </TableRow>
- )}
- </React.Fragment>
- );
- })}
- {filteredScheduled.length === 0 && (
- <TableRow className="hover:bg-transparent">
- <TableCell colSpan={9}>
- <EmptyState compact icon={<Calendar />} title={`No ${statusFilter} posts`} description="Choose a different status to see other posts." />
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </SurfaceBox>
- </section>
+ {schedule.scheduledPosts.length > 0 && (
+ <ScheduledPostsSection schedule={schedule} editor={editor} removal={removal} igAccounts={igAccounts} />
)}
<p className="text-caption text-ink-faint">
Files upload to Cloudinary first because Instagram needs a public URL. Twiligent then creates an Instagram media container, waits for processing, and publishes it. Publishing needs the instagram_business_content_publish permission. Instagram allows 100 posts per account every 24 hours.
</p>
- <ConfirmDialog
- open={confirmDeleteAll}
- onOpenChange={setConfirmDeleteAll}
- title="Delete all scheduled posts?"
- description="Every record is removed: pending, published and failed. Pending posts will not go out. Posts already on Instagram stay live; only Twiligent's records are deleted. Posts that are publishing right now are kept."
- confirmLabel="Delete all"
- onConfirm={handleDeleteAll}
- busy={deleting}
- hold
- />
-
- <ConfirmDialog
- open={!!pendingDelete}
- onOpenChange={open => { if (!open) setPendingDelete(null); }}
- title={pendingDelete?.status === 'published' ? 'Remove this record?' : 'Delete this scheduled post?'}
- description={pendingDelete?.status === 'published'
- ? 'The post stays live on Instagram. Only the record in Twiligent is removed.'
- : 'It will not be published. The uploaded media stays in Cloudinary.'}
- confirmLabel={pendingDelete?.status === 'published' ? 'Remove' : 'Delete'}
- onConfirm={handleDeleteScheduled}
- busy={deleting}
- hold
- />
+ <ScheduledPostDialogs removal={removal} />
</div>
);
}
diff --git a/frontend/src/features/publishing/igPublishFlow.js b/frontend/src/features/publishing/igPublishFlow.js
new file mode 100644
index 0000000..cf6c172
--- /dev/null
+++ b/frontend/src/features/publishing/igPublishFlow.js
@@ -0,0 +1,106 @@
+import { api } from '../../services/api';
+import { buildContainerPayload, buildScheduledPostPayload, singleUploadMessage } from './publishHelpers.js';
+
+const POLL_ATTEMPTS = 30;
+const POLL_INTERVAL_MS = 3000;
+const IMAGE_SETTLE_MS = 2000;
+
+export function wait(ms) {
+ return new Promise(resolve => setTimeout(resolve, ms));
+}
+
+function containerFinished(status, failedMessage) {
+ if (status.statusCode === 'FINISHED' || status.statusCode === 'PUBLISHED') return true;
+ if (status.statusCode === 'ERROR') throw new Error(failedMessage);
+ if (status.statusCode === 'EXPIRED') throw new Error('Container expired');
+ return false;
+}
+
+async function pollTolerant(containerId, accountId, onStatus) {
+ try {
+ const status = await api.getIGContainerStatus(containerId, accountId);
+ onStatus(`Instagram status: ${status.statusCode || 'IN_PROGRESS'}`);
+ return containerFinished(status, 'Container processing failed: ' + (status.status || 'Unknown'));
+ } catch (err) {
+ if (err.message.includes('processing failed') || err.message.includes('expired')) throw err;
+ return false;
+ }
+}
+
+async function pollStrict(containerId, accountId) {
+ const status = await api.getIGContainerStatus(containerId, accountId);
+ return containerFinished(status, 'Processing failed');
+}
+
+// single posts ride out failed checks and fail on timeout; bulk stops quietly after the last try
+export async function waitForContainer(containerId, accountId, { tolerant = false, onStatus } = {}) {
+ for (let i = 0; i < POLL_ATTEMPTS; i++) {
+ await wait(POLL_INTERVAL_MS);
+ const finished = tolerant
+ ? await pollTolerant(containerId, accountId, onStatus)
+ : await pollStrict(containerId, accountId);
+ if (finished) return true;
+ }
+ if (tolerant) throw new Error('Instagram took too long to process the media. Try again in a few minutes.');
+ return false;
+}
+
+// photos need no processing, Instagram only needs a moment before they can be published
+export async function waitUntilReady(contentType, containerId, accountId, { onProcessing, ...pollOptions }) {
+ if (contentType !== 'REELS' && contentType !== 'STORIES') {
+ await wait(IMAGE_SETTLE_MS);
+ return;
+ }
+ onProcessing();
+ await waitForContainer(containerId, accountId, pollOptions);
+}
+
+export async function uploadSingleMedia(file, cloudConfig, onProgress) {
+ if (!cloudConfig) throw new Error('Cloudinary is not set up on the server. Check Settings.');
+ try {
+ return await api.uploadToCloudinary(file, cloudConfig, { onProgress });
+ } catch (err) {
+ throw new Error(singleUploadMessage(err));
+ }
+}
+
+async function uploadPostMedia(form, cloudConfig, progress) {
+ const mediaUrl = await uploadSingleMedia(form.file, cloudConfig, progress.setUploadProgress);
+ if (!form.coverFile || form.contentType !== 'REELS') return { mediaUrl, coverUrl: null };
+ progress.setStatusMessage('Uploading cover');
+ const coverUrl = await uploadSingleMedia(form.coverFile, cloudConfig, progress.setUploadProgress);
+ return { mediaUrl, coverUrl };
+}
+
+function postDetails(form, uploaded) {
+ return { ...form.fields, accountId: form.selectedAccount, mediaType: form.contentType, ...uploaded };
+}
+
+export async function scheduleSinglePost(form, cloudConfig, scheduledAt, progress) {
+ const uploaded = await uploadPostMedia(form, cloudConfig, progress);
+ progress.setPublishStatus('scheduling');
+ progress.setStatusMessage('Saving the scheduled post');
+ const res = await api.createScheduledPost(buildScheduledPostPayload({ ...postDetails(form, uploaded), scheduledAt }));
+ if (!res.success) throw new Error(res.message || 'Failed to schedule');
+}
+
+export async function publishSinglePost(form, cloudConfig, progress) {
+ const uploaded = await uploadPostMedia(form, cloudConfig, progress);
+ progress.setPublishStatus('creating-container');
+ progress.setStatusMessage('Creating the Instagram media container');
+ const containerRes = await api.createIGContainer(form.selectedAccount, buildContainerPayload(postDetails(form, uploaded)));
+ if (!containerRes.success || !containerRes.containerId) throw new Error(containerRes.message || 'Failed to create container');
+ await waitUntilReady(form.contentType, containerRes.containerId, form.selectedAccount, {
+ tolerant: true,
+ onStatus: progress.setStatusMessage,
+ onProcessing: () => {
+ progress.setPublishStatus('processing');
+ progress.setStatusMessage('Instagram is processing the media');
+ },
+ });
+ progress.setPublishStatus('publishing');
+ progress.setStatusMessage('Publishing to Instagram');
+ const publishRes = await api.publishIGContainer(form.selectedAccount, containerRes.containerId);
+ if (!publishRes.success || !publishRes.mediaId) throw new Error(publishRes.message || 'Publish failed');
+ return publishRes.mediaId;
+}
diff --git a/frontend/src/features/publishing/publishConstants.js b/frontend/src/features/publishing/publishConstants.js
new file mode 100644
index 0000000..4e9fc68
--- /dev/null
+++ b/frontend/src/features/publishing/publishConstants.js
@@ -0,0 +1,41 @@
+import { Image as ImageIcon, Film, BookOpen } from 'lucide-react';
+
+export const BULK_INTERVAL_OPTIONS = [
+ { value: 720, label: 'Every 12 hours' },
+ { value: 1440, label: 'Once a day' },
+ { value: 2880, label: 'Every 2 days' },
+ { value: 4320, label: 'Every 3 days' },
+ { value: 10080, label: 'Once a week' },
+];
+
+export const CONTENT_TYPES = [
+ { value: 'IMAGE', label: 'Photo', icon: ImageIcon, accept: 'image/jpeg', desc: 'JPEG, 4:5 to 1.91:1, up to 8MB' },
+ { value: 'REELS', label: 'Reel', icon: Film, accept: 'video/mp4,video/quicktime', desc: 'MP4 or MOV, 9:16, 3 seconds to 15 minutes, up to 300MB' },
+ { value: 'STORIES', label: 'Story', icon: BookOpen, accept: 'image/jpeg,video/mp4,video/quicktime', desc: 'Image or video, 9:16, up to 60 seconds' },
+];
+
+export const POST_STATUS = {
+ published: { label: 'Published', variant: 'success' },
+ failed: { label: 'Failed', variant: 'destructive' },
+ publishing: { label: 'Publishing', variant: 'info' },
+ pending: { label: 'Pending', variant: 'warning' },
+};
+
+export const BULK_STATUS = {
+ pending: { label: 'Pending', variant: 'secondary' },
+ uploading: { label: 'Uploading', variant: 'info' },
+ creating: { label: 'Creating', variant: 'info' },
+ processing: { label: 'Processing', variant: 'info' },
+ publishing: { label: 'Publishing', variant: 'info' },
+ scheduling: { label: 'Scheduling', variant: 'info' },
+ done: { label: 'Published', variant: 'success' },
+ scheduled: { label: 'Scheduled', variant: 'warning' },
+ error: { label: 'Failed', variant: 'destructive' },
+};
+
+export const ACTIVE_BULK = ['uploading', 'creating', 'processing', 'publishing', 'scheduling'];
+export const CAPTION_LIMIT = 2200;
+
+export function contentTypeOf(value) {
+ return CONTENT_TYPES.find(type => type.value === value);
+}
diff --git a/frontend/src/features/publishing/publishHelpers.js b/frontend/src/features/publishing/publishHelpers.js
new file mode 100644
index 0000000..a01f937
--- /dev/null
+++ b/frontend/src/features/publishing/publishHelpers.js
@@ -0,0 +1,105 @@
+// post payloads and checks; no JSX or path aliases so node --test can import it
+
+const MINUTE_MS = 60000;
+
+export function parseUserTags(text) {
+ return text.split(',').map(entry => {
+ const parts = entry.trim().replace(/^@/, '').split(/\s+/);
+ return { username: parts[0], x: parts[1] ? parseFloat(parts[1]) : 0.5, y: parts[2] ? parseFloat(parts[2]) : 0.5 };
+ }).filter(tag => tag.username);
+}
+
+export function parseCollaborators(text) {
+ return text.split(',').map(name => name.trim()).filter(Boolean);
+}
+
+export function buildScheduledPostPayload(post) {
+ const { accountId, mediaType, mediaUrl, caption, coverUrl, shareToFeed, collaborators } = post;
+ const { audioName, thumbOffset, locationId, userTags, altText, scheduledAt } = post;
+ return {
+ accountId,
+ platform: 'instagram',
+ mediaType,
+ mediaUrl,
+ caption: caption || '',
+ coverUrl: coverUrl || null,
+ shareToFeed: mediaType === 'REELS' ? shareToFeed : true,
+ collaborators: collaborators ? parseCollaborators(collaborators) : [],
+ audioName: audioName || '',
+ thumbOffset: thumbOffset ? parseInt(thumbOffset, 10) : null,
+ locationId: locationId || '',
+ userTags: userTags ? parseUserTags(userTags) : [],
+ altText: (mediaType === 'IMAGE' && altText) ? altText : '',
+ scheduledAt: scheduledAt.toISOString(),
+ };
+}
+
+export function buildContainerPayload(post) {
+ const { mediaType, mediaUrl, caption, coverUrl, shareToFeed, collaborators } = post;
+ const { audioName, thumbOffset, locationId, userTags, altText } = post;
+ return {
+ mediaType,
+ mediaUrl,
+ caption: caption || undefined,
+ coverUrl: coverUrl || undefined,
+ shareToFeed: mediaType === 'REELS' ? shareToFeed : undefined,
+ collaborators: collaborators ? parseCollaborators(collaborators) : undefined,
+ audioName: audioName || undefined,
+ thumbOffset: thumbOffset ? parseInt(thumbOffset, 10) : undefined,
+ locationId: locationId || undefined,
+ userTags: userTags ? parseUserTags(userTags) : undefined,
+ altText: (mediaType === 'IMAGE' && altText) ? altText : undefined,
+ };
+}
+
+// bulk posts share the queue settings and only carry their own caption
+export function bulkPostDetails(settings, item, mediaUrl) {
+ return {
+ accountId: settings.account,
+ mediaType: settings.contentType,
+ mediaUrl,
+ caption: item.caption,
+ shareToFeed: settings.shareToFeed,
+ collaborators: settings.collaborators,
+ locationId: settings.locationId,
+ userTags: settings.userTags,
+ };
+}
+
+export function singleUploadMessage(err) {
+ if (err.reason === 'network') return 'The upload lost its network connection. Check your connection and try again.';
+ if (err.reason === 'rejected') return err.cloudinaryMessage || 'Upload failed';
+ return err.message;
+}
+
+export function singlePostError({ selectedAccount, file, contentType, hasCloudConfig, fields, now }) {
+ if (!selectedAccount || !file || !contentType) return 'Choose an account, a content type and a file before publishing.';
+ if (!hasCloudConfig) return 'Cloudinary is not set up on the server. Check Settings.';
+ if (!fields.scheduleMode) return '';
+ if (!fields.scheduleDate || !fields.scheduleTime) return 'Set a date and time for the scheduled post.';
+ if (new Date(`${fields.scheduleDate}T${fields.scheduleTime}`) <= now) return 'Pick a time in the future.';
+ return '';
+}
+
+export function bulkBaseTime(settings) {
+ return settings.scheduleMode ? new Date(`${settings.startDate}T${settings.startTime}`) : null;
+}
+
+export function bulkStartError({ settings, fileCount, hasCloudConfig, now }) {
+ if (!settings.account || fileCount === 0 || !settings.contentType) return 'Choose an account, a content type and at least one file.';
+ if (!hasCloudConfig) return 'Cloudinary is not set up on the server. Check Settings.';
+ if (settings.scheduleMode && (!settings.startDate || !settings.startTime)) return 'Set a start date and time for the schedule.';
+ const baseTime = bulkBaseTime(settings);
+ if (baseTime && baseTime <= now) return 'Pick a start time in the future.';
+ return '';
+}
+
+export function editPostError({ postId, date, time, now }) {
+ if (!postId || !date || !time) return 'Set a date and time.';
+ if (new Date(`${date}T${time}`) <= now) return 'Pick a time in the future.';
+ return '';
+}
+
+export function bulkScheduledTime(baseTime, offset, intervalMinutes) {
+ return new Date(baseTime.getTime() + offset * intervalMinutes * MINUTE_MS);
+}
diff --git a/frontend/src/features/publishing/publishHelpers.test.js b/frontend/src/features/publishing/publishHelpers.test.js
new file mode 100644
index 0000000..42abf04
--- /dev/null
+++ b/frontend/src/features/publishing/publishHelpers.test.js
@@ -0,0 +1,118 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ parseUserTags, parseCollaborators, buildScheduledPostPayload, buildContainerPayload, bulkPostDetails,
+ singleUploadMessage, singlePostError, bulkStartError, bulkBaseTime, editPostError, bulkScheduledTime,
+} from './publishHelpers.js';
+
+const scheduledAt = new Date('2030-05-01T08:00:00Z');
+const fullPost = {
+ accountId: 'ig1', mediaType: 'REELS', mediaUrl: 'https://cdn/x.mp4', caption: 'Hello', coverUrl: 'https://cdn/c.jpg',
+ shareToFeed: false, collaborators: 'one, two ,', audioName: 'Song', thumbOffset: '1500', locationId: '42',
+ userTags: '@ann 0.2 0.3, bob', altText: 'Alt',
+};
+const bulkSettings = {
+ account: 'ig2', contentType: 'REELS', shareToFeed: true, collaborators: 'pal', locationId: '', userTags: '',
+ sharedCaption: '', scheduleMode: true, startDate: '2030-05-01', startTime: '08:00', interval: 1440,
+};
+
+test('user tags drop the @, default to the centre and skip empty names', () => {
+ assert.deepEqual(parseUserTags('@ann 0.2 0.3, bob, ,'), [
+ { username: 'ann', x: 0.2, y: 0.3 },
+ { username: 'bob', x: 0.5, y: 0.5 },
+ ]);
+});
+
+test('collaborators are trimmed and empty entries removed', () => {
+ assert.deepEqual(parseCollaborators(' one, two ,,'), ['one', 'two']);
+});
+
+test('the scheduled post payload keeps the exact shape and key order', () => {
+ const payload = buildScheduledPostPayload({ ...fullPost, scheduledAt });
+ assert.equal(JSON.stringify(payload), JSON.stringify({
+ accountId: 'ig1', platform: 'instagram', mediaType: 'REELS', mediaUrl: 'https://cdn/x.mp4', caption: 'Hello',
+ coverUrl: 'https://cdn/c.jpg', shareToFeed: false, collaborators: ['one', 'two'], audioName: 'Song', thumbOffset: 1500,
+ locationId: '42', userTags: [{ username: 'ann', x: 0.2, y: 0.3 }, { username: 'bob', x: 0.5, y: 0.5 }], altText: '',
+ scheduledAt: '2030-05-01T08:00:00.000Z',
+ }));
+});
+
+test('empty single post fields fall back to the scheduled defaults', () => {
+ const payload = buildScheduledPostPayload({ accountId: 'a', mediaType: 'IMAGE', mediaUrl: 'u', altText: 'Alt', scheduledAt });
+ assert.deepEqual(payload, {
+ accountId: 'a', platform: 'instagram', mediaType: 'IMAGE', mediaUrl: 'u', caption: '', coverUrl: null, shareToFeed: true,
+ collaborators: [], audioName: '', thumbOffset: null, locationId: '', userTags: [], altText: 'Alt',
+ scheduledAt: '2030-05-01T08:00:00.000Z',
+ });
+});
+
+test('the container payload leaves out empty fields', () => {
+ assert.equal(JSON.stringify(buildContainerPayload({ ...fullPost })), JSON.stringify({
+ mediaType: 'REELS', mediaUrl: 'https://cdn/x.mp4', caption: 'Hello', coverUrl: 'https://cdn/c.jpg', shareToFeed: false,
+ collaborators: ['one', 'two'], audioName: 'Song', thumbOffset: 1500, locationId: '42',
+ userTags: [{ username: 'ann', x: 0.2, y: 0.3 }, { username: 'bob', x: 0.5, y: 0.5 }],
+ }));
+ assert.equal(JSON.stringify(buildContainerPayload({ mediaType: 'IMAGE', mediaUrl: 'u', altText: 'Alt' })),
+ JSON.stringify({ mediaType: 'IMAGE', mediaUrl: 'u', altText: 'Alt' }));
+});
+
+test('bulk payloads match the shapes the bulk upload has always sent', () => {
+ const item = { caption: '' };
+ const details = bulkPostDetails(bulkSettings, item, 'https://cdn/b.mp4');
+ assert.equal(JSON.stringify(buildScheduledPostPayload({ ...details, scheduledAt })), JSON.stringify({
+ accountId: 'ig2', platform: 'instagram', mediaType: 'REELS', mediaUrl: 'https://cdn/b.mp4', caption: '', coverUrl: null,
+ shareToFeed: true, collaborators: ['pal'], audioName: '', thumbOffset: null, locationId: '', userTags: [], altText: '',
+ scheduledAt: '2030-05-01T08:00:00.000Z',
+ }));
+ assert.equal(JSON.stringify(buildContainerPayload(details)), JSON.stringify({
+ mediaType: 'REELS', mediaUrl: 'https://cdn/b.mp4', caption: undefined, shareToFeed: true, collaborators: ['pal'],
+ locationId: undefined, userTags: undefined,
+ }));
+});
+
+test('single post upload errors keep their own wording', () => {
+ assert.equal(singleUploadMessage({ reason: 'network', message: 'x' }), 'The upload lost its network connection. Check your connection and try again.');
+ assert.equal(singleUploadMessage({ reason: 'rejected', cloudinaryMessage: 'Bad preset', message: 'Upload failed' }), 'Bad preset');
+ assert.equal(singleUploadMessage({ reason: 'rejected', parseMessage: 'Unexpected token', message: 'Upload failed' }), 'Upload failed');
+ assert.equal(singleUploadMessage(new Error('Other')), 'Other');
+});
+
+test('single post checks run in order', () => {
+ const now = new Date('2030-05-01T00:00:00');
+ const base = { selectedAccount: 'a', file: {}, contentType: 'IMAGE', hasCloudConfig: true, now };
+ const fields = { scheduleMode: true, scheduleDate: '2030-05-02', scheduleTime: '09:00' };
+ assert.equal(singlePostError({ ...base, file: null, fields }), 'Choose an account, a content type and a file before publishing.');
+ assert.equal(singlePostError({ ...base, hasCloudConfig: false, fields }), 'Cloudinary is not set up on the server. Check Settings.');
+ assert.equal(singlePostError({ ...base, fields: { ...fields, scheduleTime: '' } }), 'Set a date and time for the scheduled post.');
+ assert.equal(singlePostError({ ...base, fields: { ...fields, scheduleDate: '2030-04-30' } }), 'Pick a time in the future.');
+ assert.equal(singlePostError({ ...base, fields }), '');
+ assert.equal(singlePostError({ ...base, fields: { scheduleMode: false } }), '');
+});
+
+test('bulk start checks run in order', () => {
+ const now = new Date('2030-04-30T00:00:00');
+ const base = { settings: bulkSettings, fileCount: 2, hasCloudConfig: true, now };
+ assert.equal(bulkStartError({ ...base, fileCount: 0 }), 'Choose an account, a content type and at least one file.');
+ assert.equal(bulkStartError({ ...base, hasCloudConfig: false }), 'Cloudinary is not set up on the server. Check Settings.');
+ assert.equal(bulkStartError({ ...base, settings: { ...bulkSettings, startTime: '' } }), 'Set a start date and time for the schedule.');
+ assert.equal(bulkStartError({ ...base, now: new Date('2031-01-01T00:00:00') }), 'Pick a start time in the future.');
+ assert.equal(bulkStartError(base), '');
+ assert.equal(bulkStartError({ ...base, settings: { ...bulkSettings, scheduleMode: false } }), '');
+});
+
+test('bulk base time only exists in schedule mode', () => {
+ assert.equal(bulkBaseTime({ ...bulkSettings, scheduleMode: false }), null);
+ assert.equal(bulkBaseTime(bulkSettings).getTime(), new Date('2030-05-01T08:00').getTime());
+});
+
+test('editing a scheduled post needs a future date and time', () => {
+ const now = new Date('2030-05-01T00:00:00');
+ assert.equal(editPostError({ postId: null, date: '2030-05-02', time: '08:00', now }), 'Set a date and time.');
+ assert.equal(editPostError({ postId: 'p', date: '2030-04-02', time: '08:00', now }), 'Pick a time in the future.');
+ assert.equal(editPostError({ postId: 'p', date: '2030-05-02', time: '08:00', now }), '');
+});
+
+test('bulk posts are spaced by the interval', () => {
+ const base = new Date('2030-05-01T08:00:00Z');
+ assert.equal(bulkScheduledTime(base, 2, 720).toISOString(), '2030-05-02T08:00:00.000Z');
+});
diff --git a/frontend/src/features/publishing/queueHelpers.js b/frontend/src/features/publishing/queueHelpers.js
new file mode 100644
index 0000000..06e668c
--- /dev/null
+++ b/frontend/src/features/publishing/queueHelpers.js
@@ -0,0 +1,66 @@
+// bulk queue and progress helpers; no JSX or path aliases so node --test can import it
+
+const DAY_MINUTES = 1440;
+
+export function intervalLabel(minutes) {
+ if (minutes >= DAY_MINUTES) return `${minutes / DAY_MINUTES} day${minutes > DAY_MINUTES ? 's' : ''}`;
+ return `${minutes / 60} hours`;
+}
+
+export function bulkStatsOf(files) {
+ const countOf = status => files.filter(file => file.status === status).length;
+ return {
+ total: files.length,
+ pending: countOf('pending'),
+ done: countOf('done'),
+ scheduled: countOf('scheduled'),
+ errors: countOf('error'),
+ };
+}
+
+export function bulkFilesTitle(count) {
+ if (!count) return 'Files';
+ return `Files (${count})`;
+}
+
+export function bulkActionLabel(scheduleMode, pending) {
+ const suffix = pending === 1 ? '' : 's';
+ if (scheduleMode) return `Schedule ${pending} post${suffix}`;
+ return `Publish ${pending} post${suffix} now`;
+}
+
+export function progressHeading(publishStatus) {
+ if (publishStatus === 'creating-container') return 'Preparing the post';
+ if (publishStatus === 'scheduling') return 'Saving the schedule';
+ if (publishStatus === 'processing') return 'Instagram is processing the media';
+ return 'Publishing';
+}
+
+export function fileSizeMb(file, digits) {
+ return (file.size / (1024 * 1024)).toFixed(digits);
+}
+
+export function isVideoFile(file) {
+ return file.type.startsWith('video/');
+}
+
+export function newQueueItem(file, id) {
+ return { id, file, preview: URL.createObjectURL(file), caption: '', status: 'pending', progress: 0, error: null, mediaId: null };
+}
+
+export function revokePreview(item) {
+ if (item?.preview) URL.revokeObjectURL(item.preview);
+}
+
+export function removeQueueItem(items, id) {
+ revokePreview(items.find(item => item.id === id));
+ return items.filter(item => item.id !== id);
+}
+
+export function patchQueueItem(items, id, patch) {
+ return items.map(item => (item.id === id ? { ...item, ...patch } : item));
+}
+
+export function applyCaptionToPending(items, caption) {
+ return items.map(item => (item.status === 'pending' ? { ...item, caption } : item));
+}
diff --git a/frontend/src/features/publishing/queueHelpers.test.js b/frontend/src/features/publishing/queueHelpers.test.js
new file mode 100644
index 0000000..7b07679
--- /dev/null
+++ b/frontend/src/features/publishing/queueHelpers.test.js
@@ -0,0 +1,59 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ intervalLabel, bulkStatsOf, bulkFilesTitle, bulkActionLabel, progressHeading, fileSizeMb, isVideoFile,
+ patchQueueItem, applyCaptionToPending, removeQueueItem,
+} from './queueHelpers.js';
+
+test('intervals read in days from a day upward and in hours below', () => {
+ assert.equal(intervalLabel(720), '12 hours');
+ assert.equal(intervalLabel(1440), '1 day');
+ assert.equal(intervalLabel(2880), '2 days');
+ assert.equal(intervalLabel(10080), '7 days');
+});
+
+test('bulk stats count each status', () => {
+ const files = ['pending', 'pending', 'done', 'scheduled', 'error', 'uploading'].map(status => ({ status }));
+ assert.deepEqual(bulkStatsOf(files), { total: 6, pending: 2, done: 1, scheduled: 1, errors: 1 });
+});
+
+test('the files title shows the count once there are files', () => {
+ assert.equal(bulkFilesTitle(0), 'Files');
+ assert.equal(bulkFilesTitle(3), 'Files (3)');
+});
+
+test('the bulk action label matches the mode and count', () => {
+ assert.equal(bulkActionLabel(true, 1), 'Schedule 1 post');
+ assert.equal(bulkActionLabel(true, 0), 'Schedule 0 posts');
+ assert.equal(bulkActionLabel(false, 2), 'Publish 2 posts now');
+});
+
+test('each working status has its own heading', () => {
+ assert.equal(progressHeading('creating-container'), 'Preparing the post');
+ assert.equal(progressHeading('scheduling'), 'Saving the schedule');
+ assert.equal(progressHeading('processing'), 'Instagram is processing the media');
+ assert.equal(progressHeading('publishing'), 'Publishing');
+});
+
+test('file helpers read size and type', () => {
+ const file = { size: 3 * 1024 * 1024 + 512 * 1024, type: 'video/mp4' };
+ assert.equal(fileSizeMb(file, 1), '3.5');
+ assert.equal(fileSizeMb(file, 2), '3.50');
+ assert.equal(isVideoFile(file), true);
+ assert.equal(isVideoFile({ type: 'image/jpeg' }), false);
+});
+
+test('queue updates return new arrays and leave other items alone', () => {
+ const items = [{ id: 1, status: 'pending', caption: '' }, { id: 2, status: 'done', caption: 'kept' }];
+ const patched = patchQueueItem(items, 1, { status: 'uploading', progress: 0 });
+ assert.deepEqual(patched[0], { id: 1, status: 'uploading', caption: '', progress: 0 });
+ assert.equal(patched[1], items[1]);
+ assert.notEqual(patched, items);
+ assert.deepEqual(applyCaptionToPending(items, 'Hi').map(item => item.caption), ['Hi', 'kept']);
+});
+
+test('removing a queue item keeps the others', () => {
+ const items = [{ id: 1 }, { id: 2 }];
+ assert.deepEqual(removeQueueItem(items, 1), [{ id: 2 }]);
+ assert.equal(items.length, 2);
+});
diff --git a/frontend/src/features/publishing/scheduleHelpers.js b/frontend/src/features/publishing/scheduleHelpers.js
new file mode 100644
index 0000000..498ca55
--- /dev/null
+++ b/frontend/src/features/publishing/scheduleHelpers.js
@@ -0,0 +1,72 @@
+// scheduled post list and date helpers; no JSX or path aliases so node --test can import it
+
+export const OVERDUE_MS = 30 * 60 * 1000;
+
+function pad(value) {
+ return String(value).padStart(2, '0');
+}
+
+export function scheduledStatusChips(posts) {
+ const countOf = status => posts.filter(post => post.status === status).length;
+ return [
+ { value: 'all', label: 'All', count: posts.length },
+ { value: 'pending', label: 'Pending', count: countOf('pending') },
+ { value: 'publishing', label: 'Publishing', count: countOf('publishing') },
+ { value: 'published', label: 'Published', count: countOf('published') },
+ { value: 'failed', label: 'Failed', count: countOf('failed') },
+ ];
+}
+
+export function filterScheduledPosts(posts, statusFilter) {
+ return posts
+ .filter(post => statusFilter === 'all' || post.status === statusFilter)
+ .sort((first, second) => new Date(second.scheduledAt) - new Date(first.scheduledAt));
+}
+
+export function overduePostsOf(posts, now = Date.now()) {
+ return posts.filter(post => post.status === 'pending' && now - new Date(post.scheduledAt).getTime() > OVERDUE_MS);
+}
+
+export function isPastDue(post, now = new Date()) {
+ return post.status === 'pending' && new Date(post.scheduledAt) < now;
+}
+
+export function overdueLead(count) {
+ if (count === 1) return '1 post is';
+ return `${count} posts are`;
+}
+
+export function deleteAllMessage(deleted) {
+ const suffix = deleted === 1 ? '' : 's';
+ return `Deleted ${deleted} post${suffix}`;
+}
+
+export function formatScheduleDate(iso) {
+ if (!iso) return '-';
+ return new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
+}
+
+export function toLocalDateInput(date) {
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
+}
+
+export function toLocalTimeInput(date) {
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
+}
+
+// the page has always used the UTC calendar day for date inputs
+export function utcDateInput(date = new Date()) {
+ return date.toISOString().split('T')[0];
+}
+
+export function defaultBulkStartDate(now = new Date()) {
+ const tomorrow = new Date(now);
+ tomorrow.setDate(tomorrow.getDate() + 1);
+ return utcDateInput(tomorrow);
+}
+
+export function goesLiveLabel({ scheduleMode, scheduleDate, scheduleTime }) {
+ if (!scheduleMode) return 'Right away';
+ if (!scheduleDate || !scheduleTime) return 'Pick a time';
+ return new Date(`${scheduleDate}T${scheduleTime}`).toLocaleString();
+}
diff --git a/frontend/src/features/publishing/scheduleHelpers.test.js b/frontend/src/features/publishing/scheduleHelpers.test.js
new file mode 100644
index 0000000..f531a2c
--- /dev/null
+++ b/frontend/src/features/publishing/scheduleHelpers.test.js
@@ -0,0 +1,70 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ OVERDUE_MS, scheduledStatusChips, filterScheduledPosts, overduePostsOf, isPastDue, overdueLead, deleteAllMessage,
+ formatScheduleDate, toLocalDateInput, toLocalTimeInput, utcDateInput, defaultBulkStartDate, goesLiveLabel,
+} from './scheduleHelpers.js';
+
+const posts = [
+ { id: 1, status: 'pending', scheduledAt: '2030-05-01T08:00:00Z' },
+ { id: 2, status: 'published', scheduledAt: '2030-05-03T08:00:00Z' },
+ { id: 3, status: 'pending', scheduledAt: '2030-05-02T08:00:00Z' },
+ { id: 4, status: 'failed', scheduledAt: '2030-04-01T08:00:00Z' },
+];
+
+test('status chips count every status', () => {
+ assert.deepEqual(scheduledStatusChips(posts).map(chip => [chip.value, chip.count]), [
+ ['all', 4], ['pending', 2], ['publishing', 0], ['published', 1], ['failed', 1],
+ ]);
+});
+
+test('the filter sorts newest first without changing the input', () => {
+ const before = posts.map(post => post.id);
+ assert.deepEqual(filterScheduledPosts(posts, 'all').map(post => post.id), [2, 3, 1, 4]);
+ assert.deepEqual(filterScheduledPosts(posts, 'pending').map(post => post.id), [3, 1]);
+ assert.deepEqual(posts.map(post => post.id), before);
+});
+
+test('a post is overdue only when more than 30 minutes late', () => {
+ const due = new Date('2030-05-01T08:00:00Z').getTime();
+ assert.deepEqual(overduePostsOf(posts, due + OVERDUE_MS).map(post => post.id), []);
+ assert.deepEqual(overduePostsOf(posts, due + OVERDUE_MS + 1).map(post => post.id), [1]);
+});
+
+test('only pending posts can be past due', () => {
+ const now = new Date('2030-06-01T00:00:00Z');
+ assert.equal(isPastDue(posts[0], now), true);
+ assert.equal(isPastDue(posts[1], now), false);
+ assert.equal(isPastDue(posts[0], new Date('2030-04-01T00:00:00Z')), false);
+});
+
+test('counts read naturally', () => {
+ assert.equal(overdueLead(1), '1 post is');
+ assert.equal(overdueLead(3), '3 posts are');
+ assert.equal(deleteAllMessage(1), 'Deleted 1 post');
+ assert.equal(deleteAllMessage(0), 'Deleted 0 posts');
+});
+
+test('missing dates show a dash', () => {
+ assert.equal(formatScheduleDate(null), '-');
+ assert.equal(formatScheduleDate('2030-05-01T08:00:00Z'), new Date('2030-05-01T08:00:00Z').toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }));
+});
+
+test('local inputs use the local calendar and clock', () => {
+ const date = new Date(2030, 0, 5, 7, 3);
+ assert.equal(toLocalDateInput(date), '2030-01-05');
+ assert.equal(toLocalTimeInput(date), '07:03');
+});
+
+test('the default bulk start is the next day in UTC', () => {
+ const now = new Date(2030, 0, 5, 12, 0);
+ const tomorrow = new Date(2030, 0, 6, 12, 0);
+ assert.equal(defaultBulkStartDate(now), tomorrow.toISOString().split('T')[0]);
+ assert.equal(utcDateInput(now), now.toISOString().split('T')[0]);
+});
+
+test('the goes live label follows the schedule fields', () => {
+ assert.equal(goesLiveLabel({ scheduleMode: false, scheduleDate: '2030-05-01', scheduleTime: '08:00' }), 'Right away');
+ assert.equal(goesLiveLabel({ scheduleMode: true, scheduleDate: '2030-05-01', scheduleTime: '' }), 'Pick a time');
+ assert.equal(goesLiveLabel({ scheduleMode: true, scheduleDate: '2030-05-01', scheduleTime: '08:00' }), new Date('2030-05-01T08:00').toLocaleString());
+});
diff --git a/frontend/src/features/publishing/useBulkPublish.js b/frontend/src/features/publishing/useBulkPublish.js
new file mode 100644
index 0000000..7fd4ee0
--- /dev/null
+++ b/frontend/src/features/publishing/useBulkPublish.js
@@ -0,0 +1,97 @@
+import { api } from '../../services/api';
+import { waitUntilReady, wait } from './igPublishFlow.js';
+import {
+ buildContainerPayload, buildScheduledPostPayload, bulkBaseTime, bulkPostDetails, bulkScheduledTime, bulkStartError,
+} from './publishHelpers.js';
+
+const CANCELLED = 'cancelled';
+const DONE = 'done';
+const BETWEEN_FILES_MS = 2000;
+
+async function scheduleItem(run, item, mediaUrl, offset) {
+ const { settings } = run;
+ run.patchFile(item.id, { status: 'scheduling', progress: 100 });
+ const scheduledAt = bulkScheduledTime(run.baseTime, offset, settings.interval);
+ const res = await api.createScheduledPost(buildScheduledPostPayload({ ...bulkPostDetails(settings, item, mediaUrl), scheduledAt }));
+ if (!res.success) throw new Error(res.message || 'Failed to schedule');
+ run.patchFile(item.id, { status: 'scheduled', progress: 100 });
+}
+
+async function publishItem(run, item, mediaUrl) {
+ const { settings } = run;
+ run.patchFile(item.id, { status: 'creating', progress: 100 });
+ const containerRes = await api.createIGContainer(settings.account, buildContainerPayload(bulkPostDetails(settings, item, mediaUrl)));
+ if (!containerRes.success || !containerRes.containerId) throw new Error(containerRes.message || 'Container creation failed');
+ if (run.isCancelled()) return CANCELLED;
+ await waitUntilReady(settings.contentType, containerRes.containerId, settings.account, {
+ onProcessing: () => run.patchFile(item.id, { status: 'processing' }),
+ });
+ if (run.isCancelled()) return CANCELLED;
+ run.patchFile(item.id, { status: 'publishing' });
+ const publishRes = await api.publishIGContainer(settings.account, containerRes.containerId);
+ if (!publishRes.success || !publishRes.mediaId) throw new Error(publishRes.message || 'Publish failed');
+ run.patchFile(item.id, { status: 'done', mediaId: publishRes.mediaId });
+ return DONE;
+}
+
+async function processItem(run, item, offset) {
+ run.patchFile(item.id, { status: 'uploading', progress: 0 });
+ const onProgress = progress => run.patchFile(item.id, { progress });
+ const mediaUrl = await api.uploadToCloudinary(item.file, run.cloudConfig, { onProgress });
+ if (run.isCancelled()) return CANCELLED;
+ if (!run.settings.scheduleMode) return publishItem(run, item, mediaUrl);
+ await scheduleItem(run, item, mediaUrl, offset);
+ return DONE;
+}
+
+// a stop request ends the loop without touching the file in progress
+async function runQueue(run, pendingFiles) {
+ const tally = { offset: 0, succeeded: 0, failed: 0 };
+ for (let i = 0; i < pendingFiles.length; i++) {
+ if (run.isCancelled()) break;
+ const item = pendingFiles[i];
+ try {
+ const outcome = await processItem(run, item, tally.offset);
+ if (outcome === CANCELLED) break;
+ if (run.settings.scheduleMode) tally.offset++;
+ tally.succeeded++;
+ } catch (err) {
+ run.patchFile(item.id, { status: 'error', error: err.message });
+ tally.failed++;
+ }
+ if (i < pendingFiles.length - 1 && !run.isCancelled()) await wait(BETWEEN_FILES_MS);
+ }
+ return tally;
+}
+
+export function useBulkPublish({ queue, settings, cloudConfig, showToast, onScheduled }) {
+ const { cancelRef } = queue;
+
+ // the queue and settings are read once, as they are at the moment of the click
+ const handleBulkProcess = async () => {
+ const error = bulkStartError({ settings, fileCount: queue.files.length, hasCloudConfig: !!cloudConfig, now: new Date() });
+ if (error) {
+ showToast(error, 'error');
+ return;
+ }
+ const baseTime = bulkBaseTime(settings);
+ queue.setProcessing(true);
+ cancelRef.current = false;
+ const pendingFiles = queue.files.filter(item => item.status === 'pending');
+ const run = { settings, cloudConfig, baseTime, patchFile: queue.patchFile, isCancelled: () => cancelRef.current };
+ const tally = await runQueue(run, pendingFiles);
+ queue.setProcessing(false);
+ if (cancelRef.current) {
+ showToast('Bulk upload stopped. Files already processed keep their status.', 'warning');
+ return;
+ }
+ showToast(`Bulk upload finished: ${tally.succeeded} succeeded, ${tally.failed} failed`, tally.succeeded > 0 ? 'success' : 'error');
+ if (settings.scheduleMode) onScheduled();
+ };
+
+ const stopBulk = () => {
+ cancelRef.current = true;
+ };
+
+ return { handleBulkProcess, stopBulk };
+}
diff --git a/frontend/src/features/publishing/useBulkQueue.js b/frontend/src/features/publishing/useBulkQueue.js
new file mode 100644
index 0000000..4f8b7dc
--- /dev/null
+++ b/frontend/src/features/publishing/useBulkQueue.js
@@ -0,0 +1,44 @@
+import { useRef, useState } from 'react';
+import {
+ applyCaptionToPending, newQueueItem, patchQueueItem, removeQueueItem, revokePreview,
+} from './queueHelpers.js';
+
+export function useBulkQueue({ sharedCaption, onFirstFiles }) {
+ const [files, setFiles] = useState([]);
+ const [processing, setProcessing] = useState(false);
+ const fileInputRef = useRef(null);
+ const idCounter = useRef(0);
+ const cancelRef = useRef(false);
+
+ const handleFilesSelect = e => {
+ const picked = Array.from(e.target.files || []);
+ if (!picked.length) return;
+ const newItems = picked.map(file => newQueueItem(file, ++idCounter.current));
+ setFiles(prev => {
+ if (prev.length === 0) onFirstFiles();
+ return [...prev, ...newItems];
+ });
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ };
+
+ const removeFile = id => setFiles(prev => removeQueueItem(prev, id));
+
+ const patchFile = (id, patch) => setFiles(prev => patchQueueItem(prev, id, patch));
+
+ const applySharedCaption = () => {
+ if (!sharedCaption) return;
+ setFiles(prev => applyCaptionToPending(prev, sharedCaption));
+ };
+
+ const clearFiles = () => {
+ files.forEach(revokePreview);
+ setFiles([]);
+ setProcessing(false);
+ cancelRef.current = false;
+ };
+
+ return {
+ files, processing, setProcessing, fileInputRef, cancelRef,
+ handleFilesSelect, removeFile, patchFile, applySharedCaption, clearFiles,
+ };
+}
diff --git a/frontend/src/features/publishing/useBulkSettings.js b/frontend/src/features/publishing/useBulkSettings.js
new file mode 100644
index 0000000..3d6ec1e
--- /dev/null
+++ b/frontend/src/features/publishing/useBulkSettings.js
@@ -0,0 +1,30 @@
+import { useState } from 'react';
+import { defaultBulkStartDate } from './scheduleHelpers.js';
+
+const INITIAL_SETTINGS = {
+ account: '',
+ contentType: 'REELS',
+ sharedCaption: '',
+ collaborators: '',
+ userTags: '',
+ locationId: '',
+ shareToFeed: true,
+ scheduleMode: false,
+ startDate: '',
+ startTime: '',
+ interval: 1440,
+};
+
+export function useBulkSettings() {
+ const [settings, setSettings] = useState(INITIAL_SETTINGS);
+
+ const setSetting = (name, value) => setSettings(prev => ({ ...prev, [name]: value }));
+
+ // the first files added default to one post a day from 08:00 the next day
+ const applyFirstBatchDefaults = () => {
+ const startDate = defaultBulkStartDate();
+ setSettings(prev => ({ ...prev, scheduleMode: true, interval: 1440, startTime: '08:00', startDate }));
+ };
+
+ return { settings, setSetting, applyFirstBatchDefaults };
+}
diff --git a/frontend/src/features/publishing/usePublishProgress.js b/frontend/src/features/publishing/usePublishProgress.js
new file mode 100644
index 0000000..1f528f4
--- /dev/null
+++ b/frontend/src/features/publishing/usePublishProgress.js
@@ -0,0 +1,28 @@
+import { useState } from 'react';
+
+export function usePublishProgress() {
+ const [activeStep, setActiveStep] = useState(0);
+ const [uploadProgress, setUploadProgress] = useState(0);
+ const [publishStatus, setPublishStatus] = useState('');
+ const [statusMessage, setStatusMessage] = useState('');
+ const [publishedMediaId, setPublishedMediaId] = useState(null);
+
+ // try again goes back to the form but keeps the last upload percentage
+ const retry = () => {
+ setActiveStep(0);
+ setPublishStatus('');
+ };
+
+ const resetProgress = () => {
+ setActiveStep(0);
+ setPublishStatus('');
+ setStatusMessage('');
+ setPublishedMediaId(null);
+ setUploadProgress(0);
+ };
+
+ return {
+ activeStep, setActiveStep, uploadProgress, setUploadProgress, publishStatus, setPublishStatus,
+ statusMessage, setStatusMessage, publishedMediaId, setPublishedMediaId, retry, resetProgress,
+ };
+}
diff --git a/frontend/src/features/publishing/useScheduledPostDelete.js b/frontend/src/features/publishing/useScheduledPostDelete.js
new file mode 100644
index 0000000..980780b
--- /dev/null
+++ b/frontend/src/features/publishing/useScheduledPostDelete.js
@@ -0,0 +1,43 @@
+import { useState } from 'react';
+import { api } from '../../services/api';
+import { deleteAllMessage } from './scheduleHelpers.js';
+
+export function useScheduledPostDelete({ showToast, loadScheduledPosts }) {
+ const [pendingDelete, setPendingDelete] = useState(null);
+ const [confirmDeleteAll, setConfirmDeleteAll] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+
+ const handleDeleteScheduled = async () => {
+ if (!pendingDelete) return;
+ setDeleting(true);
+ try {
+ await api.deleteScheduledPost(pendingDelete.id);
+ showToast(pendingDelete.status === 'published' ? 'Record removed' : 'Scheduled post deleted');
+ loadScheduledPosts();
+ } catch (err) {
+ showToast(`Couldn't delete the post. ${err.message}`, 'error');
+ } finally {
+ setDeleting(false);
+ setPendingDelete(null);
+ }
+ };
+
+ const handleDeleteAll = async () => {
+ setDeleting(true);
+ try {
+ const res = await api.deleteAllScheduledPosts();
+ showToast(deleteAllMessage(res.deleted));
+ loadScheduledPosts();
+ } catch (err) {
+ showToast(`Couldn't delete the posts. ${err.message}`, 'error');
+ } finally {
+ setDeleting(false);
+ setConfirmDeleteAll(false);
+ }
+ };
+
+ return {
+ pendingDelete, setPendingDelete, confirmDeleteAll, setConfirmDeleteAll, deleting,
+ handleDeleteScheduled, handleDeleteAll,
+ };
+}
diff --git a/frontend/src/features/publishing/useScheduledPostEdit.js b/frontend/src/features/publishing/useScheduledPostEdit.js
new file mode 100644
index 0000000..364e72b
--- /dev/null
+++ b/frontend/src/features/publishing/useScheduledPostEdit.js
@@ -0,0 +1,44 @@
+import { useState } from 'react';
+import { api } from '../../services/api';
+import { editPostError } from './publishHelpers.js';
+import { toLocalDateInput, toLocalTimeInput } from './scheduleHelpers.js';
+
+const EMPTY_DRAFT = { postId: null, caption: '', date: '', time: '' };
+
+export function useScheduledPostEdit({ showToast, loadScheduledPosts }) {
+ const [draft, setDraft] = useState(EMPTY_DRAFT);
+ const [savingEdit, setSavingEdit] = useState(false);
+
+ const setDraftField = (name, value) => setDraft(prev => ({ ...prev, [name]: value }));
+
+ const startEditPost = post => {
+ const scheduledAt = new Date(post.scheduledAt);
+ const date = toLocalDateInput(scheduledAt);
+ setDraft({ postId: post.id, caption: post.caption || '', date, time: toLocalTimeInput(scheduledAt) });
+ };
+
+ const cancelEdit = () => setDraft(EMPTY_DRAFT);
+
+ const handleSaveEdit = async () => {
+ const error = editPostError({ ...draft, now: new Date() });
+ if (error) {
+ showToast(error, 'error');
+ return;
+ }
+ const scheduledAt = new Date(`${draft.date}T${draft.time}`);
+ setSavingEdit(true);
+ try {
+ const res = await api.updateScheduledPost(draft.postId, { caption: draft.caption, scheduledAt: scheduledAt.toISOString() });
+ if (!res.success) throw new Error(res.message || 'Update failed');
+ showToast('Scheduled post updated');
+ cancelEdit();
+ loadScheduledPosts();
+ } catch (err) {
+ showToast(`Couldn't update the post. ${err.message}`, 'error');
+ } finally {
+ setSavingEdit(false);
+ }
+ };
+
+ return { draft, setDraftField, savingEdit, startEditPost, cancelEdit, handleSaveEdit };
+}
diff --git a/frontend/src/features/publishing/useScheduledPosts.js b/frontend/src/features/publishing/useScheduledPosts.js
new file mode 100644
index 0000000..92627db
--- /dev/null
+++ b/frontend/src/features/publishing/useScheduledPosts.js
@@ -0,0 +1,19 @@
+import { useCallback, useState } from 'react';
+import { api } from '../../services/api';
+
+export function useScheduledPosts() {
+ const [scheduledPosts, setScheduledPosts] = useState([]);
+ const [statusFilter, setStatusFilter] = useState('all');
+
+ const loadScheduledPosts = useCallback(async () => {
+ try {
+ const res = await api.getScheduledPosts();
+ if (res.success) setScheduledPosts(res.posts || []);
+ } catch {
+ // the schedule list is optional, publishing still works
+ return;
+ }
+ }, []);
+
+ return { scheduledPosts, loadScheduledPosts, statusFilter, setStatusFilter };
+}
diff --git a/frontend/src/features/publishing/useSinglePostForm.js b/frontend/src/features/publishing/useSinglePostForm.js
new file mode 100644
index 0000000..5aaed22
--- /dev/null
+++ b/frontend/src/features/publishing/useSinglePostForm.js
@@ -0,0 +1,46 @@
+import { useState } from 'react';
+import { useSinglePostMedia } from './useSinglePostMedia';
+
+const INITIAL_FIELDS = {
+ caption: '',
+ shareToFeed: true,
+ audioName: '',
+ thumbOffset: '',
+ locationId: '',
+ collaborators: '',
+ userTags: '',
+ altText: '',
+ scheduleMode: false,
+ scheduleDate: '',
+ scheduleTime: '',
+};
+
+export function useSinglePostForm() {
+ const media = useSinglePostMedia();
+ const [selectedAccount, setSelectedAccount] = useState('');
+ const [contentType, setContentType] = useState('');
+ const [fields, setFields] = useState(INITIAL_FIELDS);
+
+ const setField = (name, value) => setFields(prev => ({ ...prev, [name]: value }));
+
+ const changeContentType = value => {
+ setContentType(value);
+ media.clearFile();
+ };
+
+ // the account stays selected so the next post goes to the same place
+ const resetForm = () => {
+ media.clearFile();
+ media.clearCover();
+ setFields(INITIAL_FIELDS);
+ setContentType('');
+ };
+
+ const scheduleIncomplete = fields.scheduleMode && (!fields.scheduleDate || !fields.scheduleTime);
+ const canPublish = !!media.file && !!contentType && !!selectedAccount && !scheduleIncomplete;
+
+ return {
+ ...media, selectedAccount, setSelectedAccount, contentType, changeContentType,
+ fields, setField, resetForm, canPublish,
+ };
+}
diff --git a/frontend/src/features/publishing/useSinglePostMedia.js b/frontend/src/features/publishing/useSinglePostMedia.js
new file mode 100644
index 0000000..edf7fa3
--- /dev/null
+++ b/frontend/src/features/publishing/useSinglePostMedia.js
@@ -0,0 +1,45 @@
+import { useRef, useState } from 'react';
+
+function clearInput(inputRef) {
+ if (inputRef.current) inputRef.current.value = '';
+}
+
+export function useSinglePostMedia() {
+ const [file, setFile] = useState(null);
+ const [filePreview, setFilePreview] = useState(null);
+ const [coverFile, setCoverFile] = useState(null);
+ const [coverPreview, setCoverPreview] = useState(null);
+ const fileInputRef = useRef(null);
+ const coverInputRef = useRef(null);
+
+ const handleFileSelect = e => {
+ const picked = e.target.files?.[0];
+ if (!picked) return;
+ setFile(picked);
+ setFilePreview(URL.createObjectURL(picked));
+ };
+
+ const handleCoverSelect = e => {
+ const picked = e.target.files?.[0];
+ if (!picked) return;
+ setCoverFile(picked);
+ setCoverPreview(URL.createObjectURL(picked));
+ };
+
+ const clearFile = () => {
+ setFile(null);
+ setFilePreview(null);
+ clearInput(fileInputRef);
+ };
+
+ const clearCover = () => {
+ setCoverFile(null);
+ setCoverPreview(null);
+ clearInput(coverInputRef);
+ };
+
+ return {
+ file, filePreview, coverFile, coverPreview, fileInputRef, coverInputRef,
+ handleFileSelect, handleCoverSelect, clearFile, clearCover,
+ };
+}
diff --git a/frontend/src/features/publishing/useSinglePublish.js b/frontend/src/features/publishing/useSinglePublish.js
new file mode 100644
index 0000000..7fd57df
--- /dev/null
+++ b/frontend/src/features/publishing/useSinglePublish.js
@@ -0,0 +1,72 @@
+import { useState } from 'react';
+import { usePublishProgress } from './usePublishProgress';
+import { publishSinglePost, scheduleSinglePost } from './igPublishFlow.js';
+import { singlePostError } from './publishHelpers.js';
+
+function beginRun(run) {
+ run.setUploading(true);
+ run.progress.setPublishStatus('uploading-cloudinary');
+ run.progress.setActiveStep(2);
+}
+
+function failRun(run, err, title) {
+ run.progress.setPublishStatus('error');
+ run.progress.setStatusMessage(err.message);
+ run.showToast(`${title}. ${err.message}`, 'error');
+}
+
+async function schedulePost(run) {
+ const { form, progress } = run;
+ const scheduledAt = new Date(`${form.fields.scheduleDate}T${form.fields.scheduleTime}`);
+ beginRun(run);
+ try {
+ await scheduleSinglePost(form, run.cloudConfig, scheduledAt, progress);
+ progress.setPublishStatus('scheduled');
+ progress.setStatusMessage(`Scheduled for ${scheduledAt.toLocaleString()}`);
+ run.showToast('Post scheduled');
+ run.onScheduled();
+ } catch (err) {
+ failRun(run, err, 'Scheduling failed');
+ } finally {
+ run.setUploading(false);
+ }
+}
+
+async function publishNow(run) {
+ const { progress } = run;
+ beginRun(run);
+ progress.setStatusMessage('Uploading media');
+ try {
+ const mediaId = await publishSinglePost(run.form, run.cloudConfig, progress);
+ progress.setPublishStatus('done');
+ progress.setPublishedMediaId(mediaId);
+ progress.setStatusMessage('Published');
+ run.showToast('Published to Instagram');
+ } catch (err) {
+ failRun(run, err, 'Publishing failed');
+ } finally {
+ run.setUploading(false);
+ }
+}
+
+export function useSinglePublish({ form, cloudConfig, showToast, onScheduled }) {
+ const progress = usePublishProgress();
+ const [uploading, setUploading] = useState(false);
+
+ // reads the form as it is at the moment of the click
+ const handlePublish = async () => {
+ const error = singlePostError({ ...form, hasCloudConfig: !!cloudConfig, now: new Date() });
+ if (error) {
+ showToast(error, 'error');
+ return;
+ }
+ const run = { form, cloudConfig, progress, setUploading, showToast, onScheduled };
+ if (form.fields.scheduleMode) {
+ await schedulePost(run);
+ return;
+ }
+ await publishNow(run);
+ };
+
+ return { ...progress, uploading, handlePublish };
+}