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.

feat(frontend): show form errors at their field and protect typed work

spacesdrivea763bc878a7f
diff --git a/docs/architecture/data-flows/PUBLISHING.md b/docs/architecture/data-flows/PUBLISHING.md
index d40209b..906ca3b 100644
--- a/docs/architecture/data-flows/PUBLISHING.md
+++ b/docs/architecture/data-flows/PUBLISHING.md
@@ -32,9 +32,11 @@ User selects account + uploads media + fills caption
-> Poll every 3 seconds, up to 30 times (about 90 seconds); after that the post fails
with a "took too long" message, in single and bulk publishing alike, because
publishing an unfinished container fails anyway
- -> Wait for status_code = 'FINISHED'
- -> ERROR -> throw error, mark as failed
- -> EXPIRED -> throw error
+ -> Wait for status_code = 'FINISHED'; while waiting the page shows the seconds waited
+ against the usual minute, and a single post offers Stop waiting (an AbortSignal that
+ ends the wait; the container is left unpublished)
+ -> ERROR -> ContainerFailedError with a plain message (try a shorter H.264 MP4), mark as failed
+ -> EXPIRED -> ContainerFailedError: publish again
│
▼
4. Frontend: Publish the container
@@ -45,7 +47,9 @@ User selects account + uploads media + fills caption
-> Returns { mediaId }
│
▼
-5. Frontend: Show success toast with mediaId
+5. Frontend: Show the result screen (Published, Post scheduled or the failure with Try again,
+ which keeps the file and fields); its heading takes focus. Problems found before upload
+ (account, type, file, schedule) are shown under their field, not in a toast
```
## Scheduled Publishing
@@ -103,7 +107,7 @@ The full failure table is in `docs/architecture/data-flows/SCHEDULING.md`.
| Type | Container params | Status polling | Notes |
|---|---|---|---|
| IMAGE | `image_url`, optional `alt_text`, `location_id`, `user_tags` | No | Publishes immediately |
-| REELS | `video_url`, `media_type=REELS`, optional `share_to_feed`, `cover_url`, `audio_name`, `thumb_offset`, `collaborators` | Yes | Requires FINISHED before publish |
+| REELS | `video_url`, `media_type=REELS`, optional `share_to_feed`, `cover_url`, `audio_name`, `thumb_offset`, `collaborators` | Yes | Requires FINISHED before publish; the form takes the thumbnail time in seconds and sends `thumb_offset` in milliseconds |
| STORIES | `video_url` or `image_url`, `media_type=STORIES`, optional `user_tags` | Yes (for video) | Images publish immediately |
## Error States
diff --git a/frontend/src/components/AccountSelect.tsx b/frontend/src/components/AccountSelect.tsx
index 901d058..15f723a 100644
--- a/frontend/src/components/AccountSelect.tsx
+++ b/frontend/src/components/AccountSelect.tsx
@@ -7,16 +7,20 @@ interface AccountSelectProps {
value: string;
onChange: (value: string) => void;
disabled?: boolean;
+ id?: string;
+ 'aria-describedby'?: string;
+ 'aria-invalid'?: boolean;
}
-export default function AccountSelect({ accounts, value, onChange, disabled }: AccountSelectProps) {
+// with an id, the visible label of its FieldRow names it; without one it names itself
+export default function AccountSelect({ accounts, value, onChange, disabled, id, ...aria }: AccountSelectProps) {
const selected = accounts.find(account => account.id === value);
return (
<Select value={value} onValueChange={onChange as (value: string | null) => void} disabled={disabled}>
- <SelectTrigger className="h-(--control-h-lg) w-full" aria-label="Instagram account">
+ <SelectTrigger id={id} className="h-(--control-h-lg) w-full" aria-label={id ? undefined : 'Instagram account'} {...aria}>
{selected ? (
<span className="flex min-w-0 items-center gap-2">
- <AccountAvatar account={selected} size="xs" />
+ <AccountAvatar account={selected} size="xs" decorative />
<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>
@@ -29,7 +33,7 @@ export default function AccountSelect({ accounts, value, onChange, disabled }: A
{accounts.map(account => (
<SelectItem key={account.id} value={account.id}>
<span className="flex items-center gap-2">
- <AccountAvatar account={account} size="xs" />
+ <AccountAvatar account={account} size="xs" decorative />
<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>
diff --git a/frontend/src/components/ConfirmDialog.tsx b/frontend/src/components/ConfirmDialog.tsx
index f9a5c40..44df442 100644
--- a/frontend/src/components/ConfirmDialog.tsx
+++ b/frontend/src/components/ConfirmDialog.tsx
@@ -16,17 +16,19 @@ export interface ConfirmDialogProps {
cancelLabel?: React.ReactNode;
onConfirm: () => void;
busy?: boolean;
+ busyLabel?: string;
hold?: boolean;
icon?: React.ReactNode;
}
-// destructive actions use `hold` so a stray click cannot confirm them
+// destructive actions use `hold` so a stray click cannot confirm them; the button also confirms on a second press
export default function ConfirmDialog({
open,
onOpenChange,
title,
description,
confirmLabel = 'Confirm',
+ busyLabel = 'Working',
cancelLabel = 'Cancel',
onConfirm,
busy = false,
@@ -40,18 +42,19 @@ export default function ConfirmDialog({
{hold && <AlertDialogMedia>{icon}</AlertDialogMedia>}
<AlertDialogTitle>{title}</AlertDialogTitle>
{description && <AlertDialogDescription>{description}</AlertDialogDescription>}
+ {hold && <p className="text-small text-ink-muted">Hold the button, or press it twice, to confirm.</p>}
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={busy}>{cancelLabel}</AlertDialogCancel>
{hold ? (
<HoldToConfirmButton onConfirm={onConfirm} disabled={busy}>
{busy ? <Spinner className="size-4" /> : null}
- {busy ? 'Working' : `Hold to ${confirmLabel.toLowerCase()}`}
+ {busy ? busyLabel : confirmLabel}
</HoldToConfirmButton>
) : (
<AlertDialogAction onClick={onConfirm} disabled={busy}>
{busy && <Spinner className="size-4" />}
- {confirmLabel}
+ {busy ? busyLabel : confirmLabel}
</AlertDialogAction>
)}
</AlertDialogFooter>
diff --git a/frontend/src/components/DetailPanel.tsx b/frontend/src/components/DetailPanel.tsx
index 478a33b..e1a5071 100644
--- a/frontend/src/components/DetailPanel.tsx
+++ b/frontend/src/components/DetailPanel.tsx
@@ -1,6 +1,7 @@
import React from 'react';
import { AlertCircle } from 'lucide-react';
import { cn } from '@/lib/utils';
+import { fieldErrorId, fieldHintId } from '@/lib/fieldIds';
// sticky on wide screens, stacked below the main area on narrow ones
export interface DetailPanelProps {
@@ -31,14 +32,6 @@ export default function DetailPanel({ title, description, children, footer, clas
);
}
-export function fieldHintId(htmlFor: string): string {
- return `${htmlFor}-hint`;
-}
-
-export function fieldErrorId(htmlFor: string): string {
- return `${htmlFor}-error`;
-}
-
// Label, hint, error and control in one settings-style row. With htmlFor, the hint and error are wired to a single
// child control through aria-describedby and aria-invalid; group renders a fieldset for several controls.
export interface FieldRowProps {
diff --git a/frontend/src/components/HoldToConfirmButton.tsx b/frontend/src/components/HoldToConfirmButton.tsx
index 606760a..ffc6316 100644
--- a/frontend/src/components/HoldToConfirmButton.tsx
+++ b/frontend/src/components/HoldToConfirmButton.tsx
@@ -1,6 +1,7 @@
import React, { useEffect, useRef, useState } from 'react';
import { createHoldController, DEFAULT_HOLD_MS } from '@/lib/holdProgress';
import { cn } from '@/lib/utils';
+import LiveStatus from './LiveStatus';
const HOLD_KEYS = new Set([' ', 'Enter']);
@@ -10,21 +11,25 @@ export interface HoldToConfirmButtonProps {
onConfirm: () => void;
children?: React.ReactNode;
holdingLabel?: React.ReactNode;
+ armedLabel?: React.ReactNode;
duration?: number;
disabled?: boolean;
className?: string;
}
-// Destructive confirm that must be held, by pointer or by Space/Enter. A plain click never fires it.
+// Destructive confirm: hold it (pointer, Space or Enter), or press it twice. One stray press never fires it, and
+// pressing twice serves voice control and switch users, who cannot hold.
export default function HoldToConfirmButton({
onConfirm,
children,
holdingLabel = 'Keep holding',
+ armedLabel = 'Press again to confirm',
duration = DEFAULT_HOLD_MS,
disabled = false,
className,
}: HoldToConfirmButtonProps) {
const [progress, setProgress] = useState(0);
+ const [armedState, setArmed] = useState(false);
const controllerRef = useRef<HoldController | null>(null);
const confirmRef = useRef(onConfirm);
@@ -44,42 +49,67 @@ export default function HoldToConfirmButton({
if (disabled) controllerRef.current?.reset();
}, [disabled]);
+ // a disabled button is never armed, so a busy dialog cannot confirm on the press after it
+ const armed = armedState && !disabled;
+
const start = () => { if (!disabled) controllerRef.current?.start(); };
const cancel = () => controllerRef.current?.cancel();
const holding = progress > 0 && progress < 1;
+ // a short press arms the button and the next one confirms; a press that completed a hold is not counted again
+ const press = () => {
+ if (disabled || controllerRef.current?.completed) return;
+ if (armed) {
+ setArmed(false);
+ confirmRef.current?.();
+ return;
+ }
+ setArmed(true);
+ };
+
return (
- <button
- type="button"
- disabled={disabled}
- onPointerDown={e => { if (e.button === 0) { e.currentTarget.setPointerCapture?.(e.pointerId); start(); } }}
- onPointerUp={cancel}
- onPointerCancel={cancel}
- onPointerLeave={cancel}
- onKeyDown={e => {
- if (!HOLD_KEYS.has(e.key)) return;
- e.preventDefault();
- if (!e.repeat) start();
- }}
- onKeyUp={e => { if (HOLD_KEYS.has(e.key)) cancel(); }}
- onBlur={cancel}
- onContextMenu={e => e.preventDefault()}
- className={cn(
- 'relative inline-flex h-(--control-h) shrink-0 touch-none items-center justify-center gap-2 overflow-hidden rounded-control bg-danger-soft px-4 text-sm font-medium text-danger select-none',
- 'transition-colors duration-(--duration-fast) focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
- 'disabled:pointer-events-none disabled:opacity-50',
- className,
- )}
- >
- <span
- aria-hidden="true"
- className="absolute inset-y-0 left-0 bg-brand"
- style={{ width: `${progress * 100}%` }}
- />
- <span className={cn('relative z-10 flex items-center gap-2', progress > 0.5 && 'text-on-brand')}>
- {holding ? holdingLabel : children}
- </span>
- <span role="progressbar" aria-label="Hold progress" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(progress * 100)} className="sr-only" />
- </button>
+ <>
+ <button
+ type="button"
+ disabled={disabled}
+ onPointerDown={e => { if (e.button === 0) { e.currentTarget.setPointerCapture?.(e.pointerId); start(); } }}
+ onPointerUp={cancel}
+ onPointerCancel={cancel}
+ onPointerLeave={cancel}
+ onClick={e => { if (e.detail > 0) press(); }}
+ onKeyDown={e => {
+ if (e.key === 'Escape' && armed) { setArmed(false); return; }
+ if (!HOLD_KEYS.has(e.key)) return;
+ e.preventDefault();
+ if (!e.repeat) start();
+ }}
+ onKeyUp={e => {
+ if (!HOLD_KEYS.has(e.key)) return;
+ e.preventDefault();
+ const completed = controllerRef.current?.completed;
+ cancel();
+ if (!completed) press();
+ }}
+ onBlur={() => { cancel(); setArmed(false); }}
+ onContextMenu={e => e.preventDefault()}
+ className={cn(
+ 'relative inline-flex h-(--control-h) shrink-0 touch-none items-center justify-center gap-2 overflow-hidden rounded-control bg-danger-soft px-4 text-sm font-medium text-danger select-none',
+ 'transition-colors duration-(--duration-fast) focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
+ 'disabled:pointer-events-none disabled:opacity-50',
+ armed && 'bg-brand text-on-brand',
+ className,
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className="absolute inset-y-0 left-0 bg-brand"
+ style={{ width: `${progress * 100}%` }}
+ />
+ <span className={cn('relative z-10 flex items-center gap-2', progress > 0.5 && 'text-on-brand')}>
+ {holding ? holdingLabel : armed ? armedLabel : children}
+ </span>
+ </button>
+ <LiveStatus message={armed ? 'Press the button again to confirm, or press Escape to stop.' : ''} />
+ </>
);
}
diff --git a/frontend/src/components/SegmentedChoice.tsx b/frontend/src/components/SegmentedChoice.tsx
new file mode 100644
index 0000000..b1de108
--- /dev/null
+++ b/frontend/src/components/SegmentedChoice.tsx
@@ -0,0 +1,81 @@
+import React from 'react';
+import { cn } from '@/lib/utils';
+
+export interface SegmentedOption<T extends string> {
+ value: T;
+ label: React.ReactNode;
+ icon?: React.ReactNode;
+}
+
+export interface SegmentedChoiceProps<T extends string> {
+ name: string;
+ // given to the checked radio, or the first one, so a label or an error can move focus to the choice
+ id?: string;
+ options: SegmentedOption<T>[];
+ value: T;
+ onChange: (value: T) => void;
+ variant?: 'segmented' | 'tiles';
+ disabled?: boolean;
+ className?: string;
+ 'aria-describedby'?: string;
+}
+
+// one choice from a few, built on native radio buttons so arrow keys, form semantics and screen readers work without
+// ARIA; put it inside a FieldRow with `group` so its legend names the choice
+export default function SegmentedChoice<T extends string>({
+ name,
+ id,
+ options,
+ value,
+ onChange,
+ variant = 'segmented',
+ disabled = false,
+ className,
+ ...aria
+}: SegmentedChoiceProps<T>) {
+ return (
+ <div
+ className={cn(
+ variant === 'segmented'
+ ? 'flex h-(--control-h) w-full gap-0.5 rounded-control bg-surface-sunken p-1 sm:w-fit'
+ : 'grid grid-cols-3 gap-2',
+ className,
+ )}
+ >
+ {options.map((option, index) => {
+ const checked = option.value === value;
+ const focusTarget = checked || (index === 0 && !options.some(item => item.value === value));
+ return (
+ <label
+ key={option.value}
+ className={cn(
+ 'relative flex cursor-pointer items-center justify-center gap-1.5 text-sm font-medium transition-colors duration-(--duration-fast) select-none',
+ 'has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-ring has-[:disabled]:cursor-not-allowed has-[:disabled]:opacity-50',
+ '[&_svg]:shrink-0 [&_svg]:stroke-[1.75]',
+ variant === 'segmented'
+ ? cn('h-full flex-1 rounded-[calc(var(--radius-control)-2px)] px-3 [&_svg]:size-4', checked ? 'bg-surface-raised text-ink shadow-sm' : 'text-ink-muted hover:text-ink')
+ : cn(
+ 'flex-col rounded-field border px-2 py-3 text-center [&_svg]:size-5',
+ checked ? 'border-brand bg-brand-soft/50 text-brand-text' : 'border-line-control text-ink-muted hover:bg-surface-hover hover:text-ink',
+ ),
+ )}
+ >
+ <input
+ id={focusTarget ? id : undefined}
+ type="radio"
+ name={name}
+ value={option.value}
+ checked={checked}
+ disabled={disabled}
+ onChange={() => onChange(option.value)}
+ className="sr-only"
+ {...aria}
+ />
+ {option.icon}
+ <span className={variant === 'tiles' ? 'text-small font-semibold' : undefined}>{option.label}</span>
+ </label>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/frontend/src/features/accounts/AccountCard.tsx b/frontend/src/features/accounts/AccountCard.tsx
index 3252491..e8960ce 100644
--- a/frontend/src/features/accounts/AccountCard.tsx
+++ b/frontend/src/features/accounts/AccountCard.tsx
@@ -6,7 +6,8 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import { AccountAvatar } from '@/components/platform';
import { accountName, accountPath } from '@/lib/accounts';
import { cn } from '@/lib/utils';
-import { fmtNum, timeAgo } from '../../utils/formatters';
+import Num from '@/components/Num';
+import RelativeTime from '@/components/RelativeTime';
import { accountCardHandle, accountMetrics } from './accountManagerData';
import type { Platform } from '@shared/types/domain.ts';
import type { AppAccount } from '../../utils/formatters';
@@ -27,7 +28,12 @@ function CookieStatus({ hasCookie }: CookieStatusProps) {
if (hasCookie) {
return <span className="flex items-center gap-1 text-success"><Lock className="size-3" />Session cookie stored</span>;
}
- return <span className="flex items-center gap-1 text-danger"><Lock className="size-3" />Error: no session cookie. Remove and add the account again.</span>;
+ return (
+ <span className="flex items-center gap-1 text-danger">
+ <Lock className="size-3" aria-hidden="true" />
+ <span><span className="sr-only">Error: </span>No session cookie is stored. Remove the account and add it again with its cookie.</span>
+ </span>
+ );
}
export default function AccountCard({ acct, platform, refreshing, onRefresh, onDelete }: AccountCardProps) {
@@ -35,7 +41,7 @@ export default function AccountCard({ acct, platform, refreshing, onRefresh, onD
return (
<article className="flex flex-col gap-4 rounded-card border border-line bg-surface-raised p-4">
<div className="flex items-center gap-3">
- <AccountAvatar account={acct} size="lg" showPlatform />
+ <AccountAvatar account={acct} size="lg" showPlatform decorative />
<div className="min-w-0 flex-1">
<Link to={accountPath(acct)} className="block truncate text-sm font-semibold text-ink hover:underline">{accountName(acct)}</Link>
<p className="truncate text-caption text-ink-faint">{accountCardHandle(acct, platform)}</p>
@@ -52,23 +58,23 @@ export default function AccountCard({ acct, platform, refreshing, onRefresh, onD
{metrics.map(([label, value]) => (
<div key={label} className="flex flex-col items-center gap-0.5 px-2 text-center">
<dt className="text-caption text-ink-faint">{label}</dt>
- <dd className="font-heading text-base font-semibold text-ink tabular-nums">{fmtNum(value)}</dd>
+ <dd className="font-heading text-base font-semibold text-ink tabular-nums"><Num value={value} /></dd>
</div>
))}
</dl>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-caption text-ink-faint">
{platform === 'reddit' && <CookieStatus hasCookie={acct.hasCookie} />}
- {acct.lastUpdated && <span>Updated {timeAgo(acct.lastUpdated).toLowerCase()}</span>}
+ {acct.lastUpdated && <span>Updated <RelativeTime date={acct.lastUpdated} /></span>}
</div>
<div className="mt-auto flex gap-2">
<Button variant="outline" size="sm" className="flex-1" onClick={onRefresh} disabled={refreshing}>
<RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />
- {refreshing ? 'Refreshing' : 'Refresh'}
+ {refreshing ? 'Refreshing' : 'Refresh'}<span className="sr-only"> {accountName(acct)}</span>
</Button>
<Tooltip>
- <TooltipTrigger render={<Button variant="ghost" size="icon-sm" onClick={onDelete} aria-label={`Remove ${accountName(acct)}`} className="text-ink-muted hover:bg-danger-soft hover:text-danger" />}>
+ <TooltipTrigger render={<Button variant="ghost" size="icon-sm" onClick={onDelete} aria-label={`Remove ${accountName(acct)}`} className="ml-2 text-ink-muted hover:bg-danger-soft hover:text-danger" />}>
<Trash2 />
</TooltipTrigger>
<TooltipContent>Remove account</TooltipContent>
diff --git a/frontend/src/features/accounts/AccountManager.tsx b/frontend/src/features/accounts/AccountManager.tsx
index db37cfb..9e34b81 100644
--- a/frontend/src/features/accounts/AccountManager.tsx
+++ b/frontend/src/features/accounts/AccountManager.tsx
@@ -69,7 +69,8 @@ export default function AccountManager() {
onOpenChange={open => { if (!open) setPendingDelete(null); }}
title={pendingDelete ? `Remove ${accountName(pendingDelete)}?` : 'Remove account?'}
description="Its cached analytics are deleted. Scheduled posts for this account are removed with it. You can add the account again later."
- confirmLabel="Remove"
+ confirmLabel="Remove account"
+ busyLabel="Removing"
onConfirm={handleDelete}
busy={deleting}
hold
diff --git a/frontend/src/features/accounts/AccountSection.tsx b/frontend/src/features/accounts/AccountSection.tsx
index fa26903..6a36e3e 100644
--- a/frontend/src/features/accounts/AccountSection.tsx
+++ b/frontend/src/features/accounts/AccountSection.tsx
@@ -10,7 +10,7 @@ export interface AccountSectionProps {
section: AccountSectionInfo;
accounts: AppAccount[];
refreshingId: string | null;
- onRefresh: (id: string) => void;
+ onRefresh: (acct: AppAccount) => void;
onDelete: (acct: AppAccount) => void;
}
@@ -33,7 +33,7 @@ export default function AccountSection({ section, accounts, refreshingId, onRefr
acct={acct}
platform={section.key}
refreshing={refreshingId === acct.id}
- onRefresh={() => onRefresh(acct.id)}
+ onRefresh={() => onRefresh(acct)}
onDelete={() => onDelete(acct)}
/>
))}
diff --git a/frontend/src/features/accounts/AddAccountDialog.tsx b/frontend/src/features/accounts/AddAccountDialog.tsx
index 6072572..b8d52a7 100644
--- a/frontend/src/features/accounts/AddAccountDialog.tsx
+++ b/frontend/src/features/accounts/AddAccountDialog.tsx
@@ -1,4 +1,6 @@
-import React from 'react';
+import React, { useEffect, useRef } from 'react';
+import { AlertCircle } from 'lucide-react';
+import { Alert, AlertDescription } from '@/components/ui/alert';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import ChoiceCard from '@/components/ChoiceCard';
import InstagramTesterNotice from '@/components/InstagramTesterNotice';
@@ -18,16 +20,22 @@ export interface AddAccountDialogProps {
flow: AddAccountFlow;
}
+const STEP_DESCRIPTION: Record<Platform, string> = {
+ youtube: 'Find the channel to check it is the right one, then add it.',
+ instagram: 'Instagram opens so you can sign in and approve access.',
+ reddit: 'Add the username and the session cookie from your browser.',
+};
+
+// each card moves on to its platform's step, so these are plain buttons, not radios
function PlatformPicker({ onSelect }: PlatformPickerProps) {
return (
- <div role="radiogroup" aria-label="Platform" className="grid grid-cols-1 gap-3 sm:grid-cols-3">
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3" data-platform-picker>
{PLATFORM_CHOICES.map(choice => (
<ChoiceCard
key={choice.value}
icon={<choice.Icon />}
title={PLATFORM_META[choice.value].label}
description={choice.description}
- selected={false}
onSelect={() => onSelect(choice.value)}
/>
))}
@@ -37,13 +45,31 @@ function PlatformPicker({ onSelect }: PlatformPickerProps) {
export default function AddAccountDialog({ flow }: AddAccountDialogProps) {
const { platform, channel, reddit } = flow;
+ const contentRef = useRef<HTMLDivElement>(null);
+ const firstStep = useRef(true);
+
+ // the button that was pressed disappears with its step, so focus moves to the start of the new step
+ useEffect(() => {
+ if (firstStep.current) {
+ firstStep.current = false;
+ return;
+ }
+ const content = contentRef.current;
+ if (!content) return;
+ const frame = requestAnimationFrame(() => {
+ if (platform === 'instagram') document.getElementById('add-account-primary')?.focus();
+ else if (!platform) content.querySelector<HTMLButtonElement>('[data-platform-picker] button')?.focus();
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [platform]);
+
return (
<Dialog open={flow.dialogOpen} onOpenChange={open => { if (!open) flow.closeDialog(); }}>
- <DialogContent className="sm:max-w-xl">
+ <DialogContent ref={contentRef} className="sm:max-w-xl">
<DialogHeader>
- <DialogTitle>{platform ? platformChoiceTitle(platform) : 'Add an account'}</DialogTitle>
+ <DialogTitle>{platform ? platformChoiceTitle(platform) : 'Add account'}</DialogTitle>
<DialogDescription>
- {platform ? 'Fill in the details, review, then add.' : 'Choose the platform you want to track.'}
+ {platform ? STEP_DESCRIPTION[platform] : 'Choose the platform of the account.'}
</DialogDescription>
</DialogHeader>
@@ -56,13 +82,14 @@ export default function AddAccountDialog({ flow }: AddAccountDialogProps) {
onResolve={channel.handleResolve}
resolving={channel.resolving}
resolved={channel.resolved}
+ error={flow.errorFor('channel')}
/>
)}
{platform === 'instagram' && (
<div className="flex flex-col gap-4">
- <p className="text-sm text-ink-muted">
- We open Instagram so you can sign in and approve access. When you finish, Instagram sends you back here and the account appears in the list. The account must be an Instagram Business or Creator account; personal accounts cannot be connected.
+ <p className="max-w-prose text-body text-ink-muted">
+ When you finish, Instagram sends you back here and the account appears in the list. The account must be an Instagram Business or Creator account; personal accounts cannot be connected.
</p>
<InstagramTesterNotice />
</div>
@@ -73,11 +100,21 @@ export default function AddAccountDialog({ flow }: AddAccountDialogProps) {
username={reddit.username}
cookie={reddit.cookie}
onUsernameChange={reddit.setUsername}
+ onUsernameBlur={reddit.tidyUsername}
onCookieChange={reddit.setCookie}
onSubmit={flow.redditAdd.handleAddReddit}
+ usernameError={flow.errorFor('username')}
+ cookieError={flow.errorFor('cookie')}
/>
)}
+ {flow.submitError && (
+ <Alert variant="destructive" role="alert">
+ <AlertCircle />
+ <AlertDescription><span className="sr-only">Error: </span>{flow.submitError}</AlertDescription>
+ </Alert>
+ )}
+
<AddAccountFooter flow={flow} />
</DialogContent>
</Dialog>
diff --git a/frontend/src/features/accounts/AddAccountFooter.tsx b/frontend/src/features/accounts/AddAccountFooter.tsx
index db17d67..4678db0 100644
--- a/frontend/src/features/accounts/AddAccountFooter.tsx
+++ b/frontend/src/features/accounts/AddAccountFooter.tsx
@@ -9,8 +9,9 @@ export interface AddAccountFooterProps {
flow: AddAccountFlow;
}
+// the main button stays enabled: pressing it with a field missing says which one, instead of greying out silently
export default function AddAccountFooter({ flow }: AddAccountFooterProps) {
- const { platform, channel, reddit, channelAdd, redditAdd, instagram } = flow;
+ const { platform, channelAdd, redditAdd, instagram } = flow;
const { adding } = channelAdd;
const { connecting } = instagram;
const { addingReddit } = redditAdd;
@@ -25,19 +26,19 @@ export default function AddAccountFooter({ flow }: AddAccountFooterProps) {
) : null}
<Button variant="outline" onClick={flow.closeDialog}>Cancel</Button>
{platform === 'youtube' && (
- <Button onClick={channelAdd.handleAdd} disabled={!channel.input.trim() || adding}>
+ <Button onClick={channelAdd.handleAdd} disabled={adding}>
{adding && <Spinner className="size-4" />}
{adding ? 'Adding channel' : 'Add channel'}
</Button>
)}
{platform === 'instagram' && (
- <Button onClick={instagram.handleConnectInstagram} disabled={connecting}>
+ <Button id="add-account-primary" onClick={instagram.handleConnectInstagram} disabled={connecting}>
{connecting ? <Spinner className="size-4" /> : <ExternalLink data-icon="inline-start" />}
{connecting ? 'Opening Instagram' : 'Continue to Instagram'}
</Button>
)}
{platform === 'reddit' && (
- <Button onClick={redditAdd.handleAddReddit} disabled={!reddit.username.trim() || !reddit.cookie.trim() || addingReddit}>
+ <Button type="submit" form="add-account-form" disabled={addingReddit}>
{addingReddit && <Spinner className="size-4" />}
{addingReddit ? 'Adding account' : 'Add Reddit account'}
</Button>
diff --git a/frontend/src/features/accounts/RedditAccountFields.tsx b/frontend/src/features/accounts/RedditAccountFields.tsx
index 18ec202..bfe38e0 100644
--- a/frontend/src/features/accounts/RedditAccountFields.tsx
+++ b/frontend/src/features/accounts/RedditAccountFields.tsx
@@ -8,28 +8,38 @@ export interface RedditAccountFieldsProps {
username: string;
cookie: string;
onUsernameChange: (value: string) => void;
+ onUsernameBlur: () => void;
onCookieChange: (value: string) => void;
onSubmit: () => void;
+ usernameError?: string;
+ cookieError?: string;
}
-export default function RedditAccountFields({ username, cookie, onUsernameChange, onCookieChange, onSubmit }: RedditAccountFieldsProps) {
+// a real form, so Enter submits once and the busy guard in the add step stops a second request
+export default function RedditAccountFields({
+ username, cookie, onUsernameChange, onUsernameBlur, onCookieChange, onSubmit, usernameError, cookieError,
+}: RedditAccountFieldsProps) {
return (
- <div className="flex flex-col gap-4">
- <FieldRow label="Username" htmlFor="reddit-user">
- <div className="relative">
- <span className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-sm font-medium text-ink-faint">u/</span>
- <Input
- id="reddit-user"
- className="h-(--control-h-lg) pl-8"
- value={username}
- onChange={e => onUsernameChange(e.target.value)}
- placeholder="username"
- onKeyDown={e => e.key === 'Enter' && onSubmit()}
- autoFocus
- />
- </div>
+ <form
+ id="add-account-form"
+ noValidate
+ onSubmit={e => { e.preventDefault(); onSubmit(); }}
+ className="flex flex-col gap-4"
+ >
+ <FieldRow label="Username" htmlFor="reddit-user" hint="The name, u/name or the address of the profile." error={usernameError}>
+ <Input
+ id="reddit-user"
+ className="h-(--control-h-lg)"
+ value={username}
+ onChange={e => onUsernameChange(e.target.value)}
+ onBlur={onUsernameBlur}
+ placeholder="u/username"
+ autoComplete="off"
+ spellCheck={false}
+ autoFocus
+ />
</FieldRow>
- <FieldRow label="Session cookie" hint="We store it on the server and never show it again." htmlFor="reddit-cookie">
+ <FieldRow label="Session cookie" hint="Stored on the server and never shown again." htmlFor="reddit-cookie" error={cookieError}>
<Input
id="reddit-cookie"
type="password"
@@ -37,7 +47,7 @@ export default function RedditAccountFields({ username, cookie, onUsernameChange
value={cookie}
onChange={e => onCookieChange(e.target.value)}
placeholder="reddit_session value"
- onKeyDown={e => e.key === 'Enter' && onSubmit()}
+ autoComplete="off"
/>
</FieldRow>
<Alert>
@@ -47,6 +57,8 @@ export default function RedditAccountFields({ username, cookie, onUsernameChange
<strong className="font-semibold text-ink">reddit_session</strong>.
</AlertDescription>
</Alert>
- </div>
+ {/* lets Enter in either field submit the form */}
+ <button type="submit" hidden aria-hidden="true" tabIndex={-1} />
+ </form>
);
}
diff --git a/frontend/src/features/accounts/YouTubeAccountFields.tsx b/frontend/src/features/accounts/YouTubeAccountFields.tsx
index b852b8d..da5aa0e 100644
--- a/frontend/src/features/accounts/YouTubeAccountFields.tsx
+++ b/frontend/src/features/accounts/YouTubeAccountFields.tsx
@@ -18,16 +18,17 @@ export interface YouTubeAccountFieldsProps {
onResolve: () => void;
resolving: boolean;
resolved: YouTubeChannelData | null;
+ error?: string;
}
function ResolvedChannel({ channel }: ResolvedChannelProps) {
return (
<div className="flex items-center gap-3 rounded-card border border-success/30 bg-success-soft p-3">
- <AccountAvatar account={{ platform: 'youtube', title: channel.title, thumbnail: channel.thumbnails?.medium || channel.thumbnails?.default }} size="lg" />
+ <AccountAvatar account={{ platform: 'youtube', title: channel.title, thumbnail: channel.thumbnails?.medium || channel.thumbnails?.default }} size="lg" decorative />
<div className="min-w-0 flex-1">
<p className="flex items-center gap-1.5 text-sm font-semibold text-ink">
<span className="truncate">{channel.title}</span>
- <CheckCircle2 className="size-4 shrink-0 text-success" aria-label="Channel found" />
+ <CheckCircle2 className="size-4 shrink-0 text-success" aria-hidden="true" />
</p>
<p className="text-caption text-ink-muted">{channel.customUrl}</p>
{channel.subscriberCount != null && (
@@ -40,31 +41,35 @@ function ResolvedChannel({ channel }: ResolvedChannelProps) {
);
}
-export default function YouTubeAccountFields({ input, onInputChange, onResolve, resolving, resolved }: YouTubeAccountFieldsProps) {
+// Enter or Find looks the channel up; the dialog's Add channel button adds it
+export default function YouTubeAccountFields({ input, onInputChange, onResolve, resolving, resolved, error }: YouTubeAccountFieldsProps) {
return (
- <div className="flex flex-col gap-4">
- <FieldRow label="Channel" hint="A channel URL, an @handle or a channel ID that starts with UC." htmlFor="yt-channel">
- <div className="flex gap-2">
- <div className="relative flex-1">
- <Link2 className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-ink-faint" />
- <Input
- id="yt-channel"
- className="h-(--control-h-lg) pl-9"
- value={input}
- onChange={e => onInputChange(e.target.value)}
- placeholder="youtube.com/@channel"
- onKeyDown={e => e.key === 'Enter' && onResolve()}
- autoFocus
- />
- </div>
- <Button variant="outline" size="lg" onClick={onResolve} disabled={resolving || !input.trim()}>
- {resolving ? <Spinner className="size-4" /> : <Search data-icon="inline-start" />}
- Find
- </Button>
+ <form noValidate onSubmit={e => { e.preventDefault(); onResolve(); }} className="flex flex-col gap-4">
+ <FieldRow label="Channel" hint="A channel link, an @handle or a channel ID that starts with UC." htmlFor="yt-channel" error={error}>
+ <div className="relative">
+ <Link2 className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-ink-faint" aria-hidden="true" />
+ <Input
+ id="yt-channel"
+ className="h-(--control-h-lg) pl-9"
+ value={input}
+ onChange={e => onInputChange(e.target.value)}
+ placeholder="youtube.com/@channel"
+ autoComplete="off"
+ spellCheck={false}
+ autoFocus
+ />
</div>
</FieldRow>
+ <Button type="submit" variant="outline" className="self-start" disabled={resolving}>
+ {resolving ? <Spinner className="size-4" /> : <Search data-icon="inline-start" />}
+ {resolving ? 'Finding the channel' : 'Find the channel'}
+ </Button>
- {resolved && <ResolvedChannel channel={resolved} />}
- </div>
+ {/* mounted before a result, so finding the channel is announced */}
+ <div role="status" aria-live="polite">
+ {resolved && <ResolvedChannel channel={resolved} />}
+ {resolved && <span className="sr-only">Found {resolved.title}. Add it with the Add channel button.</span>}
+ </div>
+ </form>
);
}
diff --git a/frontend/src/features/accounts/accountManagerData.ts b/frontend/src/features/accounts/accountManagerData.ts
index b17e657..0751690 100644
--- a/frontend/src/features/accounts/accountManagerData.ts
+++ b/frontend/src/features/accounts/accountManagerData.ts
@@ -84,3 +84,28 @@ export function accountCardHandle(account: AccountFields, platform: Platform): s
export function visibleSections(groups: Record<Platform, unknown[]>): AccountSectionInfo[] {
return ACCOUNT_SECTIONS.filter(section => groups[section.key].length > 0);
}
+
+// people paste "u/name", "@name" or their profile address; the Worker keeps the same name
+export function redditUsername(input: string): string {
+ const text = input.trim();
+ const fromUrl = text.match(/reddit\.com\/(?:user|u)\/([^/?#\s]+)/i);
+ return (fromUrl ? fromUrl[1] : text).replace(/^\/?u\//i, '').replace(/^@/, '').trim();
+}
+
+export type AddAccountField = 'channel' | 'username' | 'cookie';
+
+export interface AddAccountProblem {
+ field: AddAccountField;
+ message: string;
+}
+
+// what is missing before an account can be added, or null
+export function redditFieldsProblem(username: string, cookie: string): AddAccountProblem | null {
+ if (!redditUsername(username)) return { field: 'username', message: 'Enter the Reddit username, such as u/name.' };
+ if (!cookie.trim()) return { field: 'cookie', message: 'Paste the reddit_session cookie value. The steps below show where to find it.' };
+ return null;
+}
+
+export function channelFieldProblem(input: string): AddAccountProblem | null {
+ return input.trim() ? null : { field: 'channel', message: 'Paste a channel link, an @handle or a channel ID that starts with UC.' };
+}
diff --git a/frontend/src/features/accounts/useAccountDelete.ts b/frontend/src/features/accounts/useAccountDelete.ts
index f6b9b7e..cc059a3 100644
--- a/frontend/src/features/accounts/useAccountDelete.ts
+++ b/frontend/src/features/accounts/useAccountDelete.ts
@@ -11,7 +11,7 @@ export function useAccountDelete({ showToast, loadAccounts }: AccountActionDeps)
const [deleting, setDeleting] = useState(false);
const handleDelete = async () => {
- if (!pendingDelete) return;
+ if (!pendingDelete || deleting) return;
setDeleting(true);
try {
await api.deleteAccount(pendingDelete.id);
@@ -19,7 +19,7 @@ export function useAccountDelete({ showToast, loadAccounts }: AccountActionDeps)
setPendingDelete(null);
loadAccounts();
} catch (err) {
- showToast(`Couldn't remove the account. ${(err as Error).message}`, 'error');
+ showToast(`Couldn't remove ${accountName(pendingDelete)}. ${(err as Error).message}`, 'error');
} finally {
setDeleting(false);
}
diff --git a/frontend/src/features/accounts/useAccountRefresh.ts b/frontend/src/features/accounts/useAccountRefresh.ts
index 7f0a5ee..50ac1b6 100644
--- a/frontend/src/features/accounts/useAccountRefresh.ts
+++ b/frontend/src/features/accounts/useAccountRefresh.ts
@@ -1,32 +1,36 @@
import { useState } from 'react';
+import { accountName } from '@/lib/accounts';
import { api } from '../../services/api';
+import type { AppAccount } from '../../utils/formatters';
import type { AccountActionDeps } from './useAccountDelete';
// one id for both buttons: 'all' for refresh-all, else the account id
export function useAccountRefresh({ showToast, loadAccounts }: AccountActionDeps) {
const [refreshingId, setRefreshingId] = useState<string | null>(null);
- const refreshOne = async (id: string) => {
- setRefreshingId(id);
+ const refreshOne = async (account: AppAccount) => {
+ if (refreshingId) return;
+ setRefreshingId(account.id);
try {
- await api.refreshAccount(id);
- showToast('Account refreshed');
+ await api.refreshAccount(account.id);
+ showToast(`${accountName(account)} refreshed`);
loadAccounts();
} catch (err) {
- showToast(`Refresh failed. ${(err as Error).message}`, 'error');
+ showToast(`Couldn't refresh ${accountName(account)}. ${(err as Error).message}`, 'error');
} finally {
setRefreshingId(null);
}
};
const refreshAll = async () => {
+ if (refreshingId) return;
setRefreshingId('all');
try {
await api.refreshAll();
showToast('All accounts refreshed');
loadAccounts();
} catch (err) {
- showToast(`Refresh failed. ${(err as Error).message}`, 'error');
+ showToast(`Couldn't refresh your accounts. ${(err as Error).message}`, 'error');
} finally {
setRefreshingId(null);
}
diff --git a/frontend/src/features/accounts/useAddAccount.ts b/frontend/src/features/accounts/useAddAccount.ts
index bbfada8..6d91c00 100644
--- a/frontend/src/features/accounts/useAddAccount.ts
+++ b/frontend/src/features/accounts/useAddAccount.ts
@@ -1,5 +1,7 @@
import { useState } from 'react';
import { api } from '../../services/api';
+import { channelFieldProblem, redditFieldsProblem, redditUsername } from './accountManagerData';
+import type { AddAccountField, AddAccountProblem } from './accountManagerData';
import type { AppContextValue } from '../../context/AppContext';
import type { Platform } from '@shared/types/domain.ts';
import type { YouTubeChannelData } from '@shared/types/youtube.ts';
@@ -7,12 +9,21 @@ import type { AccountActionDeps } from './useAccountDelete';
type ShowToast = AppContextValue['showToast'];
+const FIELD_IDS: Record<AddAccountField, string> = { channel: 'yt-channel', username: 'reddit-user', cookie: 'reddit-cookie' };
+
interface AddStepDeps {
showToast: ShowToast;
finishAdding: () => void;
+ setProblem: (problem: AddAccountProblem | null) => void;
+ setSubmitError: (message: string | null) => void;
+}
+
+// a problem is shown under its field and focus moves there, so the person sees what to fix without a toast
+function focusProblem(problem: AddAccountProblem) {
+ document.getElementById(FIELD_IDS[problem.field])?.focus();
}
-function useChannelLookup(showToast: ShowToast) {
+function useChannelLookup(setProblem: AddStepDeps['setProblem']) {
const [input, setInput] = useState('');
const [resolving, setResolving] = useState(false);
const [resolved, setResolved] = useState<YouTubeChannelData | null>(null);
@@ -20,17 +31,27 @@ function useChannelLookup(showToast: ShowToast) {
const changeInput = (value: string) => {
setInput(value);
setResolved(null);
+ setProblem(null);
};
const handleResolve = async () => {
- if (!input.trim()) return;
+ if (resolving) return;
+ const problem = channelFieldProblem(input);
+ if (problem) {
+ setProblem(problem);
+ focusProblem(problem);
+ return;
+ }
setResolving(true);
setResolved(null);
try {
const res = await api.resolveChannel(input.trim());
setResolved(res.data || res);
+ setProblem(null);
} catch (err) {
- showToast(`Couldn't find that channel. ${(err as Error).message}`, 'error');
+ const found = { field: 'channel' as const, message: `Couldn't find that channel. ${(err as Error).message}` };
+ setProblem(found);
+ focusProblem(found);
} finally {
setResolving(false);
}
@@ -45,30 +66,48 @@ function useChannelLookup(showToast: ShowToast) {
return { input, resolving, resolved, changeInput, handleResolve, clearResolved, reset };
}
-function useRedditFields() {
- const [username, setUsername] = useState('');
- const [cookie, setCookie] = useState('');
+function useRedditFields(setProblem: AddStepDeps['setProblem']) {
+ const [username, setUsernameValue] = useState('');
+ const [cookie, setCookieValue] = useState('');
+
+ const setUsername = (value: string) => {
+ setUsernameValue(value);
+ setProblem(null);
+ };
+ const setCookie = (value: string) => {
+ setCookieValue(value);
+ setProblem(null);
+ };
+ // a pasted profile address or u/name is shown as the plain name once the field is left
+ const tidyUsername = () => setUsernameValue(current => redditUsername(current));
const reset = () => {
- setUsername('');
- setCookie('');
+ setUsernameValue('');
+ setCookieValue('');
};
- return { username, cookie, setUsername, setCookie, reset };
+ return { username, cookie, setUsername, setCookie, tidyUsername, reset };
}
-function useChannelAdd({ input, showToast, finishAdding }: AddStepDeps & { input: string }) {
+function useChannelAdd({ input, showToast, finishAdding, setProblem, setSubmitError }: AddStepDeps & { input: string }) {
const [adding, setAdding] = useState(false);
const handleAdd = async () => {
- if (!input.trim()) return;
+ if (adding) return;
+ const problem = channelFieldProblem(input);
+ if (problem) {
+ setProblem(problem);
+ focusProblem(problem);
+ return;
+ }
setAdding(true);
+ setSubmitError(null);
try {
await api.addAccount(input.trim());
showToast('YouTube channel added');
finishAdding();
} catch (err) {
- showToast(`Couldn't add the channel. ${(err as Error).message}`, 'error');
+ setSubmitError(`Couldn't add the channel. ${(err as Error).message}`);
} finally {
setAdding(false);
}
@@ -77,18 +116,26 @@ function useChannelAdd({ input, showToast, finishAdding }: AddStepDeps & { input
return { adding, handleAdd };
}
-function useRedditAdd({ username, cookie, showToast, finishAdding }: AddStepDeps & { username: string; cookie: string }) {
+function useRedditAdd({ username, cookie, showToast, finishAdding, setProblem, setSubmitError }: AddStepDeps & { username: string; cookie: string }) {
const [addingReddit, setAddingReddit] = useState(false);
const handleAddReddit = async () => {
- if (!username.trim() || !cookie.trim()) return;
+ if (addingReddit) return;
+ const problem = redditFieldsProblem(username, cookie);
+ if (problem) {
+ setProblem(problem);
+ focusProblem(problem);
+ return;
+ }
setAddingReddit(true);
+ setSubmitError(null);
+ const name = redditUsername(username);
try {
- await api.addRedditAccount(username.trim(), cookie.trim());
- showToast('Reddit account added');
+ await api.addRedditAccount(name, cookie.trim());
+ showToast(`u/${name} added`);
finishAdding();
} catch (err) {
- showToast(`Couldn't add the Reddit account. ${(err as Error).message}`, 'error');
+ setSubmitError(`Couldn't add u/${name}. ${(err as Error).message}`);
} finally {
setAddingReddit(false);
}
@@ -97,17 +144,19 @@ function useRedditAdd({ username, cookie, showToast, finishAdding }: AddStepDeps
return { addingReddit, handleAddReddit };
}
-function useInstagramConnect(showToast: ShowToast) {
+function useInstagramConnect(setSubmitError: AddStepDeps['setSubmitError']) {
const [connecting, setConnecting] = useState(false);
const handleConnectInstagram = async () => {
+ if (connecting) return;
setConnecting(true);
+ setSubmitError(null);
try {
const { url } = await api.getInstagramAuthUrl();
// same tab: instagram redirects back to /accounts?ig_connected=true
window.location.href = url;
} catch (err) {
- showToast(`Couldn't start Instagram sign-in. ${(err as Error).message}`, 'error');
+ setSubmitError(`Couldn't start Instagram sign-in. ${(err as Error).message}`);
setConnecting(false);
}
};
@@ -117,9 +166,17 @@ function useInstagramConnect(showToast: ShowToast) {
export function useAddAccount({ showToast, loadAccounts }: AccountActionDeps) {
const [dialogOpen, setDialogOpen] = useState(false);
- const [platform, setPlatform] = useState<Platform | null>(null);
- const channel = useChannelLookup(showToast);
- const reddit = useRedditFields();
+ const [platform, setPlatformValue] = useState<Platform | null>(null);
+ const [problem, setProblem] = useState<AddAccountProblem | null>(null);
+ const [submitError, setSubmitError] = useState<string | null>(null);
+ const channel = useChannelLookup(setProblem);
+ const reddit = useRedditFields(setProblem);
+
+ const setPlatform = (value: Platform | null) => {
+ setPlatformValue(value);
+ setProblem(null);
+ setSubmitError(null);
+ };
const closeDialog = () => {
setDialogOpen(false);
@@ -144,13 +201,15 @@ export function useAddAccount({ showToast, loadAccounts }: AccountActionDeps) {
setDialogOpen(true);
};
- const channelAdd = useChannelAdd({ input: channel.input, showToast, finishAdding });
- const redditAdd = useRedditAdd({ username: reddit.username, cookie: reddit.cookie, showToast, finishAdding });
- const instagram = useInstagramConnect(showToast);
+ const deps = { showToast, finishAdding, setProblem, setSubmitError };
+ const channelAdd = useChannelAdd({ input: channel.input, ...deps });
+ const redditAdd = useRedditAdd({ username: reddit.username, cookie: reddit.cookie, ...deps });
+ const instagram = useInstagramConnect(setSubmitError);
+ const errorFor = (field: AddAccountField) => (problem?.field === field ? problem.message : undefined);
return {
dialogOpen, setDialogOpen, platform, setPlatform, closeDialog, goBack, openWithPlatform,
- channel, reddit, channelAdd, redditAdd, instagram,
+ channel, reddit, channelAdd, redditAdd, instagram, errorFor, submitError,
};
}
diff --git a/frontend/src/features/analytics/tracked/AddTrackedDialog.tsx b/frontend/src/features/analytics/tracked/AddTrackedDialog.tsx
index 62649c4..38d45bc 100644
--- a/frontend/src/features/analytics/tracked/AddTrackedDialog.tsx
+++ b/frontend/src/features/analytics/tracked/AddTrackedDialog.tsx
@@ -1,3 +1,5 @@
+import { AlertCircle } from 'lucide-react';
+import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
@@ -10,21 +12,21 @@ import type { AppAccount } from '../../../utils/formatters';
import type { AddTracked } from './useAddTracked';
interface LinkStatusProps {
- url: string;
detectedType: 'reddit' | 'youtube' | null;
}
-function LinkStatus({ url, detectedType }: LinkStatusProps) {
- if (detectedType) {
- return (
- <p className="flex items-center gap-1.5 text-caption text-success">
- <PlatformBadge platform={detectedType} className="h-5" />
- {detectedType === 'youtube' ? 'YouTube video found' : 'Reddit post found'}
- </p>
- );
- }
- if (!url.trim()) return null;
- return <p className="text-caption text-danger">Error: only Reddit posts and YouTube videos can be tracked.</p>;
+// a found link is confirmed as soon as it is pasted; the region stays mounted so the confirmation is announced
+function LinkStatus({ detectedType }: LinkStatusProps) {
+ return (
+ <div role="status" aria-live="polite">
+ {detectedType && (
+ <p className="flex items-center gap-1.5 text-small text-success">
+ <PlatformBadge platform={detectedType} className="h-5" />
+ {detectedType === 'youtube' ? 'YouTube video found' : 'Reddit post found'}
+ </p>
+ )}
+ </div>
+ );
}
export interface AddTrackedDialogProps {
@@ -47,11 +49,21 @@ export default function AddTrackedDialog({ add, redditAccounts, categories }: Ad
<DialogTitle>Track content</DialogTitle>
<DialogDescription>Paste a Reddit post or a YouTube video or Shorts link.</DialogDescription>
</DialogHeader>
- <form id="track-form" onSubmit={add.handleAdd} className="flex flex-col gap-5">
- <FieldRow label="Link" htmlFor="track-url">
- <Input id="track-url" className="h-(--control-h-lg)" placeholder="https://" value={url} onChange={e => add.setDraftField('url', e.target.value)} autoFocus />
- <LinkStatus url={url} detectedType={detectedType} />
+ <form id="track-form" onSubmit={add.handleAdd} noValidate className="flex flex-col gap-5">
+ <FieldRow label="Link" htmlFor="track-url" error={add.urlError ?? undefined}>
+ <Input
+ id="track-url"
+ type="url"
+ inputMode="url"
+ className="h-(--control-h-lg)"
+ placeholder="https://"
+ value={url}
+ onChange={e => add.setDraftField('url', e.target.value)}
+ onBlur={add.checkUrl}
+ autoFocus
+ />
</FieldRow>
+ <LinkStatus detectedType={detectedType} />
{detectedType === 'reddit' && (
<FieldRow label="Fetch with account" hint="A session cookie helps Reddit accept requests from the server." htmlFor="track-account">
@@ -68,20 +80,27 @@ export default function AddTrackedDialog({ add, redditAccounts, categories }: Ad
)}
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
- <FieldRow label="Label" hint="Optional" htmlFor="track-label">
+ <FieldRow label="Label" optional htmlFor="track-label">
<Input id="track-label" placeholder="Launch teaser" value={draft.label} onChange={e => add.setDraftField('label', e.target.value)} />
</FieldRow>
- <FieldRow label="Category" hint="Optional" htmlFor="track-category">
+ <FieldRow label="Category" optional htmlFor="track-category">
<Input id="track-category" placeholder="Campaign A" value={draft.category} onChange={e => add.setDraftField('category', e.target.value)} />
<CategoryPicker categories={categories} onPick={category => add.setDraftField('category', category)} />
</FieldRow>
</div>
+
+ {add.submitError && (
+ <Alert variant="destructive" role="alert">
+ <AlertCircle />
+ <AlertDescription><span className="sr-only">Error: </span>{add.submitError}</AlertDescription>
+ </Alert>
+ )}
</form>
<DialogFooter>
- <Button variant="outline" onClick={() => add.setOpen(false)} disabled={adding}>Cancel</Button>
- <Button type="submit" form="track-form" disabled={adding || !url.trim() || !detectedType}>
+ <Button variant="outline" onClick={() => add.handleOpenChange(false)} disabled={adding}>Cancel</Button>
+ <Button type="submit" form="track-form" disabled={adding}>
{adding && <Spinner className="size-4" />}
- {adding ? 'Fetching details' : 'Track'}
+ {adding ? 'Fetching details' : 'Track content'}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/frontend/src/features/analytics/tracked/BulkCategoryBar.tsx b/frontend/src/features/analytics/tracked/BulkCategoryBar.tsx
index 1bd03da..31b0f91 100644
--- a/frontend/src/features/analytics/tracked/BulkCategoryBar.tsx
+++ b/frontend/src/features/analytics/tracked/BulkCategoryBar.tsx
@@ -1,6 +1,8 @@
import { Tag } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
+import { Spinner } from '@/components/ui/spinner';
+import { fieldErrorId } from '@/lib/fieldIds';
import type { BulkCategory } from './useBulkCategory';
export interface BulkCategoryBarProps {
@@ -13,22 +15,33 @@ export default function BulkCategoryBar({ selectedCount, bulk, onClear }: BulkCa
return (
<form
onSubmit={bulk.handleBulkCategory}
+ noValidate
className="sticky top-[calc(var(--topbar-h)+0.75rem)] z-10 flex flex-wrap items-center gap-3 rounded-card border border-brand/30 bg-surface-raised px-4 py-3 shadow-md"
aria-label="Bulk actions"
>
- <span className="text-sm font-medium text-ink">{selectedCount} selected</span>
- <div className="flex min-w-0 flex-1 items-center gap-2">
- <Tag className="size-4 shrink-0 text-ink-faint" />
+ {/* the bar mounts with the first selection, so the count is announced as it changes after that */}
+ <span className="text-sm font-medium text-ink" role="status" aria-live="polite">{selectedCount} selected</span>
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
+ <Tag className="size-4 shrink-0 text-ink-faint" aria-hidden="true" />
+ <label htmlFor="bulk-category" className="text-sm font-medium text-ink">Category</label>
<Input
- placeholder="Category name"
- aria-label="Category to assign"
+ id="bulk-category"
+ placeholder="Campaign A"
value={bulk.bulkCategory}
onChange={e => bulk.setBulkCategory(e.target.value)}
+ aria-invalid={bulk.categoryError ? true : undefined}
+ aria-describedby={bulk.categoryError ? fieldErrorId('bulk-category') : undefined}
className="h-(--control-h-sm) max-w-xs"
/>
- <Button type="submit" size="sm" disabled={!bulk.bulkCategory.trim()}>Assign category</Button>
+ <Button type="submit" size="sm" disabled={bulk.assigning}>
+ {bulk.assigning && <Spinner className="size-4" />}
+ {bulk.assigning ? 'Assigning' : 'Assign category'}
+ </Button>
+ {bulk.categoryError && (
+ <p id={fieldErrorId('bulk-category')} className="basis-full text-sm text-danger"><span className="sr-only">Error: </span>{bulk.categoryError}</p>
+ )}
</div>
- <Button type="button" size="sm" variant="ghost" onClick={onClear}>Clear selection</Button>
+ <Button type="button" size="sm" variant="ghost" onClick={onClear} disabled={bulk.assigning}>Clear selection</Button>
</form>
);
}
diff --git a/frontend/src/features/analytics/tracked/EditTrackedDialog.tsx b/frontend/src/features/analytics/tracked/EditTrackedDialog.tsx
index b571849..28c494d 100644
--- a/frontend/src/features/analytics/tracked/EditTrackedDialog.tsx
+++ b/frontend/src/features/analytics/tracked/EditTrackedDialog.tsx
@@ -1,3 +1,5 @@
+import { AlertCircle } from 'lucide-react';
+import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
@@ -17,17 +19,17 @@ export default function EditTrackedDialog({ editor, categories }: EditTrackedDia
const { editItem, fields, setField, saving } = editor;
const showRedditFields = editItem && isRedditItem(editItem);
return (
- <Dialog open={Boolean(editItem)} onOpenChange={open => !open && editor.setEditItem(null)}>
+ <Dialog open={Boolean(editItem)} onOpenChange={open => { if (!open && !saving) editor.setEditItem(null); }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Edit tracked item</DialogTitle>
<DialogDescription className="line-clamp-2">{editItem?.title || editItem?.url}</DialogDescription>
</DialogHeader>
- <form id="edit-tracked-form" onSubmit={editor.handleSaveEdit} className="flex flex-col gap-5">
- <FieldRow label="Label" htmlFor="edit-label">
+ <form id="edit-tracked-form" onSubmit={editor.handleSaveEdit} noValidate className="flex flex-col gap-5">
+ <FieldRow label="Label" optional htmlFor="edit-label">
<Input id="edit-label" value={fields.label} onChange={e => setField('label', e.target.value)} placeholder="Launch teaser" />
</FieldRow>
- <FieldRow label="Category" htmlFor="edit-category">
+ <FieldRow label="Category" optional htmlFor="edit-category">
<Input id="edit-category" value={fields.category} onChange={e => setField('category', e.target.value)} placeholder="Campaign A" />
<CategoryPicker categories={categories} onPick={category => setField('category', category)} />
</FieldRow>
@@ -35,14 +37,23 @@ export default function EditTrackedDialog({ editor, categories }: EditTrackedDia
{showRedditFields && (
<FieldRow
label="Views"
- hint="Reddit does not report views through its API. Copy the number from the post's insights page. Leave empty to remove it."
+ optional
+ hint="Reddit does not report views through its API. Copy the number from the post's insights page, such as 12,500 or 12.5K. Leave empty to remove it."
htmlFor="edit-views"
+ error={editor.viewsError ?? undefined}
>
- <Input id="edit-views" type="number" min="0" step="1" inputMode="numeric" value={fields.views} onChange={e => setField('views', e.target.value)} placeholder="12500" />
+ <Input id="edit-views" type="text" inputMode="numeric" value={fields.views} onChange={e => setField('views', e.target.value)} onBlur={editor.tidyViews} placeholder="12500" />
</FieldRow>
)}
{showRedditFields && <TrackedImageField editor={editor} />}
+
+ {editor.saveError && (
+ <Alert variant="destructive" role="alert">
+ <AlertCircle />
+ <AlertDescription><span className="sr-only">Error: </span>{editor.saveError}</AlertDescription>
+ </Alert>
+ )}
</form>
<DialogFooter>
<Button variant="outline" onClick={() => editor.setEditItem(null)} disabled={saving}>Cancel</Button>
diff --git a/frontend/src/features/analytics/tracked/TrackedImageField.tsx b/frontend/src/features/analytics/tracked/TrackedImageField.tsx
index 7063045..0f9518d 100644
--- a/frontend/src/features/analytics/tracked/TrackedImageField.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedImageField.tsx
@@ -1,3 +1,4 @@
+import { useEffect, useRef } from 'react';
import { Upload, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
@@ -21,7 +22,7 @@ function UploadImageButton({ uploading, disabled, onClick }: UploadImageButtonPr
);
}
return (
- <Button type="button" variant="outline" className="justify-start" onClick={onClick} disabled={disabled}>
+ <Button id="tracked-image-upload" type="button" variant="outline" className="justify-start" onClick={onClick} disabled={disabled}>
<Upload data-icon="inline-start" />
Upload image
</Button>
@@ -34,17 +35,24 @@ export interface TrackedImageFieldProps {
export default function TrackedImageField({ editor }: TrackedImageFieldProps) {
const { imageUrl, uploading, imageInputRef, cloudConfig, editItem } = editor;
+ const hadImage = useRef(Boolean(imageUrl));
+
+ // removing the image removes the focused button, so focus moves to the button that adds one
+ useEffect(() => {
+ if (hadImage.current && !imageUrl) document.getElementById('tracked-image-upload')?.focus();
+ hadImage.current = Boolean(imageUrl);
+ }, [imageUrl]);
const hint = cloudConfig
? 'Reddit posts have no thumbnail in the public API. Upload a screenshot to recognise the post at a glance.'
: 'Image uploads need Cloudinary set up on the server. Check Settings.';
return (
- <FieldRow label="Image" hint={hint}>
+ <FieldRow label="Image" optional hint={hint} error={editor.imageError ?? undefined}>
<input ref={imageInputRef} type="file" accept="image/*" onChange={editor.handleImageSelect} className="hidden" aria-label="Choose an image" />
{imageUrl ? (
<div className="flex items-center gap-3 rounded-control border border-line p-2">
<ImageLightbox src={imageUrl} alt={editItem!.title || 'Reddit post'} thumbClassName="size-14" />
- <p className="min-w-0 flex-1 text-caption text-ink-faint">Select the image to view it full size.</p>
- <Button variant="ghost" size="icon-xs" onClick={() => editor.setImageUrl(null)} disabled={uploading} aria-label="Remove image">
+ <p className="min-w-0 flex-1 text-small text-ink-muted">Select the image to view it full size.</p>
+ <Button type="button" variant="ghost" size="icon-sm" onClick={() => editor.setImageUrl(null)} disabled={uploading} aria-label="Remove image">
<X />
</Button>
</div>
diff --git a/frontend/src/features/analytics/tracked/useAddTracked.ts b/frontend/src/features/analytics/tracked/useAddTracked.ts
index 9707052..05566a6 100644
--- a/frontend/src/features/analytics/tracked/useAddTracked.ts
+++ b/frontend/src/features/analytics/tracked/useAddTracked.ts
@@ -19,36 +19,64 @@ export interface UseAddTrackedOptions {
const EMPTY_DRAFT: TrackedDraft = { url: '', label: '', category: '' };
+// what is wrong with the link, or null; checked when the field is left or the form is sent, never while typing
+export function trackedLinkProblem(url: string): string | null {
+ if (!url.trim()) return 'Paste the link of a Reddit post or a YouTube video.';
+ if (!detectContentType(url.trim())) return 'Only Reddit posts and YouTube videos can be tracked. Paste a link to one of those.';
+ return null;
+}
+
// the default Reddit account is read once, when the page first renders
export function useAddTracked({ redditAccounts, setItems, showToast }: UseAddTrackedOptions) {
const [open, setOpen] = useState(false);
const [draft, setDraft] = useState(EMPTY_DRAFT);
const [accountId, setAccountId] = useState(redditAccounts[0]?.id ?? 'none');
const [adding, setAdding] = useState(false);
+ const [checked, setChecked] = useState(false);
+ const [submitError, setSubmitError] = useState<string | null>(null);
+
+ const urlError = checked ? trackedLinkProblem(draft.url) : null;
+
+ const setDraftField = (name: keyof TrackedDraft, value: string) => {
+ setDraft(prev => ({ ...prev, [name]: value }));
+ setSubmitError(null);
+ };
- const setDraftField = (name: keyof TrackedDraft, value: string) => setDraft(prev => ({ ...prev, [name]: value }));
+ // a problem shown after leaving the field updates as the person fixes it
+ const checkUrl = () => { if (draft.url.trim()) setChecked(true); };
const handleOpenChange = (nextOpen: boolean) => {
+ if (adding) return;
setOpen(nextOpen);
- if (!nextOpen) setDraft(EMPTY_DRAFT);
+ if (!nextOpen) {
+ setDraft(EMPTY_DRAFT);
+ setChecked(false);
+ setSubmitError(null);
+ }
};
const handleAdd = async (e?: FormEvent<HTMLFormElement>) => {
e?.preventDefault();
+ if (adding) return;
+ setChecked(true);
const url = draft.url.trim();
- if (!url) { showToast('Paste a Reddit post or YouTube video link to track it.', 'error'); return; }
+ if (trackedLinkProblem(url)) {
+ document.getElementById('track-url')?.focus();
+ return;
+ }
const type = detectContentType(url);
- if (!type) { showToast('That link is not a Reddit post or a YouTube video. Paste one of those.', 'error'); return; }
setAdding(true);
+ setSubmitError(null);
try {
const linkedAccount = (type === 'reddit' && accountId !== 'none') ? accountId : null;
const item = await api.addTrackedContent(url, linkedAccount, draft.label.trim(), draft.category.trim());
setItems(prev => [item, ...prev]);
setOpen(false);
setDraft(EMPTY_DRAFT);
+ setChecked(false);
showToast('Now tracking this content');
} catch (err) {
- showToast(`Couldn't track that link. ${(err as Error).message}`, 'error');
+ setSubmitError(`Couldn't track that link. ${(err as Error).message}`);
} finally {
setAdding(false);
}
@@ -56,7 +84,7 @@ export function useAddTracked({ redditAccounts, setItems, showToast }: UseAddTra
return {
open, setOpen, handleOpenChange, draft, setDraftField, detectedType: detectContentType(draft.url),
- accountId, setAccountId, adding, handleAdd,
+ accountId, setAccountId, adding, handleAdd, urlError, checkUrl, submitError,
};
}
diff --git a/frontend/src/features/analytics/tracked/useBulkCategory.ts b/frontend/src/features/analytics/tracked/useBulkCategory.ts
index 1c9404f..1a4e49f 100644
--- a/frontend/src/features/analytics/tracked/useBulkCategory.ts
+++ b/frontend/src/features/analytics/tracked/useBulkCategory.ts
@@ -13,24 +13,38 @@ export interface UseBulkCategoryOptions {
}
export function useBulkCategory({ selection, setItems, showToast }: UseBulkCategoryOptions) {
- const [bulkCategory, setBulkCategory] = useState('');
+ const [bulkCategory, setBulkCategoryValue] = useState('');
+ const [assigning, setAssigning] = useState(false);
+ const [categoryError, setCategoryError] = useState<string | null>(null);
+
+ const setBulkCategory = (value: string) => {
+ setBulkCategoryValue(value);
+ setCategoryError(null);
+ };
const handleBulkCategory = async (e?: FormEvent<HTMLFormElement>) => {
e?.preventDefault();
- if (!bulkCategory.trim() || selection.selected.size === 0) return;
+ if (assigning || selection.selected.size === 0) return;
+ if (!bulkCategory.trim()) {
+ setCategoryError('Type the category to give the selected items.');
+ document.getElementById('bulk-category')?.focus();
+ return;
+ }
const ids = [...selection.selected];
+ setAssigning(true);
const results = await Promise.allSettled(ids.map(id => api.updateTrackedContent(id, { category: bulkCategory.trim() })));
+ setAssigning(false);
const succeeded = results
.map((result, i) => (result.status === 'fulfilled' ? { id: ids[i], data: result.value } : null))
.filter(Boolean) as { id: string; data: TrackedContentItem }[];
setItems(prev => prev.map(item => succeeded.find(entry => entry.id === item.id)?.data ?? item));
selection.clear();
- setBulkCategory('');
+ setBulkCategoryValue('');
const { message, severity } = bulkCategoryMessage(succeeded.length, ids.length - succeeded.length);
showToast(message, severity);
};
- return { bulkCategory, setBulkCategory, handleBulkCategory };
+ return { bulkCategory, setBulkCategory, handleBulkCategory, assigning, categoryError };
}
export type BulkCategory = ReturnType<typeof useBulkCategory>;
diff --git a/frontend/src/features/analytics/tracked/useTrackedEditor.ts b/frontend/src/features/analytics/tracked/useTrackedEditor.ts
index 304fed5..a7b7a78 100644
--- a/frontend/src/features/analytics/tracked/useTrackedEditor.ts
+++ b/frontend/src/features/analytics/tracked/useTrackedEditor.ts
@@ -3,6 +3,7 @@ import type { ChangeEvent, FormEvent, RefObject } from 'react';
import { api } from '../../../services/api';
import { isRedditItem } from '../../../utils/trackedContent';
import { imageFileError, parseManualViews } from './trackedList.ts';
+import { normalizeViewsText } from './viewsInput.ts';
import type { TrackedContentItem, TrackedContentUpdateRequest } from '@shared/types/domain.ts';
import type { CloudinaryConfigResponse } from '@shared/types/instagram.ts';
import type { ShowToast } from './useTrackedItems';
@@ -26,30 +27,33 @@ function clearInput(inputRef: RefObject<HTMLInputElement | null>) {
if (inputRef.current) inputRef.current.value = '';
}
+// image problems are shown under the image field, where the person chose the file
function useTrackedImage({ cloudConfig, showToast }: UseTrackedImageOptions) {
const [imageUrl, setImageUrl] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
+ const [imageError, setImageError] = useState<string | null>(null);
const imageInputRef = useRef<HTMLInputElement>(null);
const handleImageSelect = async (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const error = imageFileError(file, Boolean(cloudConfig));
- if (error) { showToast(error, 'error'); return; }
+ if (error) { setImageError(error); return; }
setUploading(true);
+ setImageError(null);
try {
// the Worker never takes binary uploads, so only the returned url is saved
setImageUrl(await api.uploadImage(file, cloudConfig!));
showToast('Image uploaded');
} catch (err) {
- showToast(`Image upload failed. ${(err as Error).message}`, 'error');
+ setImageError(`Couldn't upload the image. ${(err as Error).message}`);
} finally {
setUploading(false);
clearInput(imageInputRef);
}
};
- return { imageUrl, setImageUrl, uploading, imageInputRef, handleImageSelect };
+ return { imageUrl, setImageUrl, uploading, imageInputRef, handleImageSelect, imageError, setImageError };
}
export function useTrackedEditor({ cloudConfig, replaceItem, showToast }: UseTrackedEditorOptions) {
@@ -57,39 +61,58 @@ export function useTrackedEditor({ cloudConfig, replaceItem, showToast }: UseTra
const [editItem, setEditItem] = useState<TrackedContentItem | null>(null);
const [fields, setFields] = useState<TrackedEditFields>({ label: '', category: '', views: '' });
const [saving, setSaving] = useState(false);
+ const [viewsError, setViewsError] = useState<string | null>(null);
+ const [saveError, setSaveError] = useState<string | null>(null);
- const setField = (name: keyof TrackedEditFields, value: string) => setFields(prev => ({ ...prev, [name]: value }));
+ const setField = (name: keyof TrackedEditFields, value: string) => {
+ setFields(prev => ({ ...prev, [name]: value }));
+ if (name === 'views') setViewsError(null);
+ setSaveError(null);
+ };
const openEdit = (item: TrackedContentItem) => {
setEditItem(item);
setFields({ label: item.label || '', category: item.category || '', views: item.manualViews != null ? String(item.manualViews) : '' });
image.setImageUrl(item.imageUrl || null);
+ image.setImageError(null);
+ setViewsError(null);
+ setSaveError(null);
clearInput(image.imageInputRef);
};
const handleSaveEdit = async (e?: FormEvent<HTMLFormElement>) => {
e?.preventDefault();
- if (!editItem) return;
+ if (!editItem || saving) return;
const updates: TrackedContentUpdateRequest = { label: fields.label, category: fields.category };
if (isRedditItem(editItem)) {
- const views = parseManualViews(fields.views);
- if (views.error) { showToast(views.error, 'error'); return; }
+ const views = parseManualViews(normalizeViewsText(fields.views));
+ if (views.error) {
+ setViewsError(`${views.error} Separators and K or M work too, such as 12,500 or 12.5K.`);
+ document.getElementById('edit-views')?.focus();
+ return;
+ }
updates.manualViews = views.value;
updates.imageUrl = image.imageUrl || null;
}
setSaving(true);
+ setSaveError(null);
try {
replaceItem(editItem.id, await api.updateTrackedContent(editItem.id, updates));
setEditItem(null);
showToast('Changes saved');
} catch (err) {
- showToast(`Couldn't save the changes. ${(err as Error).message}`, 'error');
+ setSaveError(`Couldn't save the changes. ${(err as Error).message}`);
} finally {
setSaving(false);
}
};
- return { ...image, editItem, setEditItem, fields, setField, saving, openEdit, handleSaveEdit, cloudConfig };
+ // the typed views are shown as the number they will be saved as, once the field is left
+ const tidyViews = () => setFields(prev => ({ ...prev, views: normalizeViewsText(prev.views) }));
+
+ return {
+ ...image, editItem, setEditItem, fields, setField, saving, openEdit, handleSaveEdit, cloudConfig, viewsError, saveError, tidyViews,
+ };
}
export type TrackedEditor = ReturnType<typeof useTrackedEditor>;
diff --git a/frontend/src/features/analytics/tracked/viewsInput.ts b/frontend/src/features/analytics/tracked/viewsInput.ts
new file mode 100644
index 0000000..5520b23
--- /dev/null
+++ b/frontend/src/features/analytics/tracked/viewsInput.ts
@@ -0,0 +1,10 @@
+// Reddit's insights page shows views as "12,500" or "12.5K"; the field accepts what people copy and keeps the number
+
+const SUFFIX: Record<string, number> = { k: 1e3, m: 1e6, b: 1e9 };
+
+export function normalizeViewsText(raw: string): string {
+ const text = raw.trim().toLowerCase().replace(/[\s,]/g, '').replace(/views?$/, '');
+ const match = text.match(/^(\d+(?:\.\d+)?)([kmb])$/);
+ if (match) return String(Math.round(Number(match[1]) * SUFFIX[match[2]]));
+ return text;
+}
diff --git a/frontend/src/features/automations/AutomationAccounts.tsx b/frontend/src/features/automations/AutomationAccounts.tsx
index 800ccd0..a78e4d0 100644
--- a/frontend/src/features/automations/AutomationAccounts.tsx
+++ b/frontend/src/features/automations/AutomationAccounts.tsx
@@ -32,7 +32,7 @@ function AccountRow({ account, needsMessages, appAccount, busy, automations }: A
return (
<li className="flex flex-col gap-3 py-4 first:pt-0 last:pb-0 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 items-start gap-3">
- {appAccount && <AccountAvatar account={appAccount} size="sm" />}
+ {appAccount && <AccountAvatar account={appAccount} size="sm" decorative />}
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<span className="truncate text-sm font-semibold text-ink">@{account.username}</span>
@@ -45,12 +45,18 @@ function AccountRow({ account, needsMessages, appAccount, busy, automations }: A
{(!account.subscribedAt || missingMessages) && (
<Button size="sm" variant="outline" onClick={() => automations.subscribeAccount(account)} disabled={busy}>
{busy ? <Spinner className="size-4" /> : <Radio data-icon="inline-start" />}
- {missingMessages ? 'Turn on message events' : 'Turn on comment events'}
+ {busy ? 'Turning on' : missingMessages ? 'Turn on message events' : 'Turn on comment events'}
</Button>
)}
<label htmlFor={switchId} className="flex items-center gap-2 text-small text-ink-muted">
- Replies
- <Switch id={switchId} checked={!account.paused} disabled={busy} onCheckedChange={checked => automations.setAccountPaused(account, !checked)} />
+ <span aria-hidden="true">Replies</span>
+ <Switch
+ id={switchId}
+ aria-label={`Replies for @${account.username}`}
+ checked={!account.paused}
+ disabled={busy}
+ onCheckedChange={checked => automations.setAccountPaused(account, !checked)}
+ />
</label>
</div>
</li>
diff --git a/frontend/src/features/automations/AutomationActivity.tsx b/frontend/src/features/automations/AutomationActivity.tsx
index 2e673ef..4bd69af 100644
--- a/frontend/src/features/automations/AutomationActivity.tsx
+++ b/frontend/src/features/automations/AutomationActivity.tsx
@@ -1,15 +1,21 @@
-import { History, MessageCircle, RefreshCw, RotateCcw, Send } from 'lucide-react';
+import { useState } from 'react';
+import { AlertCircle, History, MessageCircle, RefreshCw, RotateCcw, Send } from 'lucide-react';
+import { Alert, AlertAction, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
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 ConfirmDialog from '@/components/ConfirmDialog';
import FilterChips from '@/components/FilterChips';
+import LiveStatus from '@/components/LiveStatus';
+import RelativeTime from '@/components/RelativeTime';
import RowAction from '@/components/RowAction';
import SurfaceBox from '@/components/SurfaceBox';
-import { EmptyState } from '@/components/StateViews';
+import { EmptyState, ErrorState } from '@/components/StateViews';
+import { cn } from '@/lib/utils';
import type { ReactNode } from 'react';
-import { fmtDate, timeAgo } from '../../utils/formatters';
+import { fmtDateTime } from '../../utils/formatters';
import { ACTIVITY_FILTERS, STATS_PERIODS, canRetry, canRetryPublic, gateDetail, publicStatusDisplay, statusDisplay } from './automationData.ts';
import type { ActivityFilter, StatsPeriod, StatusDisplay } from './automationData.ts';
import type { AutomationAccountState, AutomationActivityItem, AutomationRule } from '@shared/types/automation.ts';
@@ -39,6 +45,25 @@ interface ReplyLineProps {
detail: string;
}
+// past this length a comment is clamped, with a button to read the rest
+const LONG_COMMENT_CHARS = 160;
+
+// the comment in full for screen readers, clamped on screen until the person asks for the rest
+function CommentText({ text }: { text: string }) {
+ const [expanded, setExpanded] = useState(false);
+ const long = text.length > LONG_COMMENT_CHARS;
+ return (
+ <div className="flex flex-col items-start gap-0.5">
+ <p className={cn('text-sm break-words whitespace-pre-wrap text-ink', long && !expanded && 'line-clamp-3')}>{text}</p>
+ {long && (
+ <Button type="button" variant="link" size="sm" className="h-auto py-0.5 text-small" aria-expanded={expanded} onClick={() => setExpanded(!expanded)}>
+ {expanded ? 'Show less' : 'Show the whole comment'}
+ </Button>
+ )}
+ </div>
+ );
+}
+
// one of a comment's replies: which one, where it stands and why
function ReplyLine({ icon, label, status, detail }: ReplyLineProps) {
return (
@@ -57,22 +82,22 @@ const FILTER_OPTIONS = (Object.keys(ACTIVITY_FILTERS) as ActivityFilter[]).map(v
const PERIOD_OPTIONS = (Object.keys(STATS_PERIODS) as StatsPeriod[]).map(value => ({ value, label: STATS_PERIODS[value].label }));
function ActivityRow({ item, now, ruleName, username, retrying, onRetry, onRetryPublic }: ActivityRowProps) {
- const waitingUntil = item.nextAttemptAt && ['queued', 'retry_wait'].includes(item.status) ? `Next try ${fmtDate(item.nextAttemptAt)}` : null;
+ const waitingUntil = item.nextAttemptAt && ['queued', 'retry_wait'].includes(item.status) ? `Next try ${fmtDateTime(item.nextAttemptAt)}` : null;
const privateOff = item.status === 'skipped' && item.statusReason === 'private_reply_off';
const privateDetail = privateOff
? 'This rule does not send a private reply.'
- : gateDetail(item) ?? item.errorMessage ?? waitingUntil ?? (item.acceptedAt ? `Accepted ${fmtDate(item.acceptedAt)}` : '-');
+ : gateDetail(item) ?? item.errorMessage ?? waitingUntil ?? (item.acceptedAt ? `Accepted ${fmtDateTime(item.acceptedAt)}` : '-');
const publicReply = item.publicReply;
- const publicWaiting = publicReply?.nextAttemptAt && ['queued', 'retry_wait'].includes(publicReply.status) ? `Next try ${fmtDate(publicReply.nextAttemptAt)}` : null;
+ const publicWaiting = publicReply?.nextAttemptAt && ['queued', 'retry_wait'].includes(publicReply.status) ? `Next try ${fmtDateTime(publicReply.nextAttemptAt)}` : null;
const publicDetail = publicReply
- ? publicReply.errorMessage ?? publicWaiting ?? (publicReply.acceptedAt ? `Posted ${fmtDate(publicReply.acceptedAt)}: ${publicReply.text}` : publicReply.text)
+ ? publicReply.errorMessage ?? publicWaiting ?? (publicReply.acceptedAt ? `Posted ${fmtDateTime(publicReply.acceptedAt)}: ${publicReply.text}` : publicReply.text)
: '';
return (
<TableRow>
- <TableCell className="whitespace-nowrap text-small text-ink-muted" title={fmtDate(item.createdAt)}>{timeAgo(item.createdAt)}</TableCell>
+ <TableCell className="whitespace-nowrap text-small text-ink-muted"><RelativeTime date={item.createdAt} /></TableCell>
<TableCell className="whitespace-nowrap text-small">@{username}</TableCell>
<TableCell className="min-w-56 max-w-sm whitespace-normal">
- <p className="truncate text-sm text-ink">{item.text ?? <span className="text-ink-faint">Not kept for comments no rule answered</span>}</p>
+ {item.text ? <CommentText text={item.text} /> : <p className="text-sm text-ink-faint">Not kept for comments no rule answered</p>}
{item.fromUsername && <p className="text-caption text-ink-faint">@{item.fromUsername}</p>}
</TableCell>
<TableCell className="whitespace-nowrap text-small text-ink-muted">{ruleName ?? '-'}</TableCell>
@@ -87,7 +112,7 @@ function ActivityRow({ item, now, ruleName, username, retrying, onRetry, onRetry
<div className="flex justify-end gap-1">
{canRetry(item, now) && (
<RowAction
- label={item.status === 'needs_review' || item.followup?.status === 'needs_review' ? 'Send the private reply again after checking Instagram' : 'Try the private reply again'}
+ label={needsReview(item) ? 'Send the private reply again after checking Instagram' : 'Try the private reply again'}
onClick={() => onRetry(item)}
disabled={retrying !== null}
>
@@ -109,8 +134,20 @@ function ActivityRow({ item, now, ruleName, username, retrying, onRetry, onRetry
);
}
+// a private reply Instagram did not confirm may have arrived, so sending it again is the person's decision
+function needsReview(item: AutomationActivityItem): boolean {
+ return item.status === 'needs_review' || item.followup?.status === 'needs_review';
+}
+
export default function AutomationActivity({ activity, accounts, rules }: AutomationActivityProps) {
const { filters, setFilter, items } = activity;
+ const [pendingResend, setPendingResend] = useState<AutomationActivityItem | null>(null);
+ const handleRetry = (item: AutomationActivityItem) => {
+ if (needsReview(item)) setPendingResend(item);
+ else activity.retry(item);
+ };
+ const count = `${items.length} ${items.length === 1 ? 'comment' : 'comments'} shown${activity.nextBefore ? ', older ones available' : ''}`;
+ const status = activity.loading ? 'Loading activity' : activity.error ? '' : count;
const username = (accountId: string) => accounts.find(account => account.accountId === accountId)?.username ?? 'removed account';
const ruleName = (ruleId: string | null) => rules.find(rule => rule.id === ruleId)?.name ?? null;
const accountItems = [{ value: ALL, label: 'All accounts' }, ...accounts.map(account => ({ value: account.accountId, label: `@${account.username}` }))];
@@ -120,10 +157,21 @@ export default function AutomationActivity({ activity, accounts, rules }: Automa
<div className="flex flex-wrap items-end justify-between gap-3">
<div>
<h2 className="font-heading text-section font-semibold text-ink">Activity</h2>
- <p className="text-small text-ink-muted">Every comment received on an account with an active rule, and what happened to its private and public replies. The status filter follows the private reply.</p>
+ <p className="max-w-prose text-small text-ink-muted">Every comment received on an account with an active rule, and what happened to its private and public replies. The status filter follows the private reply.</p>
</div>
- <Button size="sm" variant="ghost" onClick={activity.load}><RefreshCw data-icon="inline-start" />Refresh</Button>
+ <Button size="sm" variant="outline" onClick={activity.load} disabled={activity.loading}>
+ <RefreshCw data-icon="inline-start" className={cn(activity.loading && 'animate-spin')} />
+ {activity.loading ? 'Refreshing' : 'Refresh'}
+ </Button>
</div>
+ <LiveStatus message={status} />
+ {activity.error && items.length > 0 && (
+ <Alert variant="destructive" role="alert">
+ <AlertCircle />
+ <AlertDescription><span className="sr-only">Error: </span>{activity.error} The list below is from the last successful load.</AlertDescription>
+ <AlertAction><Button size="sm" variant="outline" onClick={activity.load}>Try again</Button></AlertAction>
+ </Alert>
+ )}
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
<FilterChips label="Status" options={FILTER_OPTIONS} value={filters.filter} onChange={value => setFilter('filter', value)} />
<div className="flex flex-wrap gap-2">
@@ -154,7 +202,7 @@ export default function AutomationActivity({ activity, accounts, rules }: Automa
</div>
</div>
<SurfaceBox content={false} className="overflow-hidden">
- <Table>
+ <Table aria-label="Reply activity" aria-busy={activity.loading || undefined}>
<TableHeader>
<TableRow>
<TableHead>When</TableHead>
@@ -174,7 +222,7 @@ export default function AutomationActivity({ activity, accounts, rules }: Automa
ruleName={ruleName(item.ruleId)}
username={username(item.accountId)}
retrying={activity.retrying?.id === item.id ? activity.retrying.action : null}
- onRetry={activity.retry}
+ onRetry={handleRetry}
onRetryPublic={activity.retryPublic}
/>
))}
@@ -182,8 +230,10 @@ export default function AutomationActivity({ activity, accounts, rules }: Automa
<TableRow className="hover:bg-transparent">
<TableCell colSpan={6}>
{activity.loading
- ? <div className="flex justify-center py-8"><Spinner className="size-5" /></div>
- : <EmptyState compact icon={<History />} title="No activity for these filters" description="Comments appear here as Instagram sends them." />}
+ ? <div className="flex items-center justify-center gap-2 py-8 text-small text-ink-muted"><Spinner className="size-5" />Loading activity</div>
+ : activity.error
+ ? <ErrorState title="The reply activity could not load" description={activity.error} onRetry={activity.load} />
+ : <EmptyState compact icon={<History />} title="No activity for these filters" description="Comments appear here as Instagram sends them. Choose All, a longer period or all accounts to see more." />}
</TableCell>
</TableRow>
)}
@@ -193,9 +243,22 @@ export default function AutomationActivity({ activity, accounts, rules }: Automa
{activity.nextBefore && (
<Button variant="outline" size="sm" className="self-center" onClick={activity.loadMore} disabled={activity.loadingMore}>
{activity.loadingMore && <Spinner className="size-4" />}
- Show older activity
+ {activity.loadingMore ? 'Loading older activity' : 'Show older activity'}
</Button>
)}
+ <ConfirmDialog
+ open={Boolean(pendingResend)}
+ onOpenChange={open => { if (!open) setPendingResend(null); }}
+ icon={<Send />}
+ title="Send the private reply again?"
+ description={`Instagram did not confirm the first one, so it may have arrived. If it did, @${pendingResend?.fromUsername ?? 'this person'} gets the message twice. Check the conversation in Instagram first.`}
+ cancelLabel="Do not send"
+ confirmLabel="Send again"
+ onConfirm={() => {
+ if (pendingResend) activity.retry(pendingResend);
+ setPendingResend(null);
+ }}
+ />
</section>
);
}
diff --git a/frontend/src/features/automations/AutomationRules.tsx b/frontend/src/features/automations/AutomationRules.tsx
index f132520..a8b7a39 100644
--- a/frontend/src/features/automations/AutomationRules.tsx
+++ b/frontend/src/features/automations/AutomationRules.tsx
@@ -1,3 +1,4 @@
+import { Link } from 'react-router-dom';
import { Copy, ListChecks, Pencil, Plus, Trash2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -13,7 +14,7 @@ interface AutomationRulesProps {
rules: AutomationRule[];
accounts: AutomationAccountState[];
automations: AutomationsState;
- onNew: () => void;
+ newRulePath: string;
onEdit: (rule: AutomationRule) => void;
onDelete: (rule: AutomationRule) => void;
}
@@ -36,7 +37,7 @@ function RuleRow({ rule, username, busy, automations, onEdit, onDelete }: RuleRo
<span className="text-sm font-semibold text-ink">{rule.name}</span>
<span className="text-caption text-ink-faint">@{username}</span>
</div>
- <div className="flex flex-wrap gap-1.5" aria-label="Keywords">
+ <div className="flex flex-wrap gap-1.5" role="group" aria-label={`Keywords and replies of ${rule.name}`}>
{rule.matchMode === 'any'
? <Badge variant="warning">Any comment</Badge>
: rule.keywords.map(keyword => <Badge key={keyword} variant="secondary">{keyword}</Badge>)}
@@ -55,19 +56,27 @@ function RuleRow({ rule, username, busy, automations, onEdit, onDelete }: RuleRo
)}
</div>
<div className="flex shrink-0 items-center gap-1">
- <label htmlFor={switchId} className="mr-2 flex items-center gap-2 text-small text-ink-muted">
- {rule.enabled ? 'On' : 'Off'}
- <Switch id={switchId} checked={rule.enabled} disabled={busy} onCheckedChange={checked => automations.setRuleEnabled(rule, checked)} />
- </label>
- <RowAction label="Edit rule" onClick={() => onEdit(rule)} disabled={busy}><Pencil /></RowAction>
- <RowAction label="Copy rule" onClick={() => automations.duplicateRule(rule)} disabled={busy}><Copy /></RowAction>
- <RowAction label="Delete rule" onClick={() => onDelete(rule)} disabled={busy} danger><Trash2 /></RowAction>
+ <div className="mr-2 flex items-center gap-2 text-small text-ink-muted">
+ <span aria-hidden="true">{rule.enabled ? 'On' : 'Off'}</span>
+ <Switch
+ id={switchId}
+ aria-label={`Rule ${rule.name}`}
+ checked={rule.enabled}
+ disabled={busy}
+ onCheckedChange={checked => automations.setRuleEnabled(rule, checked)}
+ />
+ </div>
+ <RowAction label={`Edit ${rule.name}`} onClick={() => onEdit(rule)} disabled={busy}><Pencil /></RowAction>
+ <RowAction label={`Copy ${rule.name}`} onClick={() => automations.duplicateRule(rule)} disabled={busy}><Copy /></RowAction>
+ <span className="ml-2 border-l border-divider pl-2">
+ <RowAction label={`Delete ${rule.name}`} onClick={() => onDelete(rule)} disabled={busy} danger><Trash2 /></RowAction>
+ </span>
</div>
</li>
);
}
-export default function AutomationRules({ rules, accounts, automations, onNew, onEdit, onDelete }: AutomationRulesProps) {
+export default function AutomationRules({ rules, accounts, automations, newRulePath, onEdit, onDelete }: AutomationRulesProps) {
const username = (accountId: string) => accounts.find(account => account.accountId === accountId)?.username ?? 'removed account';
return (
<SurfaceBox
@@ -80,7 +89,7 @@ export default function AutomationRules({ rules, accounts, automations, onNew, o
icon={<ListChecks />}
title="No rules yet"
description="Create a rule with a keyword, such as GUIDE, and how to answer anyone who comments it: a private reply, a public reply or both."
- action={<Button size="sm" onClick={onNew}><Plus data-icon="inline-start" />New rule</Button>}
+ action={<Button render={<Link to={newRulePath} />}><Plus data-icon="inline-start" />New rule</Button>}
/>
) : (
<ul className="flex flex-col divide-y divide-divider">
diff --git a/frontend/src/features/automations/Automations.tsx b/frontend/src/features/automations/Automations.tsx
index 4a7e596..d08898e 100644
--- a/frontend/src/features/automations/Automations.tsx
+++ b/frontend/src/features/automations/Automations.tsx
@@ -1,9 +1,9 @@
-import { useMemo, useState } from 'react';
-import { Link } from 'react-router-dom';
+import { useMemo } from 'react';
+import { Link, useNavigate } from 'react-router-dom';
import { MessageSquareReply, Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import PageHeader from '@/components/PageHeader';
-import ConfirmDialog from '@/components/ConfirmDialog';
+import SurfaceBox from '@/components/SurfaceBox';
import { EmptyState, ErrorState, PageSkeleton } from '@/components/StateViews';
import { useAppContext } from '../../context/AppContext';
import AutomationAccounts from './AutomationAccounts';
@@ -11,27 +11,28 @@ import AutomationActivity from './AutomationActivity';
import AutomationMetrics from './AutomationMetrics';
import AutomationNotices from './AutomationNotices';
import AutomationRules from './AutomationRules';
-import RuleDialog from './RuleDialog';
import { useAutomationActivity } from './useAutomationActivity';
import { useAutomations } from './useAutomations';
-import { useRuleForm } from './useRuleForm';
import type { AutomationRule } from '@shared/types/automation.ts';
export default function Automations() {
+ const navigate = useNavigate();
const { accounts } = useAppContext();
const igAccounts = useMemo(() => accounts.filter(account => account.platform === 'instagram'), [accounts]);
const automations = useAutomations();
const activity = useAutomationActivity();
- const rule = useRuleForm({ saveRule: automations.saveRule });
- const [pendingDelete, setPendingDelete] = useState<AutomationRule | null>(null);
const { overview } = automations;
+ const newRulePath = overview?.accounts[0] ? `/automations/rules/new?account=${encodeURIComponent(overview.accounts[0].accountId)}` : '/automations/rules/new';
+ const openEdit = (rule: AutomationRule) => navigate(`/automations/rules/${encodeURIComponent(rule.id)}`);
+ // the empty rules list carries its own New rule button, so the header does not repeat it
+ const hasRules = Boolean(overview && overview.rules.length > 0);
const header = (
<PageHeader
title="Automations"
description="Answer comments on your posts and reels with a private reply, a public reply under the comment, or both."
- actions={overview && overview.accounts.length > 0 && (
- <Button onClick={() => rule.openNew(overview.accounts[0].accountId)}><Plus data-icon="inline-start" />New rule</Button>
+ actions={hasRules && (
+ <Button render={<Link to={newRulePath} />}><Plus data-icon="inline-start" />New rule</Button>
)}
/>
);
@@ -42,7 +43,9 @@ export default function Automations() {
return (
<div className="flex flex-col gap-6">
{header}
- <ErrorState title="Automations could not load" description={automations.loadError} onRetry={automations.load} />
+ <SurfaceBox>
+ <ErrorState title="Automations could not load" description={automations.loadError} onRetry={automations.load} />
+ </SurfaceBox>
</div>
);
}
@@ -51,20 +54,18 @@ export default function Automations() {
return (
<div className="flex flex-col gap-6">
{header}
- <EmptyState
- icon={<MessageSquareReply />}
- title="Connect an Instagram account first"
- description="Automations reply from an Instagram professional account connected with Instagram sign-in."
- action={<Button render={<Link to="/accounts?add=1" />}>Connect Instagram</Button>}
- />
+ <SurfaceBox>
+ <EmptyState
+ icon={<MessageSquareReply />}
+ title="Connect an Instagram account first"
+ description="Automations reply from an Instagram professional account connected with Instagram sign-in."
+ action={<Button render={<Link to="/accounts?add=1" />}>Add account</Button>}
+ />
+ </SurfaceBox>
</div>
);
}
- async function confirmDelete() {
- if (pendingDelete && await automations.deleteRule(pendingDelete)) setPendingDelete(null);
- }
-
return (
<div className="flex flex-col gap-6">
{header}
@@ -75,22 +76,11 @@ export default function Automations() {
rules={overview.rules}
accounts={overview.accounts}
automations={automations}
- onNew={() => rule.openNew(overview.accounts[0].accountId)}
- onEdit={rule.openEdit}
- onDelete={setPendingDelete}
+ newRulePath={newRulePath}
+ onEdit={openEdit}
+ onDelete={automations.deleteRule}
/>
<AutomationActivity activity={activity} accounts={overview.accounts} rules={overview.rules} />
- <RuleDialog rule={rule} igAccounts={igAccounts} />
- <ConfirmDialog
- open={Boolean(pendingDelete)}
- onOpenChange={open => !open && setPendingDelete(null)}
- title={`Delete ${pendingDelete?.name ?? 'this rule'}?`}
- description="Comments stop getting this reply. Replies already sent stay sent, and the rule's past activity stays in the list."
- confirmLabel="Delete rule"
- busy={automations.busyId === pendingDelete?.id}
- hold
- onConfirm={confirmDelete}
- />
</div>
);
}
diff --git a/frontend/src/features/automations/RuleDialog.tsx b/frontend/src/features/automations/RuleDialog.tsx
deleted file mode 100644
index f745047..0000000
--- a/frontend/src/features/automations/RuleDialog.tsx
+++ /dev/null
@@ -1,198 +0,0 @@
-import { Megaphone, MessageCircle, Send, UserCheck } from 'lucide-react';
-import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
-import { Badge } from '@/components/ui/badge';
-import { Button } from '@/components/ui/button';
-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
-import { Input } from '@/components/ui/input';
-import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
-import { Spinner } from '@/components/ui/spinner';
-import { Switch } from '@/components/ui/switch';
-import { Textarea } from '@/components/ui/textarea';
-import { FieldRow } from '@/components/DetailPanel';
-import AccountSelect from '@/components/AccountSelect';
-import RuleMediaPicker from './RuleMediaPicker';
-import RulePreview from './RulePreview';
-import RulePublicReplies from './RulePublicReplies';
-import type { AutomationMatchMode } from '@shared/types/automation.ts';
-import type { ReactNode } from 'react';
-import type { AppAccount } from '../../utils/formatters';
-import type { RuleScope } from './automationData.ts';
-import type { RuleFormState } from './useRuleForm';
-
-interface RuleDialogProps {
- rule: RuleFormState;
- igAccounts: AppAccount[];
-}
-
-interface ReplySectionProps {
- id: string;
- icon: ReactNode;
- title: string;
- description: string;
- checked: boolean;
- onCheckedChange: (checked: boolean) => void;
- children: ReactNode;
-}
-
-const MATCH_MODES: { value: AutomationMatchMode; label: string }[] = [
- { value: 'contains', label: 'Anywhere in the comment, as a whole word' },
- { value: 'exact', label: 'The whole comment, nothing else' },
- { value: 'any', label: 'Any comment, no keyword needed' },
-];
-
-const SCOPES: { value: RuleScope; label: string }[] = [
- { value: 'all', label: 'Every post and reel' },
- { value: 'selected', label: 'Only the posts I choose' },
-];
-
-// one way of answering, switched on and off on its own; its fields show only while it is on
-function ReplySection({ id, icon, title, description, checked, onCheckedChange, children }: ReplySectionProps) {
- return (
- <div className="flex flex-col gap-3 rounded-card border border-line p-4">
- <label htmlFor={id} className="flex items-center justify-between gap-3 text-sm font-medium text-ink">
- <span className="flex items-center gap-2 [&_svg]:size-4 [&_svg]:text-ink-muted">{icon}{title}</span>
- <Switch id={id} checked={checked} onCheckedChange={onCheckedChange} />
- </label>
- <p className="text-small text-ink-muted">{description}</p>
- {checked && children}
- </div>
- );
-}
-
-export default function RuleDialog({ rule, igAccounts }: RuleDialogProps) {
- const { form, setField, saving } = rule;
- return (
- <Dialog open={rule.open} onOpenChange={open => !saving && rule.setOpen(open)}>
- <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-3xl">
- <DialogHeader>
- <DialogTitle>{rule.ruleId ? 'Edit rule' : 'New rule'}</DialogTitle>
- <DialogDescription>When a comment matches, Twiligent answers its author in a private message, publicly under the comment, or both.</DialogDescription>
- </DialogHeader>
- <form id="automation-rule-form" onSubmit={rule.handleSubmit} className="grid gap-6 md:grid-cols-[minmax(0,1fr)_minmax(0,0.9fr)]">
- <div className="flex flex-col gap-5">
- <FieldRow label="Instagram account">
- <AccountSelect accounts={igAccounts} value={form.accountId} onChange={value => setField('accountId', value)} disabled={Boolean(rule.ruleId)} />
- </FieldRow>
- <FieldRow label="Name" htmlFor="rule-name" hint="Only you see this.">
- <Input id="rule-name" value={form.name} maxLength={80} onChange={e => setField('name', e.target.value)} placeholder="Free guide" />
- </FieldRow>
- <FieldRow label="Match">
- <Select value={form.matchMode} onValueChange={value => value && setField('matchMode', value as AutomationMatchMode)} items={MATCH_MODES}>
- <SelectTrigger className="w-full" aria-label="Match"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {MATCH_MODES.map(mode => <SelectItem key={mode.value} value={mode.value}>{mode.label}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
- {form.matchMode !== 'any' && (
- <label htmlFor="rule-case" className="flex items-center justify-between gap-3 text-small text-ink-muted">
- Match the letter case exactly
- <Switch id="rule-case" checked={form.caseSensitive} onCheckedChange={checked => setField('caseSensitive', checked)} />
- </label>
- )}
- </FieldRow>
- {form.matchMode === 'any' ? (
- <Alert variant="warning">
- <Megaphone />
- <AlertTitle>Every comment gets this answer</AlertTitle>
- <AlertDescription>
- Everyone who comments is answered, including people who did not ask, and a busy post reaches the hourly limits sooner.
- Each person gets at most a few private replies a day and one public reply per post a day. Aim the rule at chosen posts to
- keep it small. A keyword rule for the same post still answers first.
- </AlertDescription>
- </Alert>
- ) : (
- <FieldRow label="Keywords" htmlFor="rule-keywords" hint="Separate keywords with commas. Up to 10.">
- <Input id="rule-keywords" value={form.keywordsText} onChange={e => setField('keywordsText', e.target.value)} placeholder="GUIDE, LINK" />
- </FieldRow>
- )}
- <FieldRow label="Posts">
- <Select value={form.scope} onValueChange={value => value && setField('scope', value as RuleScope)} items={SCOPES}>
- <SelectTrigger className="w-full" aria-label="Posts"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {SCOPES.map(scope => <SelectItem key={scope.value} value={scope.value}>{scope.label}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
- {form.scope === 'selected' && <RuleMediaPicker media={rule.media} loading={rule.mediaLoading} selected={form.mediaIds} onToggle={rule.toggleMedia} />}
- </FieldRow>
- <ReplySection
- id="rule-private"
- icon={<Send />}
- title="Send a private reply"
- description="Instagram allows one private message per comment, within 7 days of it."
- checked={form.privateReplyEnabled}
- onCheckedChange={checked => setField('privateReplyEnabled', checked)}
- >
- <div className="flex flex-col gap-3 border-t border-divider pt-3">
- <label htmlFor="rule-follow" className="flex items-center justify-between gap-3 text-sm font-medium text-ink">
- <span className="flex items-center gap-2">
- <UserCheck className="size-4 text-ink-muted" />Send the link only to followers
- <Badge variant="warning">Testing</Badge>
- </span>
- <Switch id="rule-follow" checked={form.requireFollow} onCheckedChange={checked => setField('requireFollow', checked)} />
- </label>
- <p className="text-small text-ink-muted">
- Instagram tells Twiligent whether someone follows you only after they message you. With this on, the first reply asks them
- to follow and reply. When they reply, Twiligent asks Instagram, then sends the reply and link to followers and a reminder to
- everyone else, twice at most. If Instagram cannot say, nothing is sent.
- </p>
- <p className="text-small text-warning">
- This option is still being tested and may or may not work. It needs Instagram to send your account&apos;s messages to
- Twiligent, which Meta may not allow without extra app approval. Use a keyword rule when the link must arrive.
- </p>
- {form.requireFollow && (
- <>
- <FieldRow label="First reply" htmlFor="rule-follow-prompt" hint="Sent to everyone who comments. It has no link.">
- <Textarea id="rule-follow-prompt" rows={3} maxLength={1000} value={form.followPromptText} onChange={e => setField('followPromptText', e.target.value)} />
- </FieldRow>
- <FieldRow label="Reminder" htmlFor="rule-follow-reminder" hint="Sent when they reply but do not follow yet.">
- <Textarea id="rule-follow-reminder" rows={3} maxLength={1000} value={form.notFollowingText} onChange={e => setField('notFollowingText', e.target.value)} />
- </FieldRow>
- </>
- )}
- </div>
- <FieldRow label={form.requireFollow ? 'Reply for followers' : 'Reply'} htmlFor="rule-reply">
- <Textarea id="rule-reply" rows={4} maxLength={1000} value={form.replyText} onChange={e => setField('replyText', e.target.value)} placeholder="Here is your guide. Enjoy it." />
- </FieldRow>
- <FieldRow label="Link" htmlFor="rule-link" hint="Optional. Added on its own line after the reply. Must start with https://">
- <Input id="rule-link" type="url" inputMode="url" value={form.linkUrl} onChange={e => setField('linkUrl', e.target.value)} placeholder="https://example.com/guide" />
- </FieldRow>
- <FieldRow label="Private replies an hour" htmlFor="rule-limit" hint="Optional. The account's own limit still applies; Instagram allows 750 an hour.">
- <Input id="rule-limit" type="number" min={1} max={750} step={1} inputMode="numeric" value={form.hourlyLimit} onChange={e => setField('hourlyLimit', e.target.value)} placeholder="No limit for this rule" />
- </FieldRow>
- </ReplySection>
- <ReplySection
- id="rule-public"
- icon={<MessageCircle />}
- title="Reply publicly under the comment"
- description="Everyone can see it. One wording is picked for each comment, so a busy post does not fill with the same words, and each person gets at most one public reply per post a day."
- checked={form.publicReplyEnabled}
- onCheckedChange={checked => setField('publicReplyEnabled', checked)}
- >
- <RulePublicReplies texts={form.publicReplyTexts} onChange={texts => setField('publicReplyTexts', texts)} />
- <p className="text-small text-ink-muted">
- Keep it short and friendly, and leave the link for the private reply. The two are sent apart, so avoid promising a message:
- the private reply can fail on its own, for example when the person does not accept messages.
- </p>
- </ReplySection>
- <label htmlFor="rule-enabled" className="flex items-center justify-between gap-3 text-sm font-medium text-ink">
- Turn the rule on when saved
- <Switch id="rule-enabled" checked={form.enabled} onCheckedChange={checked => setField('enabled', checked)} />
- </label>
- </div>
- <RulePreview rule={rule} />
- </form>
- <DialogFooter>
- <Button variant="outline" onClick={() => rule.setOpen(false)} disabled={saving}>Cancel</Button>
- <Button type="submit" form="automation-rule-form" disabled={saving}>
- {saving && <Spinner className="size-4" />}
- {saving ? 'Saving' : rule.ruleId ? 'Save rule' : 'Create rule'}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/frontend/src/features/automations/RuleEditorPage.tsx b/frontend/src/features/automations/RuleEditorPage.tsx
new file mode 100644
index 0000000..3bd5dba
--- /dev/null
+++ b/frontend/src/features/automations/RuleEditorPage.tsx
@@ -0,0 +1,342 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom';
+import { History, Megaphone, MessageCircle, Send, UserCheck } from 'lucide-react';
+import { Alert, AlertAction, AlertDescription, AlertTitle } from '@/components/ui/alert';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+import { Spinner } from '@/components/ui/spinner';
+import { Switch } from '@/components/ui/switch';
+import { Textarea } from '@/components/ui/textarea';
+import { FieldRow } from '@/components/DetailPanel';
+import { fieldErrorId } from '@/lib/fieldIds';
+import AccountSelect from '@/components/AccountSelect';
+import ConfirmDialog from '@/components/ConfirmDialog';
+import PageHeader from '@/components/PageHeader';
+import { EmptyState, ErrorState, PageSkeleton } from '@/components/StateViews';
+import { useDocumentTitle } from '@/hooks/use-document-title';
+import { useUnsavedChanges } from '@/hooks/use-unsaved-changes';
+import { useAppContext } from '../../context/AppContext';
+import RuleMediaPicker from './RuleMediaPicker';
+import RulePreview from './RulePreview';
+import RulePublicReplies from './RulePublicReplies';
+import { emptyRuleForm, ruleToForm } from './automationData.ts';
+import { useAutomations } from './useAutomations';
+import { useRuleForm } from './useRuleForm';
+import type { AutomationMatchMode } from '@shared/types/automation.ts';
+import type { ReactNode } from 'react';
+import type { AppAccount } from '../../utils/formatters';
+import type { RuleForm, RuleScope } from './automationData.ts';
+
+interface ReplySectionProps {
+ id: string;
+ icon: ReactNode;
+ title: string;
+ description: string;
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+ error?: string;
+ children: ReactNode;
+}
+
+interface RuleEditorProps {
+ ruleId: string | null;
+ initialForm: RuleForm;
+ igAccounts: AppAccount[];
+ saveRule: (form: RuleForm, ruleId: string | null) => Promise<boolean>;
+}
+
+const MATCH_MODES: { value: AutomationMatchMode; label: string }[] = [
+ { value: 'contains', label: 'Anywhere in the comment, as a whole word' },
+ { value: 'exact', label: 'The whole comment, nothing else' },
+ { value: 'any', label: 'Any comment, no keyword needed' },
+];
+
+const SCOPES: { value: RuleScope; label: string }[] = [
+ { value: 'all', label: 'Every post and reel' },
+ { value: 'selected', label: 'Only the posts I choose' },
+];
+
+// one way of answering, switched on and off on its own; its fields show only while it is on
+function ReplySection({ id, icon, title, description, checked, onCheckedChange, error, children }: ReplySectionProps) {
+ return (
+ <div className="flex flex-col gap-3 rounded-card border border-line p-4">
+ <label htmlFor={id} className="flex items-center justify-between gap-3 text-sm font-medium text-ink">
+ <span className="flex items-center gap-2 [&_svg]:size-4 [&_svg]:text-ink-muted">{icon}{title}</span>
+ <Switch
+ id={id}
+ checked={checked}
+ onCheckedChange={onCheckedChange}
+ aria-describedby={[`${id}-description`, error ? fieldErrorId(id) : ''].filter(Boolean).join(' ')}
+ aria-invalid={error ? true : undefined}
+ />
+ </label>
+ <p id={`${id}-description`} className="max-w-prose text-body text-ink-muted">{description}</p>
+ {error && <p id={fieldErrorId(id)} className="text-sm text-danger"><span className="sr-only">Error: </span>{error}</p>}
+ {checked && children}
+ </div>
+ );
+}
+
+// the editor once the rule (or the account for a new one) is known, so the form starts from fixed values
+function RuleEditor({ ruleId, initialForm, igAccounts, saveRule }: RuleEditorProps) {
+ const navigate = useNavigate();
+ const [done, setDone] = useState(false);
+ const rule = useRuleForm({ ruleId, initialForm, saveRule, onSaved: useCallback(() => setDone(true), []) });
+ const { form, setField, saving, errorFor } = rule;
+ const guard = useUnsavedChanges(rule.dirty && !saving);
+
+ // leaving waits for the render in which the saved form no longer counts as unsaved work
+ useEffect(() => {
+ if (done) navigate('/automations');
+ }, [done, navigate]);
+
+ return (
+ <>
+ {rule.restored && (
+ <Alert variant="info">
+ <History />
+ <AlertTitle>Your unsaved changes are back</AlertTitle>
+ <AlertDescription>They were kept from your last visit to this rule in this tab.</AlertDescription>
+ <AlertAction><Button size="sm" variant="outline" onClick={rule.discardDraft}>Discard them</Button></AlertAction>
+ </Alert>
+ )}
+ <form id="automation-rule-form" onSubmit={rule.handleSubmit} noValidate className="flex flex-col gap-6">
+ <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,0.85fr)]">
+ <div className="flex flex-col gap-5">
+ <FieldRow label="Instagram account" htmlFor="rule-account" error={errorFor('accountId')} hint={ruleId ? 'A saved rule stays with its account.' : undefined}>
+ <AccountSelect id="rule-account" accounts={igAccounts} value={form.accountId} onChange={value => setField('accountId', value)} disabled={Boolean(ruleId)} />
+ </FieldRow>
+ <FieldRow label="Name" htmlFor="rule-name" hint="Only you see this." error={errorFor('name')}>
+ <Input id="rule-name" value={form.name} maxLength={80} onChange={e => setField('name', e.target.value)} placeholder="Free guide" />
+ </FieldRow>
+ <FieldRow label="Match" htmlFor="rule-match">
+ <Select value={form.matchMode} onValueChange={value => value && setField('matchMode', value as AutomationMatchMode)} items={MATCH_MODES}>
+ <SelectTrigger id="rule-match" className="w-full"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {MATCH_MODES.map(mode => <SelectItem key={mode.value} value={mode.value}>{mode.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FieldRow>
+ {form.matchMode !== 'any' && (
+ <label htmlFor="rule-case" className="-mt-2 flex items-center justify-between gap-3 text-small text-ink-muted">
+ Match the letter case exactly
+ <Switch id="rule-case" checked={form.caseSensitive} onCheckedChange={checked => setField('caseSensitive', checked)} />
+ </label>
+ )}
+ {form.matchMode === 'any' ? (
+ <Alert variant="warning">
+ <Megaphone />
+ <AlertTitle>Every comment gets this answer</AlertTitle>
+ <AlertDescription>
+ Everyone who comments is answered, including people who did not ask, and a busy post reaches the hourly limits sooner.
+ Each person gets at most a few private replies a day and one public reply per post a day. Aim the rule at chosen posts to
+ keep it small. A keyword rule for the same post still answers first.
+ </AlertDescription>
+ </Alert>
+ ) : (
+ <FieldRow label="Keywords" htmlFor="rule-keywords" hint="Separate keywords with commas or new lines. Up to 10." error={errorFor('keywordsText')}>
+ <Input id="rule-keywords" value={form.keywordsText} onChange={e => setField('keywordsText', e.target.value)} placeholder="GUIDE, LINK" />
+ </FieldRow>
+ )}
+ <FieldRow label="Posts" htmlFor="rule-scope">
+ <Select value={form.scope} onValueChange={value => value && setField('scope', value as RuleScope)} items={SCOPES}>
+ <SelectTrigger id="rule-scope" className="w-full"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {SCOPES.map(scope => <SelectItem key={scope.value} value={scope.value}>{scope.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FieldRow>
+ {form.scope === 'selected' && (
+ <FieldRow label="Posts and reels to answer on" htmlFor="rule-posts" error={errorFor('mediaIds')}>
+ <RuleMediaPicker
+ id="rule-posts"
+ media={rule.media}
+ loading={rule.mediaLoading}
+ error={rule.mediaError}
+ onRetry={rule.retryMedia}
+ selected={form.mediaIds}
+ onToggle={rule.toggleMedia}
+ />
+ </FieldRow>
+ )}
+ <ReplySection
+ id="rule-private"
+ icon={<Send />}
+ title="Send a private reply"
+ description="Instagram allows one private message per comment, within 7 days of it."
+ checked={form.privateReplyEnabled}
+ onCheckedChange={checked => setField('privateReplyEnabled', checked)}
+ error={errorFor('replies')}
+ >
+ <div className="flex flex-col gap-3 border-t border-divider pt-3">
+ <label htmlFor="rule-follow" className="flex items-center justify-between gap-3 text-sm font-medium text-ink">
+ <span className="flex items-center gap-2">
+ <UserCheck className="size-4 text-ink-muted" />Send the link only to followers
+ <Badge variant="warning">Testing</Badge>
+ </span>
+ <Switch
+ id="rule-follow"
+ checked={form.requireFollow}
+ onCheckedChange={checked => setField('requireFollow', checked)}
+ aria-describedby={errorFor('requireFollow') ? fieldErrorId('rule-follow') : 'rule-follow-help'}
+ aria-invalid={errorFor('requireFollow') ? true : undefined}
+ />
+ </label>
+ {errorFor('requireFollow') && <p id={fieldErrorId('rule-follow')} className="text-sm text-danger"><span className="sr-only">Error: </span>{errorFor('requireFollow')}</p>}
+ <p id="rule-follow-help" className="max-w-prose text-body text-ink-muted">
+ Instagram tells Twiligent whether someone follows you only after they message you. With this on, the first reply asks them
+ to follow and reply. When they reply, Twiligent asks Instagram, then sends the reply and link to followers and a reminder to
+ everyone else, twice at most. If Instagram cannot say, nothing is sent.
+ </p>
+ <p className="max-w-prose text-body text-warning">
+ This option is still being tested and may or may not work. It needs Instagram to send your account&apos;s messages to
+ Twiligent, which Meta may not allow without extra app approval. Use a keyword rule when the link must arrive.
+ </p>
+ {form.requireFollow && (
+ <>
+ <FieldRow label="First reply" htmlFor="rule-follow-prompt" hint="Sent to everyone who comments. It has no link." error={errorFor('followPromptText')}>
+ <Textarea id="rule-follow-prompt" rows={3} maxLength={1000} value={form.followPromptText} onChange={e => setField('followPromptText', e.target.value)} />
+ </FieldRow>
+ <FieldRow label="Reminder" htmlFor="rule-follow-reminder" hint="Sent when they reply but do not follow yet." error={errorFor('notFollowingText')}>
+ <Textarea id="rule-follow-reminder" rows={3} maxLength={1000} value={form.notFollowingText} onChange={e => setField('notFollowingText', e.target.value)} />
+ </FieldRow>
+ </>
+ )}
+ </div>
+ <FieldRow label={form.requireFollow ? 'Reply for followers' : 'Reply'} htmlFor="rule-reply" error={errorFor('replyText')}>
+ <Textarea id="rule-reply" rows={4} maxLength={1000} value={form.replyText} onChange={e => setField('replyText', e.target.value)} placeholder="Here is your guide. Enjoy it." />
+ </FieldRow>
+ <FieldRow label="Link" htmlFor="rule-link" optional hint="Added on its own line after the reply. An address without https:// gets it added." error={errorFor('linkUrl')}>
+ <Input
+ id="rule-link"
+ type="url"
+ inputMode="url"
+ value={form.linkUrl}
+ onChange={e => setField('linkUrl', e.target.value)}
+ onBlur={rule.normalizeLinkField}
+ placeholder="https://example.com/guide"
+ />
+ </FieldRow>
+ <FieldRow label="Private replies an hour" htmlFor="rule-limit" optional hint="The account's own limit still applies; Instagram allows 750 an hour." error={errorFor('hourlyLimit')}>
+ <Input id="rule-limit" type="text" inputMode="numeric" value={form.hourlyLimit} onChange={e => setField('hourlyLimit', e.target.value.replace(/[\s,]/g, ''))} placeholder="No limit for this rule" />
+ </FieldRow>
+ </ReplySection>
+ <ReplySection
+ id="rule-public"
+ icon={<MessageCircle />}
+ title="Reply publicly under the comment"
+ description="Everyone can see it. One wording is picked for each comment, so a busy post does not fill with the same words, and each person gets at most one public reply per post a day."
+ checked={form.publicReplyEnabled}
+ onCheckedChange={checked => setField('publicReplyEnabled', checked)}
+ >
+ <RulePublicReplies texts={form.publicReplyTexts} onChange={texts => setField('publicReplyTexts', texts)} />
+ {errorFor('publicReplyTexts') && (
+ <p className="text-sm text-danger" role="alert"><span className="sr-only">Error: </span>{errorFor('publicReplyTexts')}</p>
+ )}
+ <p className="max-w-prose text-body text-ink-muted">
+ Keep it short and friendly, and leave the link for the private reply. The two are sent apart, so avoid promising a message:
+ the private reply can fail on its own, for example when the person does not accept messages.
+ </p>
+ </ReplySection>
+ <label htmlFor="rule-enabled" className="flex items-center justify-between gap-3 text-sm font-medium text-ink">
+ Turn the rule on when saved
+ <Switch id="rule-enabled" checked={form.enabled} onCheckedChange={checked => setField('enabled', checked)} />
+ </label>
+ </div>
+ <RulePreview rule={rule} />
+ </div>
+ <div className="sticky bottom-0 z-10 -mx-1 flex flex-wrap items-center justify-end gap-3 border-t border-line bg-surface/95 px-1 py-3 backdrop-blur">
+ {rule.problem && (
+ <p className="mr-auto text-sm text-danger" role="alert">
+ <span className="sr-only">Error: </span>Fix the highlighted field: {rule.problem.message}.
+ </p>
+ )}
+ <Button variant="outline" render={<Link to="/automations" />}>Cancel</Button>
+ <Button type="submit" disabled={saving}>
+ {saving && <Spinner className="size-4" />}
+ {saving ? 'Saving' : ruleId ? 'Save rule' : 'Create rule'}
+ </Button>
+ </div>
+ </form>
+ <ConfirmDialog
+ open={guard.blocked}
+ onOpenChange={open => { if (!open) guard.stay(); }}
+ title="Leave without saving the rule?"
+ description="Your changes are kept as a draft in this tab, so they come back if you open this rule again before closing the tab."
+ cancelLabel="Keep editing"
+ confirmLabel="Leave"
+ onConfirm={guard.leave}
+ />
+ </>
+ );
+}
+
+// a full page rather than a dialog, so a long rule has room, keeps its address and survives a stray click outside it
+export default function RuleEditorPage() {
+ const { id } = useParams();
+ const [params] = useSearchParams();
+ const { accounts } = useAppContext();
+ const igAccounts = useMemo(() => accounts.filter(account => account.platform === 'instagram'), [accounts]);
+ const automations = useAutomations();
+ const { overview } = automations;
+ const ruleId = id ?? null;
+ const existing = ruleId ? overview?.rules.find(rule => rule.id === ruleId) : undefined;
+ const title = ruleId ? (existing ? `Edit ${existing.name}` : 'Edit rule') : 'New rule';
+ useDocumentTitle(title);
+
+ const initialForm = useMemo(() => {
+ if (!overview) return null;
+ if (ruleId) return existing ? ruleToForm(existing) : null;
+ const requested = params.get('account');
+ const accountId = overview.accounts.some(account => account.accountId === requested) ? requested : overview.accounts[0]?.accountId;
+ return accountId ? emptyRuleForm(accountId) : null;
+ }, [existing, overview, params, ruleId]);
+
+ const header = (
+ <PageHeader
+ back={{ to: '/automations', label: 'Automations' }}
+ title={title}
+ description="When a comment matches, Twiligent answers its author in a private message, publicly under the comment, or both."
+ />
+ );
+
+ if (!overview && !automations.loadError) return <PageSkeleton metrics={0} />;
+
+ if (!overview) {
+ return (
+ <div className="flex flex-col gap-6">
+ {header}
+ <ErrorState title="The rule could not load" description={automations.loadError} onRetry={automations.load} />
+ </div>
+ );
+ }
+
+ if (!initialForm) {
+ return (
+ <div className="flex flex-col gap-6">
+ {header}
+ <EmptyState
+ icon={<Send />}
+ title={ruleId ? 'This rule no longer exists' : 'Connect an Instagram account first'}
+ description={ruleId ? 'It may have been deleted in another tab.' : 'Rules reply from an Instagram professional account connected with Instagram sign-in.'}
+ action={ruleId
+ ? <Button variant="outline" render={<Link to="/automations" />}>Back to automations</Button>
+ : <Button render={<Link to="/accounts?add=1" />}>Add account</Button>}
+ />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-6">
+ {header}
+ <RuleEditor key={ruleId ?? 'new'} ruleId={ruleId} initialForm={initialForm} igAccounts={igAccounts} saveRule={automations.saveRule} />
+ </div>
+ );
+}
diff --git a/frontend/src/features/automations/RuleMediaPicker.tsx b/frontend/src/features/automations/RuleMediaPicker.tsx
index 03abf7d..0841de6 100644
--- a/frontend/src/features/automations/RuleMediaPicker.tsx
+++ b/frontend/src/features/automations/RuleMediaPicker.tsx
@@ -1,4 +1,6 @@
import { Check, ImageOff } from 'lucide-react';
+import { Alert, AlertDescription } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { cn } from '@/lib/utils';
import type { InstagramMedia } from '@shared/types/instagram.ts';
@@ -8,14 +10,36 @@ interface RuleMediaPickerProps {
loading: boolean;
selected: string[];
onToggle: (id: string) => void;
+ error: string | null;
+ onRetry: () => void;
+ id?: string;
+ 'aria-describedby'?: string;
+ 'aria-invalid'?: boolean;
}
// the account's recent posts and reels as a grid of toggles
-export default function RuleMediaPicker({ media, loading, selected, onToggle }: RuleMediaPickerProps) {
- if (loading) return <div className="flex justify-center py-6"><Spinner className="size-5" /></div>;
- if (media.length === 0) return <p className="text-small text-ink-muted">No posts found on this account yet.</p>;
+// a failed load is an error with a retry, never an empty list
+export default function RuleMediaPicker({ media, loading, selected, onToggle, error, onRetry, id, ...aria }: RuleMediaPickerProps) {
+ if (loading) {
+ return (
+ <div role="status" className="flex items-center justify-center gap-2 py-6 text-small text-ink-muted">
+ <Spinner className="size-5" />Loading posts
+ </div>
+ );
+ }
+ if (error) {
+ return (
+ <Alert variant="destructive" role="alert">
+ <AlertDescription className="flex flex-wrap items-center justify-between gap-2">
+ <span><span className="sr-only">Error: </span>{error}</span>
+ <Button type="button" size="sm" variant="outline" onClick={onRetry}>Try again</Button>
+ </AlertDescription>
+ </Alert>
+ );
+ }
+ if (media.length === 0) return <p className="text-small text-ink-muted">This account has no posts or reels yet. Answer comments on every post instead.</p>;
return (
- <div className="grid max-h-64 grid-cols-3 gap-2 overflow-y-auto sm:grid-cols-4" role="group" aria-label="Posts and reels">
+ <div id={id} tabIndex={-1} className="grid max-h-64 grid-cols-3 gap-2 overflow-y-auto rounded-control sm:grid-cols-4" role="group" aria-label={`Posts and reels, ${selected.length} chosen`} {...aria}>
{media.map(item => {
const active = selected.includes(item.id);
const image = item.thumbnailUrl || item.mediaUrl;
diff --git a/frontend/src/features/automations/RulePreview.tsx b/frontend/src/features/automations/RulePreview.tsx
index f38d1d4..cabe29c 100644
--- a/frontend/src/features/automations/RulePreview.tsx
+++ b/frontend/src/features/automations/RulePreview.tsx
@@ -41,7 +41,7 @@ export default function RulePreview({ rule }: RulePreviewProps) {
.filter(Boolean)
.join(' and ');
return (
- <div className="flex flex-col gap-4 self-start rounded-card border border-line bg-surface-sunken p-4 md:sticky md:top-0">
+ <div className="flex flex-col gap-4 self-start rounded-card border border-line bg-surface-sunken p-4 lg:sticky lg:top-[calc(var(--topbar-h)+1.5rem)]">
{form.publicReplyEnabled && (
<div className="flex flex-col gap-2">
<p className="text-small font-medium text-ink">Under the comment</p>
@@ -74,16 +74,15 @@ export default function RulePreview({ rule }: RulePreviewProps) {
<Input id="rule-test" value={rule.sampleComment} onChange={e => rule.setSampleComment(e.target.value)} placeholder="Send me the guide" />
<Button type="button" variant="outline" onClick={rule.runTest} disabled={rule.testing || !canTest}>
{rule.testing ? <Spinner className="size-4" /> : <FlaskConical data-icon="inline-start" />}
- Test
+ {rule.testing ? 'Testing' : 'Test'}
</Button>
</div>
- {testResult && (
- <p role="status" className={cn('text-small', testResult.matched ? 'text-success' : 'text-ink-muted')}>
- {testResult.matched
- ? `${testResult.keyword ? `Matches the keyword ${testResult.keyword}.` : 'This rule answers any comment.'} This comment would get ${answers || 'no answer'}.`
- : 'No keyword matches this comment, so it would get no answer.'}
- </p>
- )}
+ {/* mounted before any result, so a new result is announced */}
+ <p role="status" className={cn('text-small', testResult?.matched ? 'text-success' : 'text-ink-muted')}>
+ {testResult && (testResult.matched
+ ? `${testResult.keyword ? `Matches the keyword ${testResult.keyword}.` : 'This rule answers any comment.'} This comment would get ${answers || 'no answer'}.`
+ : 'No keyword matches this comment, so it would get no answer.')}
+ </p>
<p className="text-caption text-ink-faint">The test checks the match only. Nothing is sent or posted.</p>
</div>
</div>
diff --git a/frontend/src/features/automations/automationData.ts b/frontend/src/features/automations/automationData.ts
index 8fd043a..dbed7fc 100644
--- a/frontend/src/features/automations/automationData.ts
+++ b/frontend/src/features/automations/automationData.ts
@@ -90,7 +90,7 @@ export interface AutomationSummary {
export type RuleScope = 'all' | 'selected';
-// the rule dialog's fields, as typed; keywords and the limit stay text until saved
+// the rule editor's fields, as typed; keywords and the limit stay text until saved
export interface RuleForm {
accountId: string;
name: string;
@@ -111,6 +111,16 @@ export interface RuleForm {
notFollowingText: string;
}
+// the field a problem belongs to, so the editor can show it under that field and move focus there
+export type RuleField =
+ | 'accountId' | 'name' | 'keywordsText' | 'mediaIds' | 'replies' | 'replyText' | 'linkUrl' | 'hourlyLimit'
+ | 'publicReplyTexts' | 'requireFollow' | 'followPromptText' | 'notFollowingText';
+
+export interface RuleFieldProblem {
+ field: RuleField;
+ message: string;
+}
+
export function periodStart(period: StatsPeriod, now: number): string {
return new Date(now - STATS_PERIODS[period].ms).toISOString();
}
@@ -272,7 +282,7 @@ export function formToRequest(form: RuleForm): AutomationRuleRequest {
mediaIds: form.scope === 'selected' ? form.mediaIds : [],
privateReplyEnabled: form.privateReplyEnabled,
replyText: form.replyText.trim(),
- linkUrl: form.linkUrl.trim() || null,
+ linkUrl: normalizeLink(form.linkUrl) || null,
publicReplyEnabled: form.publicReplyEnabled,
// texts kept while the public reply is off come back when it is turned on again
publicReplyTexts: publicReplyTexts(form.publicReplyTexts),
@@ -284,58 +294,79 @@ export function formToRequest(form: RuleForm): AutomationRuleRequest {
};
}
-function linkProblem(linkUrl: string): string | null {
+// people paste "example.com/guide" as often as the full address, so a link without a scheme is taken as https
+export function normalizeLink(linkUrl: string): string {
const link = linkUrl.trim();
+ if (!link || /^[a-z][a-z0-9+.-]*:/i.test(link)) return link;
+ return `https://${link.replace(/^\/\//, '')}`;
+}
+
+function linkProblem(linkUrl: string): string | null {
+ const link = normalizeLink(linkUrl);
if (!link) return null;
try {
const url = new URL(link);
if (url.protocol !== 'https:') return 'The link must start with https://';
if (url.username || url.password) return 'The link cannot contain a user name or password';
+ if (!url.hostname.includes('.')) return 'The link must be a full address, such as https://example.com/guide';
} catch {
- return 'The link must be a full address starting with https://';
+ return 'The link must be a full address, such as https://example.com/guide';
}
return null;
}
-// the first thing to fix before the rule can be saved, or null; the Worker checks the same rules again
-export function ruleFormProblem(form: RuleForm): string | null {
- if (!form.accountId) return 'Choose the Instagram account';
- if (!form.name.trim()) return 'Give the rule a name';
+// the first thing to fix before the rule can be saved and the field it belongs to, or null; the Worker checks the same
+export function ruleFormError(form: RuleForm): RuleFieldProblem | null {
+ const problem = (field: RuleField, message: string): RuleFieldProblem => ({ field, message });
+ if (!form.accountId) return problem('accountId', 'Choose the Instagram account');
+ if (!form.name.trim()) return problem('name', 'Give the rule a name');
if (form.matchMode !== 'any') {
const keywords = parseKeywords(form.keywordsText, form.caseSensitive);
- if (keywords.length === 0) return 'Add at least one keyword';
- if (keywords.length > MAX_KEYWORDS) return `A rule can have at most ${MAX_KEYWORDS} keywords`;
+ if (keywords.length === 0) return problem('keywordsText', 'Add at least one keyword');
+ if (keywords.length > MAX_KEYWORDS) return problem('keywordsText', `A rule can have at most ${MAX_KEYWORDS} keywords`);
}
- if (form.scope === 'selected' && form.mediaIds.length === 0) return 'Choose at least one post, or answer comments on every post';
- if (!form.privateReplyEnabled && !form.publicReplyEnabled) return 'Turn on the private reply, the public reply, or both';
- if (form.privateReplyEnabled && !form.replyText.trim()) return 'Write the reply to send';
+ if (form.scope === 'selected' && form.mediaIds.length === 0) return problem('mediaIds', 'Choose at least one post, or answer comments on every post');
+ if (!form.privateReplyEnabled && !form.publicReplyEnabled) return problem('replies', 'Turn on the private reply, the public reply, or both');
+ if (form.privateReplyEnabled && !form.replyText.trim()) return problem('replyText', 'Write the reply to send');
const link = linkProblem(form.linkUrl);
- if (link) return link;
+ if (link) return problem('linkUrl', link);
const limit = form.hourlyLimit.trim();
if (limit && !(/^\d+$/.test(limit) && Number(limit) >= 1 && Number(limit) <= MAX_HOURLY_LIMIT)) {
- return `The hourly limit must be a whole number from 1 to ${MAX_HOURLY_LIMIT}`;
+ return problem('hourlyLimit', `The hourly limit must be a whole number from 1 to ${MAX_HOURLY_LIMIT}`);
+ }
+ const bytes = messageBytes(composeReply(form.replyText, normalizeLink(form.linkUrl)));
+ if (form.privateReplyEnabled && bytes > MAX_MESSAGE_BYTES) {
+ return problem('replyText', `The reply with its link is ${bytes} bytes; Instagram accepts at most ${MAX_MESSAGE_BYTES}`);
}
- const bytes = messageBytes(composeReply(form.replyText, form.linkUrl));
- if (form.privateReplyEnabled && bytes > MAX_MESSAGE_BYTES) return `The reply with its link is ${bytes} bytes; Instagram accepts at most ${MAX_MESSAGE_BYTES}`;
if (form.publicReplyEnabled) {
const texts = publicReplyTexts(form.publicReplyTexts);
- if (texts.length === 0) return 'Write at least one public reply';
- if (texts.length > MAX_PUBLIC_REPLY_TEXTS) return `A rule can have at most ${MAX_PUBLIC_REPLY_TEXTS} public replies`;
+ if (texts.length === 0) return problem('publicReplyTexts', 'Write at least one public reply');
+ if (texts.length > MAX_PUBLIC_REPLY_TEXTS) return problem('publicReplyTexts', `A rule can have at most ${MAX_PUBLIC_REPLY_TEXTS} public replies`);
for (const text of texts) {
- const problem = publicReplyTextProblem(text);
- if (problem) return problem;
+ const textProblem = publicReplyTextProblem(text);
+ if (textProblem) return problem('publicReplyTexts', textProblem);
}
}
- if (form.requireFollow && !form.privateReplyEnabled) return 'Sending the link only to followers needs the private reply. Turn it on, or turn off the followers-only option';
+ if (form.requireFollow && !form.privateReplyEnabled) {
+ return problem('requireFollow', 'Sending the link only to followers needs the private reply. Turn it on, or turn off the followers-only option');
+ }
if (form.requireFollow) {
- if (!form.followPromptText.trim()) return 'Write the message that asks people to follow you and reply';
- if (!form.notFollowingText.trim()) return 'Write the reminder for people who do not follow you yet';
- const longest = Math.max(messageBytes(form.followPromptText.trim()), messageBytes(form.notFollowingText.trim()));
- if (longest > MAX_MESSAGE_BYTES) return `A followers-only message is ${longest} bytes; Instagram accepts at most ${MAX_MESSAGE_BYTES}`;
+ if (!form.followPromptText.trim()) return problem('followPromptText', 'Write the message that asks people to follow you and reply');
+ if (!form.notFollowingText.trim()) return problem('notFollowingText', 'Write the reminder for people who do not follow you yet');
+ const prompt = messageBytes(form.followPromptText.trim());
+ const reminder = messageBytes(form.notFollowingText.trim());
+ if (Math.max(prompt, reminder) > MAX_MESSAGE_BYTES) {
+ return problem(prompt >= reminder ? 'followPromptText' : 'notFollowingText', `A followers-only message is ${Math.max(prompt, reminder)} bytes; Instagram accepts at most ${MAX_MESSAGE_BYTES}`);
+ }
}
return null;
}
+// the message of the first problem, or null
+export function ruleFormProblem(form: RuleForm): string | null {
+ return ruleFormError(form)?.message ?? null;
+}
+
// a followers-only rule that is on needs Instagram to send the account's messages as well as its comments
export function needsMessageEvents(rules: Pick<AutomationRule, 'accountId' | 'enabled' | 'requireFollow'>[], accountId: string): boolean {
return rules.some(rule => rule.accountId === accountId && rule.enabled && rule.requireFollow);
diff --git a/frontend/src/features/automations/useAutomationActivity.ts b/frontend/src/features/automations/useAutomationActivity.ts
index 4b4b0ce..9e667c8 100644
--- a/frontend/src/features/automations/useAutomationActivity.ts
+++ b/frontend/src/features/automations/useAutomationActivity.ts
@@ -1,4 +1,6 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useSearchParams } from 'react-router-dom';
+import { readChoice, withParam } from '@/lib/urlState';
import { useAppContext } from '../../context/AppContext';
import { api } from '../../services/api';
import { ACTIVITY_FILTERS, periodStart, summarizeStats } from './automationData.ts';
@@ -26,10 +28,22 @@ function query(filters: ActivityFilters, before?: string): URLSearchParams {
return params;
}
-// the counts and the activity list share the period, account and rule filters
+const FILTER_KEYS = Object.keys(ACTIVITY_FILTERS) as ActivityFilter[];
+const PERIOD_KEYS: StatsPeriod[] = ['24h', '7d', '30d'];
+const PARAM: Record<keyof ActivityFilters, string> = { filter: 'status', period: 'period', accountId: 'account', ruleId: 'rule' };
+const DEFAULTS: ActivityFilters = { filter: 'all', period: '7d', accountId: '', ruleId: '' };
+
+// the counts and the activity list share the period, account and rule filters, kept in the address so a refresh
+// or a shared link shows the same view
export function useAutomationActivity() {
const { showToast } = useAppContext();
- const [filters, setFilters] = useState<ActivityFilters>({ filter: 'all', period: '7d', accountId: '', ruleId: '' });
+ const [params, setParams] = useSearchParams();
+ const filter = readChoice(params, PARAM.filter, FILTER_KEYS, DEFAULTS.filter);
+ const period = readChoice(params, PARAM.period, PERIOD_KEYS, DEFAULTS.period);
+ const accountId = params.get(PARAM.accountId) ?? '';
+ const ruleId = params.get(PARAM.ruleId) ?? '';
+ const filters = useMemo<ActivityFilters>(() => ({ filter, period, accountId, ruleId }), [filter, period, accountId, ruleId]);
+ const [error, setError] = useState<string | null>(null);
const [items, setItems] = useState<AutomationActivityItem[]>([]);
const [nextBefore, setNextBefore] = useState<string | null>(null);
const [summary, setSummary] = useState<AutomationSummary | null>(null);
@@ -44,7 +58,7 @@ export function useAutomationActivity() {
const load = useCallback(async () => {
const current = ++generation.current;
setLoading(true);
- setNextBefore(null);
+ setError(null);
try {
const statsQuery = query({ ...filters, filter: 'all' });
statsQuery.delete('status');
@@ -56,14 +70,16 @@ export function useAutomationActivity() {
if (current !== generation.current) return;
setItems(page.items);
setNextBefore(page.nextBefore);
+ setError(null);
setSummary(summarizeStats(stats.stats));
setCheckedAt(Date.now());
} catch (err) {
- if (current === generation.current) showToast(`Couldn't load the reply activity. ${(err as Error).message}`, 'error');
+ // the last good list stays on screen, with the failure shown above it
+ if (current === generation.current) setError(`Couldn't load the reply activity. ${(err as Error).message}`);
} finally {
if (current === generation.current) setLoading(false);
}
- }, [filters, showToast]);
+ }, [filters]);
useEffect(() => { load(); }, [load]);
@@ -101,10 +117,10 @@ export function useAutomationActivity() {
const retryPublic = useCallback((item: AutomationActivityItem) => retryAction(item, 'public'), [retryAction]);
const setFilter = useCallback(<K extends keyof ActivityFilters>(key: K, value: ActivityFilters[K]) => {
- setFilters(current => ({ ...current, [key]: value }));
- }, []);
+ setParams(current => withParam(current, PARAM[key], value, DEFAULTS[key]), { replace: true });
+ }, [setParams]);
- return { filters, setFilter, items, nextBefore, summary, loading, loadingMore, retrying, checkedAt, load, loadMore, retry, retryPublic };
+ return { filters, setFilter, items, nextBefore, summary, loading, loadingMore, retrying, checkedAt, error, load, loadMore, retry, retryPublic };
}
export type AutomationActivityState = ReturnType<typeof useAutomationActivity>;
diff --git a/frontend/src/features/automations/useAutomations.ts b/frontend/src/features/automations/useAutomations.ts
index a8d60ad..b9f30e4 100644
--- a/frontend/src/features/automations/useAutomations.ts
+++ b/frontend/src/features/automations/useAutomations.ts
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from 'react';
import { useAppContext } from '../../context/AppContext';
import { api } from '../../services/api';
+import { deleteWithUndo } from '@/lib/undoToast';
import { formToRequest } from './automationData.ts';
import type { RuleForm } from './automationData.ts';
import type { AutomationAccountState, AutomationOverviewResponse, AutomationRule } from '@shared/types/automation.ts';
@@ -51,16 +52,16 @@ export function useAutomations() {
}
}, [load, replaceRule, showToast]);
+ // the switch moves at once and moves back if the server refuses
const setRuleEnabled = useCallback(async (rule: AutomationRule, enabled: boolean) => {
- setBusyId(rule.id);
+ replaceRule({ ...rule, enabled });
try {
replaceRule((await api.updateAutomationRule(rule.id, { enabled })).rule);
showToast(enabled ? `${rule.name} turned on` : `${rule.name} turned off`);
if (enabled) load();
} catch (err) {
- showToast(`Couldn't ${enabled ? 'turn on' : 'turn off'} the rule. ${(err as Error).message}`, 'error');
- } finally {
- setBusyId(null);
+ replaceRule(rule);
+ showToast(`Couldn't ${enabled ? 'turn on' : 'turn off'} ${rule.name}. ${(err as Error).message}`, 'error');
}
}, [load, replaceRule, showToast]);
@@ -76,30 +77,36 @@ export function useAutomations() {
}
}, [replaceRule, showToast]);
- const deleteRule = useCallback(async (rule: AutomationRule): Promise<boolean> => {
- setBusyId(rule.id);
- try {
- await api.deleteAutomationRule(rule.id);
- setOverview(current => current && { ...current, rules: current.rules.filter(item => item.id !== rule.id) });
- showToast('Rule deleted');
- return true;
- } catch (err) {
- showToast(`Couldn't delete the rule. ${(err as Error).message}`, 'error');
- return false;
- } finally {
- setBusyId(null);
- }
- }, [showToast]);
+ // the rule leaves the list at once; the server delete waits out the Undo window, so Undo needs no restore call
+ const deleteRule = useCallback((rule: AutomationRule) => {
+ const position = overview?.rules.findIndex(item => item.id === rule.id) ?? -1;
+ const restore = () => setOverview(current => {
+ if (!current || current.rules.some(item => item.id === rule.id)) return current;
+ const rules = [...current.rules];
+ rules.splice(position < 0 ? rules.length : Math.min(position, rules.length), 0, rule);
+ return { ...current, rules };
+ });
+ setOverview(current => current && { ...current, rules: current.rules.filter(item => item.id !== rule.id) });
+ deleteWithUndo({
+ id: `rule:${rule.id}`,
+ message: `${rule.name} deleted`,
+ commit: () => api.deleteAutomationRule(rule.id).then(() => undefined),
+ onUndo: restore,
+ onFailure: err => {
+ restore();
+ showToast(`Couldn't delete ${rule.name}. ${err.message}`, 'error');
+ },
+ });
+ }, [overview, showToast]);
const setAccountPaused = useCallback(async (account: AutomationAccountState, paused: boolean) => {
- setBusyId(account.accountId);
+ replaceAccount({ ...account, paused });
try {
replaceAccount((await api.setAutomationAccountPaused(account.accountId, paused)).account);
showToast(paused ? `Replies paused for @${account.username}` : `Replies resumed for @${account.username}`);
} catch (err) {
- showToast(`Couldn't ${paused ? 'pause' : 'resume'} replies. ${(err as Error).message}`, 'error');
- } finally {
- setBusyId(null);
+ replaceAccount(account);
+ showToast(`Couldn't ${paused ? 'pause' : 'resume'} replies for @${account.username}. ${(err as Error).message}`, 'error');
}
}, [replaceAccount, showToast]);
diff --git a/frontend/src/features/automations/useRuleForm.ts b/frontend/src/features/automations/useRuleForm.ts
index 71f68bc..bab5023 100644
--- a/frontend/src/features/automations/useRuleForm.ts
+++ b/frontend/src/features/automations/useRuleForm.ts
@@ -1,69 +1,115 @@
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import type { FormEvent } from 'react';
import { useAppContext } from '../../context/AppContext';
import { api } from '../../services/api';
-import { emptyRuleForm, formToRequest, ruleFormProblem, ruleToForm } from './automationData.ts';
-import type { RuleForm } from './automationData.ts';
-import type { AutomationRule, AutomationTestResponse } from '@shared/types/automation.ts';
+import { clearDraft, readDraft, writeDraft } from '@/lib/sessionDraft';
+import { formToRequest, normalizeLink, ruleFormError } from './automationData.ts';
+import type { RuleField, RuleFieldProblem, RuleForm } from './automationData.ts';
+import type { AutomationTestResponse } from '@shared/types/automation.ts';
import type { InstagramMedia } from '@shared/types/instagram.ts';
// lets a keyword test run before the reply is written
const TEST_REPLY_PLACEHOLDER = 'Your reply';
+// where focus goes for each field's problem
+export const RULE_FIELD_IDS: Record<RuleField, string> = {
+ accountId: 'rule-account',
+ name: 'rule-name',
+ keywordsText: 'rule-keywords',
+ mediaIds: 'rule-posts',
+ replies: 'rule-private',
+ replyText: 'rule-reply',
+ linkUrl: 'rule-link',
+ hourlyLimit: 'rule-limit',
+ publicReplyTexts: 'rule-public-0',
+ requireFollow: 'rule-follow',
+ followPromptText: 'rule-follow-prompt',
+ notFollowingText: 'rule-follow-reminder',
+};
+
interface RuleFormDeps {
+ ruleId: string | null;
+ initialForm: RuleForm;
saveRule: (form: RuleForm, ruleId: string | null) => Promise<boolean>;
+ onSaved: () => void;
+}
+
+function draftKey(ruleId: string | null): string {
+ return `rule:${ruleId ?? 'new'}`;
}
-// the rule dialog: which rule is open, its fields, the account's posts to aim it at, and a test that sends nothing
-export function useRuleForm({ saveRule }: RuleFormDeps) {
+function sameForm(a: RuleForm, b: RuleForm): boolean {
+ return JSON.stringify(a) === JSON.stringify(b);
+}
+
+// the rule editor: its fields with a draft kept for the tab, the account's posts to aim it at, problems shown under
+// their field once a save was tried, and a test that sends nothing
+export function useRuleForm({ ruleId, initialForm, saveRule, onSaved }: RuleFormDeps) {
const { showToast } = useAppContext();
- const [open, setOpen] = useState(false);
- const [ruleId, setRuleId] = useState<string | null>(null);
- const [form, setForm] = useState<RuleForm>(emptyRuleForm(''));
+ const [draft] = useState(() => {
+ const stored = readDraft<RuleForm>(draftKey(ruleId));
+ return stored && stored.accountId === initialForm.accountId ? stored : null;
+ });
+ const [form, setForm] = useState<RuleForm>(() => draft ?? initialForm);
+ const [restored, setRestored] = useState(Boolean(draft) && !sameForm(draft ?? initialForm, initialForm));
+ const [tried, setTried] = useState(false);
const [saving, setSaving] = useState(false);
+ const [saved, setSaved] = useState(false);
const [media, setMedia] = useState<InstagramMedia[]>([]);
const [mediaLoading, setMediaLoading] = useState(false);
+ const [mediaError, setMediaError] = useState<string | null>(null);
+ const [mediaAttempt, setMediaAttempt] = useState(0);
const [sampleComment, setSampleComment] = useState('');
const [testResult, setTestResult] = useState<AutomationTestResponse | null>(null);
const [testing, setTesting] = useState(false);
- const openNew = useCallback((accountId: string) => {
- setRuleId(null);
- setForm(emptyRuleForm(accountId));
- setSampleComment('');
- setTestResult(null);
- setOpen(true);
- }, []);
+ const dirty = !saved && !sameForm(form, initialForm);
+ // a problem shows only after a save was tried, then follows the fields as they change, so it clears once fixed
+ const problem: RuleFieldProblem | null = useMemo(() => (tried ? ruleFormError(form) : null), [tried, form]);
+ const errorFor = useCallback((field: RuleField) => (problem?.field === field ? problem.message : undefined), [problem]);
- const openEdit = useCallback((rule: AutomationRule) => {
- setRuleId(rule.id);
- setForm(ruleToForm(rule));
- setSampleComment('');
- setTestResult(null);
- setOpen(true);
- }, []);
+ useEffect(() => {
+ if (saved) return;
+ if (dirty) writeDraft(draftKey(ruleId), form);
+ else clearDraft(draftKey(ruleId));
+ }, [dirty, form, ruleId, saved]);
const setField = useCallback(<K extends keyof RuleForm>(key: K, value: RuleForm[K]) => {
setForm(current => ({ ...current, [key]: value, ...(key === 'accountId' ? { mediaIds: [] } : {}) }));
setTestResult(null);
}, []);
+ // the address is shown as it will be saved, once the person leaves the field
+ const normalizeLinkField = useCallback(() => {
+ setForm(current => ({ ...current, linkUrl: normalizeLink(current.linkUrl) }));
+ }, []);
+
const toggleMedia = useCallback((id: string) => {
setForm(current => ({ ...current, mediaIds: current.mediaIds.includes(id) ? current.mediaIds.filter(item => item !== id) : [...current.mediaIds, id] }));
setTestResult(null);
}, []);
+ const discardDraft = useCallback(() => {
+ clearDraft(draftKey(ruleId));
+ setForm(initialForm);
+ setRestored(false);
+ setTried(false);
+ }, [initialForm, ruleId]);
+
// posts load only when the rule is aimed at chosen posts
useEffect(() => {
- if (!open || form.scope !== 'selected' || !form.accountId) return;
+ if (form.scope !== 'selected' || !form.accountId) return;
let cancelled = false;
setMediaLoading(true);
+ setMediaError(null);
api.getIGMedia(form.accountId)
.then(res => { if (!cancelled) setMedia(res.media); })
- .catch(err => { if (!cancelled) showToast(`Couldn't load the account's posts. ${(err as Error).message}`, 'error'); })
+ .catch(err => { if (!cancelled) setMediaError(`Couldn't load the account's posts. ${(err as Error).message}`); })
.finally(() => { if (!cancelled) setMediaLoading(false); });
return () => { cancelled = true; };
- }, [open, form.scope, form.accountId, showToast]);
+ }, [form.scope, form.accountId, mediaAttempt]);
+
+ const retryMedia = useCallback(() => setMediaAttempt(attempt => attempt + 1), []);
const runTest = useCallback(async () => {
const request = formToRequest(form);
@@ -84,20 +130,25 @@ export function useRuleForm({ saveRule }: RuleFormDeps) {
const handleSubmit = useCallback(async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
- const problem = ruleFormProblem(form);
- if (problem) {
- showToast(`Couldn't save the rule. ${problem}.`, 'error');
+ if (saving) return;
+ setTried(true);
+ const found = ruleFormError(form);
+ if (found) {
+ document.getElementById(RULE_FIELD_IDS[found.field])?.focus();
return;
}
setSaving(true);
- const saved = await saveRule(form, ruleId);
+ const ok = await saveRule(form, ruleId);
setSaving(false);
- if (saved) setOpen(false);
- }, [form, ruleId, saveRule, showToast]);
+ if (!ok) return;
+ clearDraft(draftKey(ruleId));
+ setSaved(true);
+ onSaved();
+ }, [form, onSaved, ruleId, saveRule, saving]);
return {
- open, setOpen, ruleId, form, setField, toggleMedia, saving, media, mediaLoading,
- sampleComment, setSampleComment, testResult, testing, runTest, openNew, openEdit, handleSubmit,
+ ruleId, form, setField, normalizeLinkField, toggleMedia, saving, dirty, restored, discardDraft, problem, errorFor,
+ media, mediaLoading, mediaError, retryMedia, sampleComment, setSampleComment, testResult, testing, runTest, handleSubmit,
};
}
diff --git a/frontend/src/features/publishing/BulkFileItem.tsx b/frontend/src/features/publishing/BulkFileItem.tsx
index 549ad00..3593a5f 100644
--- a/frontend/src/features/publishing/BulkFileItem.tsx
+++ b/frontend/src/features/publishing/BulkFileItem.tsx
@@ -25,27 +25,27 @@ export default function BulkFileItem({ item, position, processing, onCaptionChan
{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-media-scrim/75 px-1 font-mono text-[0.5625rem] font-semibold text-on-media">{position}</span>
+ <span className="absolute top-0.5 left-0.5 rounded-sm bg-media-scrim/75 px-1 font-mono text-caption font-semibold text-on-media" aria-hidden="true">{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="truncate text-sm font-medium text-ink" title={item.file.name}><span className="sr-only">File {position}: </span>{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>
+ <p className="line-clamp-2 text-small 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.error && <p className="mt-1 text-small text-danger"><span className="sr-only">Error: </span>{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>
+ <Button variant="ghost" size="icon-sm" onClick={() => onRemove(item.id)} aria-label={`Remove ${item.file.name}`}><X /></Button>
)}
</div>
</li>
diff --git a/frontend/src/features/publishing/BulkFileList.tsx b/frontend/src/features/publishing/BulkFileList.tsx
index 8651d0f..fb8b144 100644
--- a/frontend/src/features/publishing/BulkFileList.tsx
+++ b/frontend/src/features/publishing/BulkFileList.tsx
@@ -17,11 +17,11 @@ export default function BulkFileList({ queue, bulkType }: BulkFileListProps) {
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">
+ <Button size="sm" variant="ghost" onClick={queue.clearFiles} className="mr-2 hover:bg-danger-soft hover:text-danger">
<Trash2 data-icon="inline-start" />Clear all
</Button>
)}
- <Button size="sm" variant="outline" onClick={openPicker} disabled={processing}>
+ <Button id={files.length > 0 ? 'bulk-add-files' : undefined} size="sm" variant="outline" onClick={openPicker} disabled={processing}>
<Plus data-icon="inline-start" />Add files
</Button>
</div>
@@ -31,13 +31,14 @@ export default function BulkFileList({ queue, bulkType }: BulkFileListProps) {
<input ref={fileInputRef} type="file" hidden multiple accept={bulkType?.accept || '*'} onChange={queue.handleFilesSelect} aria-label="Files to upload" />
{files.length === 0 ? (
<button
+ id="bulk-add-files"
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" />
+ <FolderUp className="size-8 stroke-[1.5] text-ink-faint" aria-hidden="true" />
<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>
+ <span className="text-small text-ink-muted">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">
diff --git a/frontend/src/features/publishing/BulkScheduleFields.tsx b/frontend/src/features/publishing/BulkScheduleFields.tsx
index cdafb4f..177afb6 100644
--- a/frontend/src/features/publishing/BulkScheduleFields.tsx
+++ b/frontend/src/features/publishing/BulkScheduleFields.tsx
@@ -3,12 +3,13 @@ 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 { fieldErrorId } from '@/lib/fieldIds';
import ScheduleHint from './ScheduleHint';
import ScheduleToggle from './ScheduleToggle';
import { BULK_INTERVAL_OPTIONS } from './publishConstants';
import { bulkScheduledTime } from './publishHelpers.ts';
import { intervalLabel } from './queueHelpers.ts';
-import { utcDateInput } from './scheduleHelpers.ts';
+import { todayInput } from './scheduleHelpers.ts';
import type { BulkSettings } from './publishHelpers.ts';
import type { BulkSettingsState } from './useBulkSettings';
@@ -17,28 +18,54 @@ interface BulkScheduleFieldsProps {
setSetting: BulkSettingsState['setSetting'];
pending: number;
processing: boolean;
+ error?: string;
}
const INTERVAL_ITEMS = BULK_INTERVAL_OPTIONS.map(option => ({ value: String(option.value), label: option.label }));
-function SpreadOutFields({ settings, setSetting, pending, processing }: BulkScheduleFieldsProps) {
+function SpreadOutFields({ settings, setSetting, pending, processing, error }: BulkScheduleFieldsProps) {
const { startDate, startTime, interval } = settings;
const firstPost = new Date(`${startDate}T${startTime}`);
+ const describedBy = error ? fieldErrorId('bulk-when') : undefined;
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" />
+ <FieldRow label="First post date" htmlFor="bulk-date">
+ <Input
+ id="bulk-date"
+ type="date"
+ value={startDate}
+ onChange={e => setSetting('startDate', e.target.value)}
+ min={todayInput()}
+ disabled={processing}
+ aria-describedby={describedBy}
+ aria-invalid={error ? true : undefined}
+ />
+ </FieldRow>
+ <FieldRow label="First post time" htmlFor="bulk-time">
+ <Input
+ id="bulk-time"
+ type="time"
+ value={startTime}
+ onChange={e => setSetting('startTime', e.target.value)}
+ disabled={processing}
+ aria-describedby={describedBy}
+ aria-invalid={error ? true : undefined}
+ />
+ </FieldRow>
</div>
+ {error && <p id={fieldErrorId('bulk-when')} className="-mt-2 text-sm text-danger"><span className="sr-only">Error: </span>{error}</p>}
<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>
+ <FieldRow label="Gap between posts" htmlFor="bulk-interval">
+ <Select value={String(interval)} onValueChange={value => setSetting('interval', Number(value))} disabled={processing} items={INTERVAL_ITEMS}>
+ <SelectTrigger id="bulk-interval" className="w-full"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {BULK_INTERVAL_OPTIONS.map(option => <SelectItem key={option.value} value={String(option.value)}>{option.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FieldRow>
{startDate && startTime && pending > 0 && (
<Alert variant="info">
<Info />
@@ -51,21 +78,22 @@ function SpreadOutFields({ settings, setSetting, pending, processing }: BulkSche
);
}
-export default function BulkScheduleFields({ settings, setSetting, pending, processing }: BulkScheduleFieldsProps) {
- const { scheduleMode } = settings;
+export default function BulkScheduleFields(props: BulkScheduleFieldsProps) {
+ const { settings, setSetting, pending, processing } = props;
return (
<div className="flex flex-col gap-4 border-t border-divider pt-5">
- <FieldRow label="When">
+ <FieldRow label="When" group>
<ScheduleToggle
- scheduled={scheduleMode}
+ name="bulk-when"
+ scheduled={settings.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 && (
+ {settings.scheduleMode && <SpreadOutFields {...props} />}
+ {!settings.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>
diff --git a/frontend/src/features/publishing/BulkSettings.tsx b/frontend/src/features/publishing/BulkSettings.tsx
index 7bbf142..274e4d7 100644
--- a/frontend/src/features/publishing/BulkSettings.tsx
+++ b/frontend/src/features/publishing/BulkSettings.tsx
@@ -1,16 +1,19 @@
-import { AtSign, Calendar, Copy, MapPin, Send, Square, UserPlus } from 'lucide-react';
+import { useState } from 'react';
+import { AtSign, Calendar, ChevronRight, 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 { fieldErrorId } from '@/lib/fieldIds';
import AccountSelect from '@/components/AccountSelect';
import BulkScheduleFields from './BulkScheduleFields';
import IconInput from './IconInput';
import TypePicker from './TypePicker';
+import { PublishHelp } from './SinglePostSettings';
import { bulkActionLabel } from './queueHelpers.ts';
import type { AppAccount } from '../../utils/formatters';
import type { BulkSettings as BulkSettingsValues } from './publishHelpers.ts';
+import type { BulkField } from './publishHelpers.ts';
import type { BulkSettingsState } from './useBulkSettings';
interface BulkFooterProps {
@@ -19,6 +22,7 @@ interface BulkFooterProps {
processing: boolean;
onStart: () => void;
onStop: () => void;
+ error?: string;
}
interface BulkSettingsProps {
@@ -29,63 +33,86 @@ interface BulkSettingsProps {
onStart: () => void;
onStop: () => void;
onApplyCaption: () => void;
+ errorFor: (field: BulkField) => string | undefined;
}
-function BulkFooter({ settings, pending, processing, onStart, onStop }: BulkFooterProps) {
+// the start button stays enabled; pressing it with something missing says what, next to that field
+function BulkFooter({ settings, pending, processing, onStart, onStop, error }: BulkFooterProps) {
if (processing) {
return (
- <Button variant="destructive" size="lg" className="w-full" onClick={onStop}>
- <Square data-icon="inline-start" />Stop after this file
- </Button>
+ <div className="flex flex-col gap-2">
+ <Button variant="destructive" size="lg" className="w-full" onClick={onStop}>
+ <Square data-icon="inline-start" />Stop after this file
+ </Button>
+ <p className="text-small text-ink-muted">Stay on this page until the files are done. Leaving stops the uploads.</p>
+ </div>
);
}
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>
+ <div className="flex flex-col gap-2">
+ {error && <p className="text-sm text-danger" role="alert"><span className="sr-only">Error: </span>{error}</p>}
+ <Button id="bulk-start" size="lg" className="w-full" onClick={onStart}>
+ {settings.scheduleMode ? <Calendar data-icon="inline-start" /> : <Send data-icon="inline-start" />}
+ {pending === 0 ? (settings.scheduleMode ? 'Schedule posts' : 'Publish posts') : bulkActionLabel(settings.scheduleMode, pending)}
+ </Button>
+ <PublishHelp />
+ </div>
);
}
-export default function BulkSettings({ bulk, igAccounts, pending, processing, onStart, onStop, onApplyCaption }: BulkSettingsProps) {
+export default function BulkSettings({ bulk, igAccounts, pending, processing, onStart, onStop, onApplyCaption, errorFor }: BulkSettingsProps) {
const { settings, setSetting } = bulk;
- const footer = <BulkFooter settings={settings} pending={pending} processing={processing} onStart={onStart} onStop={onStop} />;
+ const [moreOpen, setMoreOpen] = useState(() => Boolean(settings.collaborators || settings.userTags || settings.locationId));
+ const footerError = errorFor('files') ?? errorFor('server');
+ const footer = <BulkFooter settings={settings} pending={pending} processing={processing} onStart={onStart} onStop={onStop} error={footerError} />;
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 label="Account" htmlFor="bulk-account" error={errorFor('account')}>
+ <AccountSelect id="bulk-account" accounts={igAccounts} value={settings.account} onChange={value => setSetting('account', value)} disabled={processing} />
</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 label="What you are posting" htmlFor="bulk-type-group" group error={errorFor('contentType')}>
+ <TypePicker
+ id="bulk-type"
+ name="bulk-type"
+ value={settings.contentType}
+ onChange={value => setSetting('contentType', value)}
+ disabled={processing}
+ aria-describedby={errorFor('contentType') ? fieldErrorId('bulk-type-group') : undefined}
+ />
</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 label="Shared caption" optional hint="Write it once, then copy it onto every file that has not gone out yet. Undo puts back captions it replaced." htmlFor="bulk-caption">
+ <Textarea id="bulk-caption" value={settings.sharedCaption} onChange={e => setSetting('sharedCaption', e.target.value)} placeholder="Caption for all files" rows={2} disabled={processing} />
</FieldRow>
+ <Button variant="outline" size="sm" className="-mt-3 self-start" onClick={onApplyCaption} disabled={!settings.sharedCaption || processing}>
+ <Copy data-icon="inline-start" />Apply to pending files
+ </Button>
+
+ <details className="group flex flex-col" open={moreOpen} onToggle={e => setMoreOpen(e.currentTarget.open)}>
+ <summary className="flex cursor-pointer list-none items-center gap-1.5 rounded-control text-sm font-medium text-ink select-none [&::-webkit-details-marker]:hidden">
+ <ChevronRight className="size-4 text-ink-muted transition-transform duration-(--duration-base) group-open:rotate-90" aria-hidden="true" />
+ More options: collaborators, tagged people, location
+ </summary>
+ <div className="mt-4 flex flex-col gap-5">
+ <FieldRow label="Collaborators" optional hint="Applied to every post. User names separated by commas; an @ or a profile link works too." 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" optional hint="Applied to every post. User names separated by commas." 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" optional hint="Applied to every post. The ID of the place's Facebook Page, from the About section of that Page." htmlFor="bulk-location">
+ <IconInput id="bulk-location" icon={MapPin} inputMode="numeric" value={settings.locationId} onChange={e => setSetting('locationId', e.target.value.trim())} placeholder="Facebook Page ID" disabled={processing} />
+ </FieldRow>
+ </div>
+ </details>
+
{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" />
+ <label htmlFor="bulk-share-to-feed" className="text-sm font-medium text-ink">Share Reels to feed</label>
+ <Switch id="bulk-share-to-feed" checked={settings.shareToFeed} onCheckedChange={checked => setSetting('shareToFeed', checked)} disabled={processing} />
</div>
)}
- <BulkScheduleFields settings={settings} setSetting={setSetting} pending={pending} processing={processing} />
+ <BulkScheduleFields settings={settings} setSetting={setSetting} pending={pending} processing={processing} error={errorFor('schedule')} />
</DetailPanel>
);
}
diff --git a/frontend/src/features/publishing/BulkUploadTab.tsx b/frontend/src/features/publishing/BulkUploadTab.tsx
index ee0beff..c276d33 100644
--- a/frontend/src/features/publishing/BulkUploadTab.tsx
+++ b/frontend/src/features/publishing/BulkUploadTab.tsx
@@ -33,6 +33,7 @@ export default function BulkUploadTab({ bulk, queue, bulkPublish, igAccounts }:
onStart={bulkPublish.handleBulkProcess}
onStop={bulkPublish.stopBulk}
onApplyCaption={queue.applySharedCaption}
+ errorFor={bulkPublish.errorFor}
/>
</div>
);
diff --git a/frontend/src/features/publishing/CaptionBox.tsx b/frontend/src/features/publishing/CaptionBox.tsx
index bd99b55..deff129 100644
--- a/frontend/src/features/publishing/CaptionBox.tsx
+++ b/frontend/src/features/publishing/CaptionBox.tsx
@@ -11,7 +11,7 @@ interface CaptionBoxProps {
export default function CaptionBox({ caption, onChange }: CaptionBoxProps) {
const nearLimit = caption.length > CAPTION_LIMIT * 0.9;
return (
- <SurfaceBox title="Caption">
+ <SurfaceBox title="Caption" subheader="Kept in this tab as you type, so a reload does not lose it.">
<Textarea
value={caption}
onChange={e => onChange(e.target.value)}
@@ -19,10 +19,11 @@ export default function CaptionBox({ caption, onChange }: CaptionBoxProps) {
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"
+ aria-describedby="caption-count"
+ className="min-h-40 rounded-control border-0 bg-transparent px-1 text-base leading-6 shadow-none hover:border-0"
/>
- <p className={cn('mt-2 text-right text-caption tabular-nums', nearLimit ? 'text-warning' : 'text-ink-faint')}>
- {caption.length.toLocaleString()} / {CAPTION_LIMIT.toLocaleString()}
+ <p id="caption-count" className={cn('mt-2 text-right text-caption tabular-nums', nearLimit ? 'text-warning' : 'text-ink-faint')}>
+ {caption.length.toLocaleString()} of {CAPTION_LIMIT.toLocaleString()} characters
</p>
</SurfaceBox>
);
diff --git a/frontend/src/features/publishing/MediaPicker.tsx b/frontend/src/features/publishing/MediaPicker.tsx
index f0328f6..ac65be9 100644
--- a/frontend/src/features/publishing/MediaPicker.tsx
+++ b/frontend/src/features/publishing/MediaPicker.tsx
@@ -1,6 +1,9 @@
+import { useEffect, useRef } from 'react';
import { Upload, X } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import SurfaceBox from '@/components/SurfaceBox';
+import { FieldRow } from '@/components/DetailPanel';
+import { fieldErrorId } from '@/lib/fieldIds';
import { cn } from '@/lib/utils';
import TypePicker from './TypePicker';
import { fileSizeMb, isVideoFile } from './queueHelpers.ts';
@@ -17,6 +20,8 @@ interface MediaPreviewProps {
interface MediaPickerProps {
form: SinglePostForm;
selectedType: ContentTypeOption | undefined;
+ typeError?: string;
+ fileError?: string;
}
function MediaPreview({ file, filePreview, selectedType, onClear }: MediaPreviewProps) {
@@ -26,19 +31,19 @@ function MediaPreview({ file, filePreview, selectedType, onClear }: MediaPreview
{isVideoFile(file) ? (
<video src={filePreview} controls muted className="max-h-72 w-full bg-media-scrim object-contain" />
) : (
- <img src={filePreview} alt="Selected media preview" className="max-h-72 w-full object-contain" />
+ <img src={filePreview} alt="Preview of the chosen photo" 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-media-scrim/75 text-on-media transition-colors hover:bg-brand"
+ aria-label={`Remove ${file.name}`}
+ className="absolute top-2 right-2 flex size-8 items-center justify-center rounded-full bg-media-scrim/75 text-on-media transition-colors hover:bg-brand focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
>
- <X className="size-3.5" />
+ <X className="size-4" aria-hidden="true" />
</button>
</div>
<div className="min-w-0">
- <p className="truncate text-sm font-semibold text-ink">{file.name}</p>
+ <p className="truncate text-sm font-semibold text-ink" title={file.name}>{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>
@@ -46,29 +51,52 @@ function MediaPreview({ file, filePreview, selectedType, onClear }: MediaPreview
);
}
-export default function MediaPicker({ form, selectedType }: MediaPickerProps) {
+export default function MediaPicker({ form, selectedType, typeError, fileError }: MediaPickerProps) {
const { contentType, file, fileInputRef } = form;
+ const hadFile = useRef(Boolean(file));
+
+ // removing the file removes the focused button, so focus moves to the button that picks a new one
+ useEffect(() => {
+ if (hadFile.current && !file) document.getElementById('post-file')?.focus();
+ hadFile.current = Boolean(file);
+ }, [file]);
+
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} />
+ <FieldRow label="What you are posting" htmlFor="post-type-group" group error={typeError}>
+ <TypePicker
+ id="post-type"
+ name="post-type"
+ value={contentType}
+ onChange={form.changeContentType}
+ aria-describedby={typeError ? fieldErrorId('post-type-group') : undefined}
+ />
+ </FieldRow>
{file ? (
<MediaPreview file={file} filePreview={form.filePreview as string} 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>
+ <div className="flex flex-col gap-2">
+ <button
+ id="post-file"
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ disabled={!contentType}
+ aria-describedby={[fileError ? fieldErrorId('post-file') : '', 'post-file-help'].filter(Boolean).join(' ')}
+ aria-invalid={fileError ? true : undefined}
+ 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',
+ fileError && 'border-danger',
+ )}
+ >
+ <Upload className="size-8 stroke-[1.5] text-ink-faint" aria-hidden="true" />
+ <span className="text-sm font-medium text-ink">{contentType ? 'Choose a file' : 'Choose what you are posting first'}</span>
+ <span id="post-file-help" className="text-small text-ink-muted">{selectedType ? selectedType.desc : 'Photo, Reel or Story, above.'}</span>
+ </button>
+ {fileError && <p id={fieldErrorId('post-file')} className="text-sm text-danger"><span className="sr-only">Error: </span>{fileError}</p>}
+ </div>
)}
<input ref={fileInputRef} type="file" hidden accept={selectedType?.accept || '*'} onChange={form.handleFileSelect} aria-label="Media file" />
</div>
diff --git a/frontend/src/features/publishing/NoInstagramAccount.tsx b/frontend/src/features/publishing/NoInstagramAccount.tsx
index 4d64333..a9fdc10 100644
--- a/frontend/src/features/publishing/NoInstagramAccount.tsx
+++ b/frontend/src/features/publishing/NoInstagramAccount.tsx
@@ -15,7 +15,7 @@ export default function NoInstagramAccount() {
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>}
+ action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add account</Button>}
/>
</SurfaceBox>
</div>
diff --git a/frontend/src/features/publishing/PublishProgress.tsx b/frontend/src/features/publishing/PublishProgress.tsx
index 590f7bb..551d6fe 100644
--- a/frontend/src/features/publishing/PublishProgress.tsx
+++ b/frontend/src/features/publishing/PublishProgress.tsx
@@ -1,33 +1,67 @@
-import { Upload } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { Square, Upload } from 'lucide-react';
+import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { Spinner } from '@/components/ui/spinner';
import SurfaceBox from '@/components/SurfaceBox';
import PublishResult from './PublishResult';
+import { EXPECTED_PROCESSING_SECONDS, MAX_PROCESSING_SECONDS } from './containerPolling.ts';
import { progressHeading } from './queueHelpers.ts';
import type { PublishStatus } from './queueHelpers.ts';
import type { PublishResultProps } from './PublishResult';
const WORKING_STATUSES: PublishStatus[] = ['creating-container', 'publishing', 'scheduling', 'processing'];
-export default function PublishProgress({ progress, ...resultProps }: PublishResultProps) {
+interface PublishProgressProps extends PublishResultProps {
+ onStopWaiting: () => void;
+}
+
+// seconds since Instagram started processing, so a long wait shows it is still moving and how long is normal
+function useElapsedSeconds(running: boolean): number {
+ const [seconds, setSeconds] = useState(0);
+ useEffect(() => {
+ if (!running) return;
+ const startedAt = Date.now();
+ const timer = setInterval(() => setSeconds(Math.floor((Date.now() - startedAt) / 1000)), 1000);
+ return () => {
+ clearInterval(timer);
+ setSeconds(0);
+ };
+ }, [running]);
+ return seconds;
+}
+
+// the visible progress; the page announces each stage through its own live region, so this block is not one
+export default function PublishProgress({ progress, onStopWaiting, ...resultProps }: PublishProgressProps) {
const { publishStatus, statusMessage, uploadProgress } = progress;
+ const processing = publishStatus === 'processing';
+ const elapsed = useElapsedSeconds(processing);
return (
<SurfaceBox>
- <div role="status" className="flex flex-col items-center gap-3 py-10 text-center">
+ <div 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" />
+ <Upload className="size-10 stroke-[1.5] text-ink-muted" aria-hidden="true" />
<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>
+ <p className="text-small text-ink-muted tabular-nums" aria-hidden="true">{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>}
+ <p className="max-w-prose text-small text-ink-muted">{statusMessage}</p>
+ {processing && (
+ <>
+ <p className="text-small text-ink-muted tabular-nums">
+ Waiting {elapsed} seconds. Usually under {EXPECTED_PROCESSING_SECONDS} seconds; Twiligent waits up to {MAX_PROCESSING_SECONDS}.
+ </p>
+ <Button variant="outline" size="sm" onClick={onStopWaiting}>
+ <Square data-icon="inline-start" />Stop waiting
+ </Button>
+ </>
+ )}
</>
)}
<PublishResult progress={progress} {...resultProps} />
diff --git a/frontend/src/features/publishing/PublishResult.tsx b/frontend/src/features/publishing/PublishResult.tsx
index 841fa10..56bdd41 100644
--- a/frontend/src/features/publishing/PublishResult.tsx
+++ b/frontend/src/features/publishing/PublishResult.tsx
@@ -1,3 +1,5 @@
+import { useEffect, useRef } from 'react';
+import type { ReactNode } from 'react';
import { AlertCircle, Calendar, CheckCircle2, ExternalLink, Plus } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -13,21 +15,28 @@ export interface PublishResultProps {
onReset: () => void;
}
+// the form that held focus is gone, so the outcome's heading takes it and a screen reader reads the result
+function ResultHeading({ children }: { children: ReactNode }) {
+ const ref = useRef<HTMLHeadingElement>(null);
+ useEffect(() => { ref.current?.focus(); }, []);
+ return <h2 ref={ref} tabIndex={-1} className="font-heading text-section font-semibold text-ink outline-none">{children}</h2>;
+}
+
export default function PublishResult({ progress, selectedType, selectedAcct, scheduleMode, onReset }: PublishResultProps) {
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>
+ <span className="flex size-12 items-center justify-center rounded-full bg-success-soft text-success"><CheckCircle2 className="size-6" aria-hidden="true" /></span>
+ <ResultHeading>Published</ResultHeading>
<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">
+ <div className="mt-2 flex flex-wrap justify-center 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
+ <ExternalLink data-icon="inline-start" />View profile<span className="sr-only"> (opens in a new tab)</span>
</Button>
)}
</div>
@@ -38,10 +47,10 @@ export default function PublishResult({ progress, selectedType, selectedAcct, sc
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>
+ <span className="flex size-12 items-center justify-center rounded-full bg-warning-soft text-warning"><Calendar className="size-6" aria-hidden="true" /></span>
+ <ResultHeading>Post scheduled</ResultHeading>
<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>
+ <p className="max-w-md text-small text-ink-muted">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>
</>
);
@@ -51,10 +60,11 @@ export default function PublishResult({ progress, selectedType, selectedAcct, sc
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>
+ <span className="flex size-12 items-center justify-center rounded-full bg-danger-soft text-danger"><AlertCircle className="size-6" aria-hidden="true" /></span>
+ <ResultHeading><span className="sr-only">Error: </span>{scheduleMode ? 'Scheduling failed' : 'Publishing failed'}</ResultHeading>
<p className="max-w-md text-sm text-ink-muted">{statusMessage}</p>
- <div className="mt-2 flex gap-2">
+ <p className="max-w-md text-small text-ink-muted">Your file, caption and settings are kept. Try again goes back to them.</p>
+ <div className="mt-2 flex flex-wrap justify-center 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.tsx b/frontend/src/features/publishing/ReelOptions.tsx
index 0e01ec4..146f6f3 100644
--- a/frontend/src/features/publishing/ReelOptions.tsx
+++ b/frontend/src/features/publishing/ReelOptions.tsx
@@ -12,12 +12,12 @@ interface ReelOptionsProps {
function CoverPicker({ form }: ReelOptionsProps) {
const { coverFile, coverInputRef } = form;
return (
- <FieldRow label="Cover image" hint="Optional JPEG.">
+ <FieldRow label="Cover image" optional hint="A JPEG shown before the Reel plays.">
{coverFile ? (
<div className="flex items-center gap-3 rounded-control border border-line p-2">
- <img src={form.coverPreview as string} 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>
+ <img src={form.coverPreview as string} alt="Chosen cover" className="size-10 rounded-sm object-cover" />
+ <span className="min-w-0 flex-1 truncate text-small text-ink" title={coverFile.name}>{coverFile.name}</span>
+ <Button variant="ghost" size="icon-sm" onClick={form.clearCover} aria-label={`Remove the cover ${coverFile.name}`}><X /></Button>
</div>
) : (
<Button variant="outline" onClick={() => coverInputRef.current?.click()} className="justify-start">
@@ -35,16 +35,24 @@ export default function ReelOptions({ form }: ReelOptionsProps) {
<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>
+ <label htmlFor="share-to-feed" className="text-sm font-medium text-ink">Share to feed</label>
+ <p id="share-to-feed-hint" className="text-small text-ink-muted">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" />
+ <Switch id="share-to-feed" checked={fields.shareToFeed} onCheckedChange={checked => setField('shareToFeed', checked)} aria-describedby="share-to-feed-hint" />
</div>
- <FieldRow label="Audio name" hint="Optional" htmlFor="audio-name">
+ <FieldRow label="Audio name" 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 label="Thumbnail time" optional hint="Seconds into the video for the frame shown as the thumbnail, such as 2.5." htmlFor="thumb-offset">
+ <IconInput
+ id="thumb-offset"
+ icon={Clock}
+ type="text"
+ inputMode="decimal"
+ 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.tsx b/frontend/src/features/publishing/ScheduleFields.tsx
index c88f0a7..822bbad 100644
--- a/frontend/src/features/publishing/ScheduleFields.tsx
+++ b/frontend/src/features/publishing/ScheduleFields.tsx
@@ -1,28 +1,51 @@
import { Input } from '@/components/ui/input';
import { FieldRow } from '@/components/DetailPanel';
+import { fieldErrorId } from '@/lib/fieldIds';
import ScheduleHint from './ScheduleHint';
import ScheduleToggle from './ScheduleToggle';
-import { utcDateInput } from './scheduleHelpers.ts';
+import { todayInput } from './scheduleHelpers.ts';
import type { SinglePostFields } from './publishHelpers.ts';
import type { SinglePostForm } from './useSinglePostForm';
interface ScheduleFieldsProps {
fields: SinglePostFields;
setField: SinglePostForm['setField'];
+ error?: string;
}
-export default function ScheduleFields({ fields, setField }: ScheduleFieldsProps) {
+export default function ScheduleFields({ fields, setField, error }: ScheduleFieldsProps) {
+ const describedBy = error ? fieldErrorId('post-when') : undefined;
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 label="When" group>
+ <ScheduleToggle name="post-when" 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" />
+ <FieldRow label="Date" htmlFor="post-date">
+ <Input
+ id="post-date"
+ type="date"
+ value={fields.scheduleDate}
+ onChange={e => setField('scheduleDate', e.target.value)}
+ min={todayInput()}
+ aria-describedby={describedBy}
+ aria-invalid={error ? true : undefined}
+ />
+ </FieldRow>
+ <FieldRow label="Time" htmlFor="post-time">
+ <Input
+ id="post-time"
+ type="time"
+ value={fields.scheduleTime}
+ onChange={e => setField('scheduleTime', e.target.value)}
+ aria-describedby={describedBy}
+ aria-invalid={error ? true : undefined}
+ />
+ </FieldRow>
</div>
+ {error && <p id={fieldErrorId('post-when')} className="-mt-2 text-sm text-danger"><span className="sr-only">Error: </span>{error}</p>}
<ScheduleHint />
</>
)}
diff --git a/frontend/src/features/publishing/ScheduleHint.tsx b/frontend/src/features/publishing/ScheduleHint.tsx
index 2754610..846277f 100644
--- a/frontend/src/features/publishing/ScheduleHint.tsx
+++ b/frontend/src/features/publishing/ScheduleHint.tsx
@@ -2,9 +2,9 @@ import { Link } from 'react-router-dom';
export default function ScheduleHint() {
return (
- <p className="text-caption text-ink-faint">
+ <p className="max-w-prose text-small text-ink-muted">
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>
+ <Link to="/settings#scheduling" className="font-medium text-brand-text underline underline-offset-4">How scheduling works</Link>
</p>
);
}
diff --git a/frontend/src/features/publishing/ScheduleToggle.tsx b/frontend/src/features/publishing/ScheduleToggle.tsx
index d040368..915592f 100644
--- a/frontend/src/features/publishing/ScheduleToggle.tsx
+++ b/frontend/src/features/publishing/ScheduleToggle.tsx
@@ -1,7 +1,8 @@
import { Calendar, Send } from 'lucide-react';
-import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import SegmentedChoice from '@/components/SegmentedChoice';
interface ScheduleToggleProps {
+ name: string;
scheduled: boolean;
onChange: (scheduled: boolean) => void;
disabled?: boolean;
@@ -9,13 +10,21 @@ interface ScheduleToggleProps {
laterLabel?: string;
}
-export default function ScheduleToggle({ scheduled, onChange, disabled, nowLabel = 'Publish now', laterLabel = 'Schedule' }: ScheduleToggleProps) {
+type When = 'now' | 'later';
+
+// a choice between two values, so it is a pair of radio buttons rather than tabs without panels
+export default function ScheduleToggle({ name, scheduled, onChange, disabled, nowLabel = 'Publish now', laterLabel = 'Schedule' }: ScheduleToggleProps) {
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>
+ <SegmentedChoice<When>
+ name={name}
+ className="sm:w-full"
+ options={[
+ { value: 'now', label: nowLabel, icon: <Send /> },
+ { value: 'later', label: laterLabel, icon: <Calendar /> },
+ ]}
+ value={scheduled ? 'later' : 'now'}
+ onChange={value => onChange(value === 'later')}
+ disabled={disabled}
+ />
);
}
diff --git a/frontend/src/features/publishing/ScheduledPostDialogs.tsx b/frontend/src/features/publishing/ScheduledPostDialogs.tsx
index 63801ee..aab8e33 100644
--- a/frontend/src/features/publishing/ScheduledPostDialogs.tsx
+++ b/frontend/src/features/publishing/ScheduledPostDialogs.tsx
@@ -5,34 +5,19 @@ interface ScheduledPostDialogsProps {
removal: ScheduledPostRemoval;
}
+// deleting one post has Undo instead; deleting every post cannot be undone, so it asks first
export default function ScheduledPostDialogs({ removal }: ScheduledPostDialogsProps) {
- 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={Boolean(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
- />
- </>
+ <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 posts"
+ busyLabel="Deleting"
+ onConfirm={removal.handleDeleteAll}
+ busy={removal.deleting}
+ hold
+ />
);
}
diff --git a/frontend/src/features/publishing/ScheduledPostEditRow.tsx b/frontend/src/features/publishing/ScheduledPostEditRow.tsx
index 0ffd95c..04c7a39 100644
--- a/frontend/src/features/publishing/ScheduledPostEditRow.tsx
+++ b/frontend/src/features/publishing/ScheduledPostEditRow.tsx
@@ -4,8 +4,9 @@ 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 { FieldRow } from '@/components/DetailPanel';
import { CAPTION_LIMIT } from './publishConstants';
-import { utcDateInput } from './scheduleHelpers.ts';
+import { todayInput } from './scheduleHelpers.ts';
import type { ScheduledPostEditor } from './useScheduledPostEdit';
interface ScheduledPostEditRowProps {
@@ -17,21 +18,32 @@ export default function ScheduledPostEditRow({ editor }: ScheduledPostEditRowPro
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" />
+ <form
+ noValidate
+ onSubmit={e => { e.preventDefault(); editor.handleSaveEdit(); }}
+ onKeyDown={e => { if (e.key === 'Escape') editor.cancelEdit(); }}
+ className="flex flex-col gap-3 p-4"
+ >
+ <FieldRow label="Caption" htmlFor="edit-post-caption" hint={`${draft.caption.length.toLocaleString()} of ${CAPTION_LIMIT.toLocaleString()} characters`}>
+ <Textarea id="edit-post-caption" value={draft.caption} onChange={e => setDraftField('caption', e.target.value)} rows={3} maxLength={CAPTION_LIMIT} autoFocus />
+ </FieldRow>
+ <div className="flex flex-wrap gap-3">
+ <FieldRow label="Date" htmlFor="edit-post-date" error={editor.errorFor('date')} className="w-44">
+ <Input id="edit-post-date" type="date" value={draft.date} onChange={e => setDraftField('date', e.target.value)} min={todayInput()} />
+ </FieldRow>
+ <FieldRow label="Time" htmlFor="edit-post-time" error={editor.errorFor('time')} className="w-44">
+ <Input id="edit-post-time" type="time" value={draft.time} onChange={e => setDraftField('time', e.target.value)} />
+ </FieldRow>
</div>
+ {editor.saveError && <p className="text-sm text-danger" role="alert"><span className="sr-only">Error: </span>{editor.saveError}</p>}
<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}>
+ <Button type="button" size="sm" variant="outline" onClick={editor.cancelEdit}>Cancel</Button>
+ <Button type="submit" size="sm" disabled={savingEdit}>
{savingEdit ? <Spinner className="size-3.5" /> : <CheckCircle2 data-icon="inline-start" />}
{savingEdit ? 'Saving' : 'Save changes'}
</Button>
</div>
- </div>
+ </form>
</TableCell>
</TableRow>
);
diff --git a/frontend/src/features/publishing/ScheduledPostRow.tsx b/frontend/src/features/publishing/ScheduledPostRow.tsx
index df83033..730446f 100644
--- a/frontend/src/features/publishing/ScheduledPostRow.tsx
+++ b/frontend/src/features/publishing/ScheduledPostRow.tsx
@@ -8,6 +8,7 @@ import ScheduledPostEditRow from './ScheduledPostEditRow';
import StatusBadge from './StatusBadge';
import { POST_STATUS, contentTypeOf } from './publishConstants';
import { formatScheduleDate, isPastDue, isRetrying } from './scheduleHelpers.ts';
+import { editButtonId } from './useScheduledPostEdit';
import type { ScheduledPost } from '@shared/types/domain.ts';
import type { AppAccount } from '../../utils/formatters';
import type { ScheduledPostEditor } from './useScheduledPostEdit';
@@ -27,21 +28,23 @@ interface ScheduledPostRowProps {
onDelete: (post: ScheduledPost) => void;
}
+// every row has the same buttons, so each name says which post it acts on
function PostActions({ post, isEditing, editor, onDelete }: PostActionsProps) {
const canEdit = post.status === 'pending';
- const deleteLabel = post.status === 'published' ? 'Remove record' : 'Delete scheduled post';
+ const when = formatScheduleDate(post.scheduledAt);
+ const deleteLabel = post.status === 'published' ? `Remove the record of the post published ${formatScheduleDate(post.publishedAt)}` : `Delete the post scheduled for ${when}`;
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>
+ <TooltipTrigger render={<Button id={editButtonId(post.id)} variant="ghost" size="icon-sm" onClick={() => editor.startEditPost(post)} aria-label={`Edit the post scheduled for ${when}`} />}><Pencil /></TooltipTrigger>
<TooltipContent>Edit</TooltipContent>
</Tooltip>
)}
- {isEditing && <Button variant="ghost" size="icon-xs" onClick={editor.cancelEdit} aria-label="Cancel editing"><X /></Button>}
+ {isEditing && <Button variant="ghost" size="icon-sm" 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>
+ <TooltipTrigger render={<Button variant="ghost" size="icon-sm" onClick={() => onDelete(post)} aria-label={deleteLabel} className="ml-2 hover:bg-danger-soft hover:text-danger" />}><Trash2 /></TooltipTrigger>
<TooltipContent>{post.status === 'published' ? 'Remove record' : 'Delete'}</TooltipContent>
</Tooltip>
)}
@@ -60,45 +63,37 @@ export default function ScheduledPostRow({ post, position, account, editor, onDe
<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" />}
+ {account && <AccountAvatar account={account} size="xs" decorative />}
<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>
+ <span className="flex items-center gap-1.5 text-small text-ink-muted"><TypeIcon className="size-3.5" aria-hidden="true" />{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 className="whitespace-normal">
+ <p className="line-clamp-3 max-w-64 text-small break-words text-ink-muted" title={post.caption || undefined}>{post.caption || 'No caption'}</p>
</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 className="flex flex-col text-small text-ink-muted">
+ <span className="flex items-center gap-1">
+ {formatScheduleDate(post.publishedAt)}
+ {post.publishedMediaId && <CheckCircle2 className="size-3.5 text-success" aria-hidden="true" />}
+ </span>
+ {post.publishedMediaId && <span className="font-mono text-caption text-ink-faint">Media ID {post.publishedMediaId}</span>}
</span>
</TableCell>
<TableCell>
<StatusBadge status={post.status} map={POST_STATUS} />
{isRetrying(post) && <p className="mt-1 text-caption text-ink-faint">Trying again on the next run</p>}
</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 className="whitespace-normal">
+ {post.error
+ ? <p className="max-w-64 text-small break-words text-danger"><span className="sr-only">Error: </span>{post.error}</p>
+ : <span className="text-ink-faint">-</span>}
</TableCell>
<PostActions post={post} isEditing={isEditing} editor={editor} onDelete={onDelete} />
</TableRow>
diff --git a/frontend/src/features/publishing/ScheduledPostsSection.tsx b/frontend/src/features/publishing/ScheduledPostsSection.tsx
index 73d79ee..3bfccfb 100644
--- a/frontend/src/features/publishing/ScheduledPostsSection.tsx
+++ b/frontend/src/features/publishing/ScheduledPostsSection.tsx
@@ -1,9 +1,12 @@
-import { Calendar, RefreshCw, Trash2 } from 'lucide-react';
+import { AlertCircle, Calendar, RefreshCw, Trash2 } from 'lucide-react';
+import { Alert, AlertAction, AlertDescription } from '@/components/ui/alert';
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 LiveStatus from '@/components/LiveStatus';
+import { cn } from '@/lib/utils';
import OverdueAlert from './OverdueAlert';
import ScheduledPostRow from './ScheduledPostRow';
import { filterScheduledPosts, overduePostsOf, scheduledStatusChips } from './scheduleHelpers.ts';
@@ -46,17 +49,28 @@ export default function ScheduledPostsSection({ schedule, editor, removal, igAcc
<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>
+ <p className="max-w-prose 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>
+ <Button size="sm" variant="outline" onClick={schedule.loadScheduledPosts} disabled={schedule.loading}>
+ <RefreshCw data-icon="inline-start" className={cn(schedule.loading && 'animate-spin')} />
+ {schedule.loading ? 'Refreshing' : 'Refresh'}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={() => removal.setConfirmDeleteAll(true)} className="ml-3 hover:bg-danger-soft hover:text-danger"><Trash2 data-icon="inline-start" />Delete all</Button>
</div>
</div>
+ {schedule.loadError && (
+ <Alert variant="destructive" role="alert">
+ <AlertCircle />
+ <AlertDescription><span className="sr-only">Error: </span>{schedule.loadError}</AlertDescription>
+ <AlertAction><Button size="sm" variant="outline" onClick={schedule.loadScheduledPosts}>Try again</Button></AlertAction>
+ </Alert>
+ )}
+ <LiveStatus message={`${filteredScheduled.length} ${filteredScheduled.length === 1 ? 'post' : 'posts'} shown`} />
{overdueCount > 0 && <OverdueAlert count={overdueCount} />}
<FilterChips label="Status" options={scheduledStatusChips(scheduledPosts)} value={statusFilter} onChange={schedule.setStatusFilter} />
<SurfaceBox content={false} className="overflow-hidden">
- <Table>
+ <Table aria-label="Scheduled posts">
<ScheduledPostsHeader />
<TableBody>
{filteredScheduled.map((post, index) => (
@@ -66,13 +80,19 @@ export default function ScheduledPostsSection({ schedule, editor, removal, igAcc
position={index + 1}
account={igAccounts.find(account => account.id === post.accountId)}
editor={editor}
- onDelete={removal.setPendingDelete}
+ onDelete={removal.deleteScheduled}
/>
))}
{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." />
+ <EmptyState
+ compact
+ icon={<Calendar />}
+ title={`No ${statusFilter} posts`}
+ description="Choose another status to see other posts."
+ action={<Button size="sm" variant="outline" onClick={() => schedule.setStatusFilter('all')}>Show all posts</Button>}
+ />
</TableCell>
</TableRow>
)}
diff --git a/frontend/src/features/publishing/SinglePostSettings.tsx b/frontend/src/features/publishing/SinglePostSettings.tsx
index c065a69..667d744 100644
--- a/frontend/src/features/publishing/SinglePostSettings.tsx
+++ b/frontend/src/features/publishing/SinglePostSettings.tsx
@@ -1,8 +1,10 @@
-import { AtSign, Calendar, Image as ImageIcon, MapPin, Send, UserPlus } from 'lucide-react';
+import { useState } from 'react';
+import { AtSign, Calendar, ChevronRight, 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 '@/components/AccountSelect';
+import { docsUrl } from '@/lib/docs';
import IconInput from './IconInput';
import PostSummary from './PostSummary';
import ReelOptions from './ReelOptions';
@@ -31,38 +33,76 @@ function PublishButtonIcon({ uploading, scheduleMode }: PublishButtonIconProps)
return <Send data-icon="inline-start" />;
}
+// what Publish needs and the platform's limit, next to the button rather than at the bottom of the page
+export function PublishHelp() {
+ return (
+ <p className="text-small text-ink-muted">
+ Instagram allows 100 posts per account in 24 hours.{' '}
+ <a href={docsUrl('/use/publishing')} target="_blank" rel="noopener noreferrer" className="font-medium text-brand-text underline underline-offset-4">
+ How publishing works<span className="sr-only"> (opens in a new tab)</span>
+ </a>
+ </p>
+ );
+}
+
export default function SinglePostSettings({ form, publish, igAccounts, selectedAcct, selectedType }: SinglePostSettingsProps) {
const { fields, setField, contentType } = form;
+ // the rarely used fields start open when one of them already holds a value, such as a restored draft
+ const [moreOpen, setMoreOpen] = useState(() => Boolean(fields.collaborators || fields.userTags || fields.locationId));
+ const serverError = publish.errorFor('server');
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>
+ <div className="flex flex-col gap-2">
+ {serverError && <p className="text-sm text-danger" role="alert"><span className="sr-only">Error: </span>{serverError}</p>}
+ <Button id="post-publish" size="lg" className="w-full" onClick={publish.handlePublish} disabled={publish.uploading}>
+ <PublishButtonIcon uploading={publish.uploading} scheduleMode={fields.scheduleMode} />
+ {publish.uploading ? (fields.scheduleMode ? 'Scheduling' : 'Publishing') : fields.scheduleMode ? 'Schedule post' : 'Publish now'}
+ </Button>
+ <PublishHelp />
+ </div>
);
return (
<DetailPanel title="Post settings" footer={footer}>
- <FieldRow label="Account">
- <AccountSelect accounts={igAccounts} value={form.selectedAccount} onChange={form.setSelectedAccount} />
+ <FieldRow label="Account" htmlFor="post-account" error={publish.errorFor('account')}>
+ <AccountSelect id="post-account" 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">
+ <FieldRow label="Alt text" optional hint="Describes the photo for people who use a screen reader." 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>
+
+ <details className="group flex flex-col" open={moreOpen} onToggle={e => setMoreOpen(e.currentTarget.open)}>
+ <summary className="flex cursor-pointer list-none items-center gap-1.5 rounded-control text-sm font-medium text-ink select-none [&::-webkit-details-marker]:hidden">
+ <ChevronRight className="size-4 text-ink-muted transition-transform duration-(--duration-base) group-open:rotate-90" aria-hidden="true" />
+ More options: collaborators, tagged people, location
+ </summary>
+ <div className="mt-4 flex flex-col gap-5">
+ <FieldRow label="Collaborators" optional hint="Instagram user names, separated by commas. An @ or a profile link works too." 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"
+ optional
+ hint="User names, separated by commas. Tags sit in the middle of the photo; to place one, add two numbers from 0 to 1 after the name, across then down, such as @ann 0.2 0.8."
+ 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"
+ optional
+ hint="Instagram identifies a place by the ID of its Facebook Page. Open the place's Facebook Page, choose About, and copy the Page ID."
+ htmlFor="location-id"
+ >
+ <IconInput id="location-id" icon={MapPin} inputMode="numeric" value={fields.locationId} onChange={e => setField('locationId', e.target.value.trim())} placeholder="Facebook Page ID" />
+ </FieldRow>
+ </div>
+ </details>
{contentType === 'REELS' && <ReelOptions form={form} />}
- <ScheduleFields fields={fields} setField={setField} />
+ <ScheduleFields fields={fields} setField={setField} error={publish.errorFor('schedule')} />
<PostSummary selectedAcct={selectedAcct} selectedType={selectedType} file={form.file} fields={fields} />
</DetailPanel>
diff --git a/frontend/src/features/publishing/SinglePostTab.tsx b/frontend/src/features/publishing/SinglePostTab.tsx
index e71a42e..fafdd5f 100644
--- a/frontend/src/features/publishing/SinglePostTab.tsx
+++ b/frontend/src/features/publishing/SinglePostTab.tsx
@@ -26,6 +26,7 @@ export default function SinglePostTab({ form, publish, igAccounts, onReset }: Si
selectedAcct={selectedAcct}
scheduleMode={form.fields.scheduleMode}
onReset={onReset}
+ onStopWaiting={publish.stopWaiting}
/>
);
}
@@ -33,7 +34,7 @@ export default function SinglePostTab({ form, publish, igAccounts, onReset }: Si
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} />
+ <MediaPicker form={form} selectedType={selectedType} typeError={publish.errorFor('contentType')} fileError={publish.errorFor('file')} />
<CaptionBox caption={form.fields.caption} onChange={caption => form.setField('caption', caption)} />
</div>
<SinglePostSettings
diff --git a/frontend/src/features/publishing/TypePicker.tsx b/frontend/src/features/publishing/TypePicker.tsx
index d3bf021..eb7e2d1 100644
--- a/frontend/src/features/publishing/TypePicker.tsx
+++ b/frontend/src/features/publishing/TypePicker.tsx
@@ -1,38 +1,31 @@
-import { cn } from '@/lib/utils';
+import SegmentedChoice from '@/components/SegmentedChoice';
import { CONTENT_TYPES } from './publishConstants';
import type { ContentTypeValue } from './publishHelpers.ts';
interface TypePickerProps {
+ id: string;
+ name: string;
value: ContentTypeValue | '';
onChange: (value: ContentTypeValue) => void;
disabled?: boolean;
+ 'aria-describedby'?: string;
}
-export default function TypePicker({ value, onChange, disabled }: TypePickerProps) {
+// native radios: one tab stop, arrow keys between the types, and the legend of the surrounding fieldset names it
+export default function TypePicker({ id, name, value, onChange, disabled, ...aria }: TypePickerProps) {
return (
- <div role="radiogroup" aria-label="Content type" className="grid grid-cols-3 gap-2">
- {CONTENT_TYPES.map(type => {
+ <SegmentedChoice<ContentTypeValue | ''>
+ id={id}
+ name={name}
+ variant="tiles"
+ options={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>
- );
+ return { value: type.value, label: type.label, icon: <Icon /> };
})}
- </div>
+ value={value}
+ onChange={next => { if (next) onChange(next); }}
+ disabled={disabled}
+ {...aria}
+ />
);
}
diff --git a/frontend/src/features/publishing/UploadContent.tsx b/frontend/src/features/publishing/UploadContent.tsx
index f764b7a..72e22e5 100644
--- a/frontend/src/features/publishing/UploadContent.tsx
+++ b/frontend/src/features/publishing/UploadContent.tsx
@@ -1,11 +1,15 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
-import { AlertCircle, FolderUp, Plus, Upload } from 'lucide-react';
-import { Alert, AlertDescription } from '@/components/ui/alert';
+import { AlertCircle, FolderUp, History, Upload } from 'lucide-react';
+import { Alert, AlertAction, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import ConfirmDialog from '@/components/ConfirmDialog';
+import LiveStatus from '@/components/LiveStatus';
import PageHeader from '@/components/PageHeader';
+import { useUnsavedChanges } from '@/hooks/use-unsaved-changes';
+import { useUrlChoice } from '@/hooks/use-url-state';
import { useAppContext } from '../../context/AppContext';
import { useCloudinaryConfig } from '../../hooks/use-cloudinary-config';
import BulkUploadTab from './BulkUploadTab';
@@ -13,6 +17,7 @@ import NoInstagramAccount from './NoInstagramAccount';
import ScheduledPostDialogs from './ScheduledPostDialogs';
import ScheduledPostsSection from './ScheduledPostsSection';
import SinglePostTab from './SinglePostTab';
+import { progressHeading } from './queueHelpers.ts';
import { useBulkPublish } from './useBulkPublish';
import { useBulkQueue } from './useBulkQueue';
import { useBulkSettings } from './useBulkSettings';
@@ -22,18 +27,27 @@ import { useScheduledPosts } from './useScheduledPosts';
import { useSinglePostForm } from './useSinglePostForm';
import { useSinglePublish } from './useSinglePublish';
import type { AppAccount } from '../../utils/formatters';
+import type { PublishStatus } from './queueHelpers.ts';
type UploadMode = 'single' | 'bulk';
+const UPLOAD_MODES: UploadMode[] = ['single', 'bulk'];
+
+// what the page's live region says at each stage; the end states are read from the result heading instead
+function stageAnnouncement(status: PublishStatus, uploading: boolean): string {
+ if (status === 'uploading-cloudinary') return 'Uploading media';
+ if (status === 'creating-container' || status === 'processing' || status === 'publishing' || status === 'scheduling') return progressHeading(status);
+ return uploading ? 'Working' : '';
+}
export default function UploadContent() {
const { accounts, showToast } = useAppContext();
const cloudConfig = useCloudinaryConfig(accounts);
const [igAccounts, setIgAccounts] = useState<AppAccount[]>([]);
- const [uploadMode, setUploadMode] = useState<UploadMode>('single');
+ const [uploadMode, setUploadMode] = useUrlChoice<UploadMode>('mode', UPLOAD_MODES, 'single');
const schedule = useScheduledPosts();
const { loadScheduledPosts } = schedule;
const editor = useScheduledPostEdit({ showToast, loadScheduledPosts });
- const removal = useScheduledPostDelete({ showToast, loadScheduledPosts });
+ const removal = useScheduledPostDelete({ showToast, loadScheduledPosts, hidePost: schedule.hidePost, showPost: schedule.showPost });
const form = useSinglePostForm();
const { setSelectedAccount } = form;
const publish = useSinglePublish({ form, cloudConfig, showToast, onScheduled: loadScheduledPosts });
@@ -41,6 +55,12 @@ export default function UploadContent() {
const queue = useBulkQueue({ sharedCaption: bulk.settings.sharedCaption, onFirstFiles: bulk.applyFirstBatchDefaults });
const bulkPublish = useBulkPublish({ queue, settings: bulk.settings, cloudConfig, showToast, onScheduled: loadScheduledPosts });
+ // work in progress or typed and not yet sent; leaving would stop the uploads or drop the files
+ const running = publish.uploading || queue.processing;
+ const singleUnsent = form.dirty && publish.activeStep !== 2;
+ const bulkUnsent = queue.files.some(item => item.status === 'pending');
+ const guard = useUnsavedChanges(running || singleUnsent || bulkUnsent || editor.dirty);
+
useEffect(() => {
const instagramAccounts = (accounts || []).filter(account => account.platform === 'instagram');
// eslint-disable-next-line react-hooks/set-state-in-effect
@@ -51,36 +71,40 @@ export default function UploadContent() {
const resetAll = () => {
form.resetForm();
- publish.resetProgress();
+ publish.reset();
};
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={publish.publishStatus === 'done' && uploadMode === 'single' && (
- <Button onClick={resetAll}><Plus data-icon="inline-start" />Publish another</Button>
- )}
- />
+ <PageHeader title="Publish" description="Post and schedule photos, Reels and Stories to Instagram." />
+ <LiveStatus message={stageAnnouncement(publish.publishStatus, publish.uploading)} />
{!cloudConfig && (
<Alert variant="warning">
<AlertCircle />
<AlertDescription>
- Uploads need Cloudinary, which is not set up on the server. Instagram only accepts media from a public URL. Set the Cloudinary environment variables, then check the status in <Link to="/settings" className="font-semibold underline">Settings</Link>.
+ Uploads need Cloudinary, which is not set up on the server. Instagram only accepts media from a public URL. Set the Cloudinary environment variables, then check the status in <Link to="/settings#server-keys" className="font-semibold underline underline-offset-4">Settings</Link>.
</AlertDescription>
</Alert>
)}
- <Tabs value={uploadMode} onValueChange={setUploadMode} className="gap-6">
+ {form.restored && publish.activeStep !== 2 && (
+ <Alert variant="info">
+ <History />
+ <AlertTitle>Your caption and settings are back</AlertTitle>
+ <AlertDescription>They were kept from earlier in this tab. Choose the file again to post them.</AlertDescription>
+ <AlertAction><Button size="sm" variant="outline" onClick={resetAll}>Discard them</Button></AlertAction>
+ </Alert>
+ )}
+
+ <Tabs value={uploadMode} onValueChange={value => setUploadMode(value as UploadMode)} className="gap-6">
<TabsList>
<TabsTrigger value="single"><Upload />Single post</TabsTrigger>
<TabsTrigger value="bulk">
<FolderUp />Bulk upload
- {queue.files.length > 0 && <Badge variant="solid" className="h-4 px-1.5">{queue.files.length}</Badge>}
+ {queue.files.length > 0 && <Badge variant="solid" className="h-4 px-1.5"><span className="sr-only">, </span>{queue.files.length}<span className="sr-only"> files</span></Badge>}
</TabsTrigger>
</TabsList>
@@ -93,15 +117,26 @@ export default function UploadContent() {
</TabsContent>
</Tabs>
- {schedule.scheduledPosts.length > 0 && (
+ {(schedule.scheduledPosts.length > 0 || schedule.loadError) && (
<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>
-
<ScheduledPostDialogs removal={removal} />
+ <ConfirmDialog
+ open={guard.blocked}
+ onOpenChange={open => { if (!open) guard.stay(); }}
+ title={running ? 'Leave while posts are uploading?' : 'Leave without posting?'}
+ description={running
+ ? 'Leaving stops the files that have not started. A file that is uploading or publishing right now may still finish, and files that already went out keep their status.'
+ : 'Chosen files are not kept. A typed caption and settings stay in this tab and come back when you return.'}
+ cancelLabel="Stay on this page"
+ confirmLabel="Leave"
+ onConfirm={() => {
+ bulkPublish.stopBulk();
+ publish.stopWaiting();
+ guard.leave();
+ }}
+ />
</div>
);
}
diff --git a/frontend/src/features/publishing/containerPolling.ts b/frontend/src/features/publishing/containerPolling.ts
index b7656ba..4bb3d71 100644
--- a/frontend/src/features/publishing/containerPolling.ts
+++ b/frontend/src/features/publishing/containerPolling.ts
@@ -4,8 +4,8 @@ import type { MediaType } from '../../../../shared/types/domain.ts';
// tolerant polling survives failed status checks, so it must report each status it sees
export type ContainerWaitOptions =
- | { tolerant: true; onStatus: (message: string) => void }
- | { tolerant?: false; onStatus?: undefined };
+ | { tolerant: true; onStatus: (message: string) => void; signal?: AbortSignal }
+ | { tolerant?: false; onStatus?: undefined; signal?: AbortSignal };
export type ReadyOptions = ContainerWaitOptions & { onProcessing: () => void };
@@ -13,31 +13,71 @@ const POLL_ATTEMPTS = 30;
const POLL_INTERVAL_MS = 3000;
const IMAGE_SETTLE_MS = 2000;
-export function wait(ms: number): Promise<void> {
- return new Promise(resolve => setTimeout(resolve, ms));
+// how long a video usually takes, shown next to the time already waited
+export const EXPECTED_PROCESSING_SECONDS = 60;
+export const MAX_PROCESSING_SECONDS = (POLL_ATTEMPTS * POLL_INTERVAL_MS) / 1000;
+
+export const STOPPED_MESSAGE = 'You stopped waiting, so the post was not published. Publish again to try once more.';
+
+// Instagram said the media cannot be used, so asking again will not help
+export class ContainerFailedError extends Error {}
+
+export class WaitStoppedError extends Error {
+ constructor() {
+ super(STOPPED_MESSAGE);
+ }
+}
+
+// what Instagram's status code means for the person waiting
+export function containerStatusMessage(statusCode: string | undefined): string {
+ if (statusCode === 'FINISHED' || statusCode === 'PUBLISHED') return 'Instagram finished processing the media.';
+ return 'Instagram is still processing the media. Videos usually take under a minute.';
+}
+
+export function wait(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(new WaitStoppedError());
+ return;
+ }
+ const timer = setTimeout(() => {
+ signal?.removeEventListener('abort', stop);
+ resolve();
+ }, ms);
+ function stop() {
+ clearTimeout(timer);
+ reject(new WaitStoppedError());
+ }
+ signal?.addEventListener('abort', stop, { once: true });
+ });
}
-function containerFinished(status: Pick<InstagramContainerStatusResponse, 'statusCode'>, failedMessage: string): boolean {
+function containerFinished(status: Pick<InstagramContainerStatusResponse, 'statusCode' | 'status'>): boolean {
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');
+ if (status.statusCode === 'ERROR') {
+ const reason = status.status ? ` Instagram said: ${status.status}.` : '';
+ throw new ContainerFailedError(`Instagram couldn't process the media.${reason} Try a shorter MP4 video (H.264 with AAC audio), or try again.`);
+ }
+ if (status.statusCode === 'EXPIRED') {
+ throw new ContainerFailedError('Instagram discarded the upload because it waited too long before publishing. Publish again.');
+ }
return false;
}
async function pollTolerant(containerId: string, accountId: string, onStatus: (message: string) => void): Promise<boolean> {
try {
const status = await api.getIGContainerStatus(containerId, accountId);
- onStatus(`Instagram status: ${status.statusCode || 'IN_PROGRESS'}`);
- return containerFinished(status, 'Container processing failed: ' + (status.status || 'Unknown'));
+ onStatus(containerStatusMessage(status.statusCode));
+ return containerFinished(status);
} catch (err) {
- if ((err as Error).message.includes('processing failed') || (err as Error).message.includes('expired')) throw err;
+ if (err instanceof ContainerFailedError) throw err;
return false;
}
}
async function pollStrict(containerId: string, accountId: string): Promise<boolean> {
const status = await api.getIGContainerStatus(containerId, accountId);
- return containerFinished(status, 'Processing failed');
+ return containerFinished(status);
}
// publishing an unfinished container fails, so running out of attempts is an error in both modes
@@ -45,13 +85,13 @@ export async function waitForContainer(
containerId: string, accountId: string, options: ContainerWaitOptions = {},
): Promise<void> {
for (let i = 0; i < POLL_ATTEMPTS; i++) {
- await wait(POLL_INTERVAL_MS);
+ await wait(POLL_INTERVAL_MS, options.signal);
const finished = options.tolerant
? await pollTolerant(containerId, accountId, options.onStatus)
: await pollStrict(containerId, accountId);
if (finished) return;
}
- throw new Error('Instagram took too long to process the media. Try again in a few minutes.');
+ throw new Error('Instagram took longer than 90 seconds to process the media. Wait a few minutes, then publish again.');
}
// photos need no processing, only a moment before Instagram can publish them
@@ -59,7 +99,7 @@ export async function waitUntilReady(
contentType: MediaType | '', containerId: string, accountId: string, { onProcessing, ...pollOptions }: ReadyOptions,
): Promise<void> {
if (contentType !== 'REELS' && contentType !== 'STORIES') {
- await wait(IMAGE_SETTLE_MS);
+ await wait(IMAGE_SETTLE_MS, pollOptions.signal);
return;
}
onProcessing();
diff --git a/frontend/src/features/publishing/publishHelpers.ts b/frontend/src/features/publishing/publishHelpers.ts
index 918699d..e1ea50c 100644
--- a/frontend/src/features/publishing/publishHelpers.ts
+++ b/frontend/src/features/publishing/publishHelpers.ts
@@ -91,8 +91,21 @@ export function parseUserTags(text: string): UserTag[] {
}).filter(tag => tag.username);
}
+// a name may be typed as @name or pasted as a profile address; Instagram wants the bare user name
+export function instagramUsername(text: string): string {
+ const name = text.trim();
+ const fromUrl = name.match(/instagram\.com\/([^/?#\s]+)/i);
+ return (fromUrl ? fromUrl[1] : name).replace(/^@/, '').trim();
+}
+
export function parseCollaborators(text: string): string[] {
- return text.split(',').map(name => name.trim()).filter(Boolean);
+ return text.split(',').map(instagramUsername).filter(Boolean);
+}
+
+// the field takes seconds, as people think of a video, with a dot or a comma; Instagram takes milliseconds
+export function thumbOffsetMs(seconds: string | undefined): number | null {
+ const value = Number.parseFloat((seconds ?? '').trim().replace(',', '.'));
+ return Number.isFinite(value) && value >= 0 ? Math.round(value * 1000) : null;
}
export function buildScheduledPostPayload(post: ScheduledPostDetails): ScheduledPostRequest {
@@ -108,7 +121,7 @@ export function buildScheduledPostPayload(post: ScheduledPostDetails): Scheduled
shareToFeed: mediaType === 'REELS' ? shareToFeed : true,
collaborators: collaborators ? parseCollaborators(collaborators) : [],
audioName: audioName || '',
- thumbOffset: thumbOffset ? parseInt(thumbOffset, 10) : null,
+ thumbOffset: thumbOffsetMs(thumbOffset),
locationId: locationId || '',
userTags: userTags ? parseUserTags(userTags) : [],
altText: (mediaType === 'IMAGE' && altText) ? altText : '',
@@ -127,7 +140,7 @@ export function buildContainerPayload(post: PostDetails): InstagramPublishReques
shareToFeed: mediaType === 'REELS' ? shareToFeed : undefined,
collaborators: collaborators ? parseCollaborators(collaborators) : undefined,
audioName: audioName || undefined,
- thumbOffset: thumbOffset ? parseInt(thumbOffset, 10) : undefined,
+ thumbOffset: thumbOffsetMs(thumbOffset) ?? undefined,
locationId: locationId || undefined,
userTags: userTags ? parseUserTags(userTags) : undefined,
altText: (mediaType === 'IMAGE' && altText) ? altText : undefined,
@@ -154,6 +167,45 @@ export function singleUploadMessage(err: UploadFailure): string {
return err.message;
}
+export type SinglePostField = 'account' | 'contentType' | 'file' | 'server' | 'schedule';
+export type BulkField = 'account' | 'contentType' | 'files' | 'server' | 'schedule';
+export type EditPostField = 'date' | 'time';
+
+export interface FieldProblem<F extends string> {
+ field: F;
+ message: string;
+}
+
+// the first thing missing before a single post can go out and the field it belongs to, or null
+export function singlePostProblem({ selectedAccount, file, contentType, hasCloudConfig, fields, now }: SinglePostCheck): FieldProblem<SinglePostField> | null {
+ if (!selectedAccount) return { field: 'account', message: 'Choose the Instagram account to post to.' };
+ if (!contentType) return { field: 'contentType', message: 'Choose what you are posting: a photo, a Reel or a Story.' };
+ if (!file) return { field: 'file', message: 'Choose the file to post.' };
+ if (!hasCloudConfig) return { field: 'server', message: 'Uploads are not set up on this server yet. The administrator needs to add the Cloudinary settings.' };
+ if (!fields.scheduleMode) return null;
+ if (!fields.scheduleDate || !fields.scheduleTime) return { field: 'schedule', message: 'Set the date and time to publish the post.' };
+ if (new Date(`${fields.scheduleDate}T${fields.scheduleTime}`) <= now) return { field: 'schedule', message: 'Pick a time in the future.' };
+ return null;
+}
+
+export function bulkStartProblem({ settings, fileCount, hasCloudConfig, now }: BulkStartCheck): FieldProblem<BulkField> | null {
+ if (fileCount === 0) return { field: 'files', message: 'Add at least one file.' };
+ if (!settings.account) return { field: 'account', message: 'Choose the Instagram account to post to.' };
+ if (!settings.contentType) return { field: 'contentType', message: 'Choose what you are posting: photos, Reels or Stories.' };
+ if (!hasCloudConfig) return { field: 'server', message: 'Uploads are not set up on this server yet. The administrator needs to add the Cloudinary settings.' };
+ if (settings.scheduleMode && (!settings.startDate || !settings.startTime)) return { field: 'schedule', message: 'Set the date and time of the first post.' };
+ const baseTime = bulkBaseTime(settings);
+ if (baseTime && baseTime <= now) return { field: 'schedule', message: 'Pick a start time in the future.' };
+ return null;
+}
+
+export function editPostProblem({ postId, date, time, now }: EditPostCheck): FieldProblem<EditPostField> | null {
+ if (!postId || !date) return { field: 'date', message: 'Set the date.' };
+ if (!time) return { field: 'time', message: 'Set the time.' };
+ if (new Date(`${date}T${time}`) <= now) return { field: 'time', message: 'Pick a time in the future.' };
+ return null;
+}
+
export function singlePostError({ selectedAccount, file, contentType, hasCloudConfig, fields, now }: SinglePostCheck): string {
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.';
diff --git a/frontend/src/features/publishing/scheduleHelpers.ts b/frontend/src/features/publishing/scheduleHelpers.ts
index 1990e83..1f8e32e 100644
--- a/frontend/src/features/publishing/scheduleHelpers.ts
+++ b/frontend/src/features/publishing/scheduleHelpers.ts
@@ -87,15 +87,15 @@ export function toLocalTimeInput(date: Date): string {
return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
-// known issue: date inputs use the UTC calendar day, not the local one
-export function utcDateInput(date: Date = new Date()): string {
- return date.toISOString().split('T')[0];
+// the earliest day a date input allows; the time is read as local time, so the day must be the local one too
+export function todayInput(now: Date = new Date()): string {
+ return toLocalDateInput(now);
}
export function defaultBulkStartDate(now: Date = new Date()): string {
const tomorrow = new Date(now);
tomorrow.setDate(tomorrow.getDate() + 1);
- return utcDateInput(tomorrow);
+ return toLocalDateInput(tomorrow);
}
export function goesLiveLabel({ scheduleMode, scheduleDate, scheduleTime }: ScheduleFieldValues): string {
diff --git a/frontend/src/features/publishing/singlePostFlow.ts b/frontend/src/features/publishing/singlePostFlow.ts
index dcc9657..375af9b 100644
--- a/frontend/src/features/publishing/singlePostFlow.ts
+++ b/frontend/src/features/publishing/singlePostFlow.ts
@@ -60,18 +60,19 @@ export async function scheduleSinglePost(
}
export async function publishSinglePost(
- form: SinglePostInput, cloudConfig: CloudinaryUploadConfig | null, progress: PublishProgressSetters,
+ form: SinglePostInput, cloudConfig: CloudinaryUploadConfig | null, progress: PublishProgressSetters, signal?: AbortSignal,
): Promise<string> {
const uploaded = await uploadPostMedia(form, cloudConfig, progress);
progress.setPublishStatus('creating-container');
- progress.setStatusMessage('Creating the Instagram media container');
+ progress.setStatusMessage('Sending the post to Instagram');
const { containerId } = await api.createIGContainer(form.selectedAccount, buildContainerPayload(postDetails(form, uploaded)));
await waitUntilReady(form.contentType, containerId, form.selectedAccount, {
tolerant: true,
+ signal,
onStatus: progress.setStatusMessage,
onProcessing: () => {
progress.setPublishStatus('processing');
- progress.setStatusMessage('Instagram is processing the media');
+ progress.setStatusMessage('Instagram is processing the media. Videos usually take under a minute.');
},
});
progress.setPublishStatus('publishing');
diff --git a/frontend/src/features/publishing/useBulkPublish.ts b/frontend/src/features/publishing/useBulkPublish.ts
index 69fdfde..cc77d6a 100644
--- a/frontend/src/features/publishing/useBulkPublish.ts
+++ b/frontend/src/features/publishing/useBulkPublish.ts
@@ -1,11 +1,12 @@
+import { useState } from 'react';
import { api } from '../../services/api';
import { waitUntilReady, wait } from './containerPolling.ts';
import {
- buildContainerPayload, buildScheduledPostPayload, bulkBaseTime, bulkPostDetails, bulkScheduledTime, bulkStartError,
+ buildContainerPayload, buildScheduledPostPayload, bulkBaseTime, bulkPostDetails, bulkScheduledTime, bulkStartProblem,
} from './publishHelpers.ts';
import type { CloudinaryUploadConfig } from '../../services/api';
import type { AppContextValue } from '../../context/AppContext';
-import type { BulkSettings } from './publishHelpers.ts';
+import type { BulkField, BulkSettings } from './publishHelpers.ts';
import type { QueueItem, QueueItemPatch } from './queueHelpers.ts';
import type { BulkQueue } from './useBulkQueue';
@@ -17,7 +18,12 @@ export interface BulkPublishOptions {
onScheduled: () => void;
}
-// cloudConfig is set and baseTime is set in schedule mode once bulkStartError passes
+// where focus goes for each problem
+const BULK_FIELD_IDS: Record<BulkField, string> = {
+ files: 'bulk-add-files', account: 'bulk-account', contentType: 'bulk-type', server: 'bulk-start', schedule: 'bulk-date',
+};
+
+// cloudConfig is set and baseTime is set in schedule mode once bulkStartProblem passes
interface BulkRun {
settings: BulkSettings;
cloudConfig: CloudinaryUploadConfig | null;
@@ -93,14 +99,22 @@ async function runQueue(run: BulkRun, pendingFiles: QueueItem[]): Promise<QueueT
export function useBulkPublish({ queue, settings, cloudConfig, showToast, onScheduled }: BulkPublishOptions) {
const { cancelRef } = queue;
+ const [tried, setTried] = useState(false);
+ const pendingCount = queue.files.filter(item => item.status === 'pending').length;
+ // shown once a start was tried, then it follows the settings so it clears as soon as they are right
+ const problem = tried ? bulkStartProblem({ settings, fileCount: pendingCount, hasCloudConfig: Boolean(cloudConfig), now: new Date() }) : null;
+ const errorFor = (field: BulkField) => (problem?.field === field ? problem.message : undefined);
// 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: Boolean(cloudConfig), now: new Date() });
- if (error) {
- showToast(error, 'error');
+ if (queue.processing) return;
+ setTried(true);
+ const found = bulkStartProblem({ settings, fileCount: pendingCount, hasCloudConfig: Boolean(cloudConfig), now: new Date() });
+ if (found) {
+ document.getElementById(BULK_FIELD_IDS[found.field])?.focus();
return;
}
+ setTried(false);
const baseTime = bulkBaseTime(settings);
queue.setProcessing(true);
cancelRef.current = false;
@@ -120,7 +134,7 @@ export function useBulkPublish({ queue, settings, cloudConfig, showToast, onSche
cancelRef.current = true;
};
- return { handleBulkProcess, stopBulk };
+ return { handleBulkProcess, stopBulk, errorFor };
}
export type BulkPublish = ReturnType<typeof useBulkPublish>;
diff --git a/frontend/src/features/publishing/useBulkQueue.ts b/frontend/src/features/publishing/useBulkQueue.ts
index b9454a3..179dac3 100644
--- a/frontend/src/features/publishing/useBulkQueue.ts
+++ b/frontend/src/features/publishing/useBulkQueue.ts
@@ -1,5 +1,7 @@
import { useRef, useState } from 'react';
import type { ChangeEvent } from 'react';
+import { toast } from 'sonner';
+import { UNDO_WINDOW_MS } from '@/lib/undoToast';
import {
applyCaptionToPending, newQueueItem, patchQueueItem, removeQueueItem, revokePreview,
} from './queueHelpers.ts';
@@ -32,16 +34,38 @@ export function useBulkQueue({ sharedCaption, onFirstFiles }: BulkQueueOptions)
const patchFile = (id: number, patch: QueueItemPatch) => setFiles(prev => patchQueueItem(prev, id, patch));
+ // overwriting typed captions is easy to do by accident, so the old ones come back with Undo
const applySharedCaption = () => {
if (!sharedCaption) return;
+ const before = files;
+ const pending = files.filter(item => item.status === 'pending').length;
+ const typed = files.filter(item => item.status === 'pending' && item.caption && item.caption !== sharedCaption).length;
setFiles(prev => applyCaptionToPending(prev, sharedCaption));
+ toast.success(`Caption applied to ${pending} pending ${pending === 1 ? 'file' : 'files'}${typed ? `, replacing ${typed} typed ${typed === 1 ? 'caption' : 'captions'}` : ''}`, {
+ duration: UNDO_WINDOW_MS,
+ action: { label: 'Undo', onClick: () => setFiles(current => current.map(item => before.find(old => old.id === item.id && item.status === 'pending') ?? item)) },
+ });
};
+ // the list comes back with Undo; previews are released only once the Undo window has passed
const clearFiles = () => {
- files.forEach(revokePreview);
+ const cleared = files;
setFiles([]);
setProcessing(false);
cancelRef.current = false;
+ let restored = false;
+ const release = setTimeout(() => { if (!restored) cleared.forEach(revokePreview); }, UNDO_WINDOW_MS + 1000);
+ toast.success(`${cleared.length} ${cleared.length === 1 ? 'file' : 'files'} cleared`, {
+ duration: UNDO_WINDOW_MS,
+ action: {
+ label: 'Undo',
+ onClick: () => {
+ restored = true;
+ clearTimeout(release);
+ setFiles(current => [...cleared, ...current]);
+ },
+ },
+ });
};
return {
diff --git a/frontend/src/features/publishing/useScheduledPostDelete.ts b/frontend/src/features/publishing/useScheduledPostDelete.ts
index 95cd068..42ddc54 100644
--- a/frontend/src/features/publishing/useScheduledPostDelete.ts
+++ b/frontend/src/features/publishing/useScheduledPostDelete.ts
@@ -1,4 +1,5 @@
import { useState } from 'react';
+import { deleteWithUndo } from '@/lib/undoToast';
import { api } from '../../services/api';
import { deleteAllMessage } from './scheduleHelpers.ts';
import type { ScheduledPost } from '@shared/types/domain.ts';
@@ -7,29 +8,35 @@ import type { AppContextValue } from '../../context/AppContext';
export interface ScheduledPostActionOptions {
showToast: AppContextValue['showToast'];
loadScheduledPosts: () => Promise<void>;
+ hidePost: (id: string) => void;
+ showPost: (id: string) => void;
}
-export function useScheduledPostDelete({ showToast, loadScheduledPosts }: ScheduledPostActionOptions) {
- const [pendingDelete, setPendingDelete] = useState<ScheduledPost | null>(null);
+export function useScheduledPostDelete({ showToast, loadScheduledPosts, hidePost, showPost }: ScheduledPostActionOptions) {
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 as Error).message}`, 'error');
- } finally {
- setDeleting(false);
- setPendingDelete(null);
- }
+ // one post leaves the list at once and is deleted after the Undo window, so a slip costs nothing
+ const deleteScheduled = (post: ScheduledPost) => {
+ const published = post.status === 'published';
+ hidePost(post.id);
+ deleteWithUndo({
+ id: `scheduled:${post.id}`,
+ message: published ? 'Record removed. The post stays on Instagram.' : 'Scheduled post deleted',
+ commit: async () => {
+ await api.deleteScheduledPost(post.id);
+ await loadScheduledPosts();
+ },
+ onUndo: () => showPost(post.id),
+ onFailure: err => {
+ showPost(post.id);
+ showToast(`Couldn't delete the post. ${err.message}`, 'error');
+ },
+ });
};
const handleDeleteAll = async () => {
+ if (deleting) return;
setDeleting(true);
try {
const res = await api.deleteAllScheduledPosts();
@@ -43,10 +50,7 @@ export function useScheduledPostDelete({ showToast, loadScheduledPosts }: Schedu
}
};
- return {
- pendingDelete, setPendingDelete, confirmDeleteAll, setConfirmDeleteAll, deleting,
- handleDeleteScheduled, handleDeleteAll,
- };
+ return { confirmDeleteAll, setConfirmDeleteAll, deleting, deleteScheduled, handleDeleteAll };
}
export type ScheduledPostRemoval = ReturnType<typeof useScheduledPostDelete>;
diff --git a/frontend/src/features/publishing/useScheduledPostEdit.ts b/frontend/src/features/publishing/useScheduledPostEdit.ts
index 5609dfd..e1e3ee6 100644
--- a/frontend/src/features/publishing/useScheduledPostEdit.ts
+++ b/frontend/src/features/publishing/useScheduledPostEdit.ts
@@ -1,9 +1,10 @@
import { useState } from 'react';
import { api } from '../../services/api';
-import { editPostError } from './publishHelpers.ts';
+import { editPostProblem } from './publishHelpers.ts';
import { toLocalDateInput, toLocalTimeInput } from './scheduleHelpers.ts';
import type { ScheduledPost } from '@shared/types/domain.ts';
-import type { ScheduledPostActionOptions } from './useScheduledPostDelete';
+import type { AppContextValue } from '../../context/AppContext';
+import type { EditPostField, FieldProblem } from './publishHelpers.ts';
export interface EditDraft {
postId: string | null;
@@ -12,43 +13,81 @@ export interface EditDraft {
time: string;
}
+interface ScheduledPostEditOptions {
+ showToast: AppContextValue['showToast'];
+ loadScheduledPosts: () => Promise<void>;
+}
+
const EMPTY_DRAFT: EditDraft = { postId: null, caption: '', date: '', time: '' };
-export function useScheduledPostEdit({ showToast, loadScheduledPosts }: ScheduledPostActionOptions) {
+export function editButtonId(postId: string): string {
+ return `edit-post-${postId}`;
+}
+
+// focus goes back to the row's Edit button once the editor closes, so keyboard users keep their place
+function returnFocus(postId: string | null) {
+ if (!postId) return;
+ requestAnimationFrame(() => document.getElementById(editButtonId(postId))?.focus());
+}
+
+export function useScheduledPostEdit({ showToast, loadScheduledPosts }: ScheduledPostEditOptions) {
const [draft, setDraft] = useState(EMPTY_DRAFT);
+ const [original, setOriginal] = useState(EMPTY_DRAFT);
const [savingEdit, setSavingEdit] = useState(false);
+ const [problem, setProblem] = useState<FieldProblem<EditPostField> | null>(null);
+ const [saveError, setSaveError] = useState<string | null>(null);
+
+ const dirty = draft.postId !== null && JSON.stringify(draft) !== JSON.stringify(original);
- const setDraftField = <K extends keyof EditDraft>(name: K, value: EditDraft[K]) => setDraft(prev => ({ ...prev, [name]: value }));
+ const setDraftField = <K extends keyof EditDraft>(name: K, value: EditDraft[K]) => {
+ setDraft(prev => ({ ...prev, [name]: value }));
+ setProblem(null);
+ };
const startEditPost = (post: ScheduledPost) => {
const scheduledAt = new Date(post.scheduledAt);
- const date = toLocalDateInput(scheduledAt);
- setDraft({ postId: post.id, caption: post.caption || '', date, time: toLocalTimeInput(scheduledAt) });
+ const next = { postId: post.id, caption: post.caption || '', date: toLocalDateInput(scheduledAt), time: toLocalTimeInput(scheduledAt) };
+ setDraft(next);
+ setOriginal(next);
+ setProblem(null);
+ setSaveError(null);
};
- const cancelEdit = () => setDraft(EMPTY_DRAFT);
+ const cancelEdit = () => {
+ const postId = draft.postId;
+ setDraft(EMPTY_DRAFT);
+ setOriginal(EMPTY_DRAFT);
+ setProblem(null);
+ setSaveError(null);
+ returnFocus(postId);
+ };
const handleSaveEdit = async () => {
- const error = editPostError({ ...draft, now: new Date() });
- if (error) {
- showToast(error, 'error');
+ if (savingEdit) return;
+ const found = editPostProblem({ ...draft, now: new Date() });
+ if (found) {
+ setProblem(found);
+ document.getElementById(found.field === 'date' ? 'edit-post-date' : 'edit-post-time')?.focus();
return;
}
const scheduledAt = new Date(`${draft.date}T${draft.time}`);
setSavingEdit(true);
+ setSaveError(null);
try {
await api.updateScheduledPost(draft.postId as string, { caption: draft.caption, scheduledAt: scheduledAt.toISOString() });
showToast('Scheduled post updated');
cancelEdit();
loadScheduledPosts();
} catch (err) {
- showToast(`Couldn't update the post. ${(err as Error).message}`, 'error');
+ setSaveError(`Couldn't update the post. ${(err as Error).message}`);
} finally {
setSavingEdit(false);
}
};
- return { draft, setDraftField, savingEdit, startEditPost, cancelEdit, handleSaveEdit };
+ const errorFor = (field: EditPostField) => (problem?.field === field ? problem.message : undefined);
+
+ return { draft, setDraftField, savingEdit, startEditPost, cancelEdit, handleSaveEdit, dirty, errorFor, saveError };
}
export type ScheduledPostEditor = ReturnType<typeof useScheduledPostEdit>;
diff --git a/frontend/src/features/publishing/useScheduledPosts.ts b/frontend/src/features/publishing/useScheduledPosts.ts
index cece8d5..6fe7332 100644
--- a/frontend/src/features/publishing/useScheduledPosts.ts
+++ b/frontend/src/features/publishing/useScheduledPosts.ts
@@ -1,23 +1,39 @@
-import { useCallback, useState } from 'react';
+import { useCallback, useMemo, useState } from 'react';
+import { useUrlChoice } from '@/hooks/use-url-state';
import { api } from '../../services/api';
import type { ScheduledPost } from '@shared/types/domain.ts';
import type { StatusFilter } from './scheduleHelpers.ts';
+const STATUS_FILTERS: StatusFilter[] = ['all', 'pending', 'publishing', 'published', 'failed'];
+
export function useScheduledPosts() {
- const [scheduledPosts, setScheduledPosts] = useState<ScheduledPost[]>([]);
- const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
+ const [loadedPosts, setLoadedPosts] = useState<ScheduledPost[]>([]);
+ const [hiddenIds, setHiddenIds] = useState<string[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ // the status filter is kept in the address, so a refresh or a shared link shows the same list
+ const [statusFilter, setStatusFilter] = useUrlChoice<StatusFilter>('status', STATUS_FILTERS, 'all', { history: 'replace' });
const loadScheduledPosts = useCallback(async () => {
+ setLoading(true);
try {
const res = await api.getScheduledPosts();
- setScheduledPosts(res.posts);
- } catch {
- // the schedule list is optional, publishing still works
- return;
+ setLoadedPosts(res.posts);
+ setLoadError(null);
+ } catch (err) {
+ // the list is optional and publishing still works, so the failure is shown on the list only
+ setLoadError(`Couldn't load the scheduled posts. ${(err as Error).message}`);
+ } finally {
+ setLoading(false);
}
}, []);
- return { scheduledPosts, loadScheduledPosts, statusFilter, setStatusFilter };
+ // a post waiting out its Undo window is hidden here, not removed, so Undo can bring it straight back
+ const hidePost = useCallback((id: string) => setHiddenIds(ids => [...ids, id]), []);
+ const showPost = useCallback((id: string) => setHiddenIds(ids => ids.filter(item => item !== id)), []);
+ const scheduledPosts = useMemo(() => loadedPosts.filter(post => !hiddenIds.includes(post.id)), [hiddenIds, loadedPosts]);
+
+ return { scheduledPosts, loadScheduledPosts, loading, loadError, statusFilter, setStatusFilter, hidePost, showPost };
}
export type ScheduledPostsState = ReturnType<typeof useScheduledPosts>;
diff --git a/frontend/src/features/publishing/useSinglePostForm.ts b/frontend/src/features/publishing/useSinglePostForm.ts
index 42e15a0..b3bf69e 100644
--- a/frontend/src/features/publishing/useSinglePostForm.ts
+++ b/frontend/src/features/publishing/useSinglePostForm.ts
@@ -1,4 +1,5 @@
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
+import { clearDraft, readDraft, writeDraft } from '@/lib/sessionDraft';
import { useSinglePostMedia } from './useSinglePostMedia';
import type { ContentTypeValue, SinglePostFields } from './publishHelpers.ts';
@@ -16,11 +17,34 @@ const INITIAL_FIELDS: SinglePostFields = {
scheduleTime: '',
};
+const DRAFT_KEY = 'publish:single';
+
+// the typed parts of a post; a chosen file cannot be kept, so it is chosen again after a reload
+interface SinglePostDraft {
+ contentType: ContentTypeValue | '';
+ fields: SinglePostFields;
+}
+
+function hasTypedWork(fields: SinglePostFields): boolean {
+ return JSON.stringify(fields) !== JSON.stringify(INITIAL_FIELDS);
+}
+
export function useSinglePostForm() {
const media = useSinglePostMedia();
+ const [draft] = useState(() => readDraft<SinglePostDraft>(DRAFT_KEY));
const [selectedAccount, setSelectedAccount] = useState<string>('');
- const [contentType, setContentType] = useState<ContentTypeValue | ''>('');
- const [fields, setFields] = useState<SinglePostFields>(INITIAL_FIELDS);
+ const [contentType, setContentType] = useState<ContentTypeValue | ''>(() => draft?.contentType ?? '');
+ const [fields, setFields] = useState<SinglePostFields>(() => ({ ...INITIAL_FIELDS, ...draft?.fields }));
+ const [restored, setRestored] = useState(() => Boolean(draft && hasTypedWork({ ...INITIAL_FIELDS, ...draft.fields })));
+
+ const typed = hasTypedWork(fields);
+ // work that would be lost by leaving: a chosen file or anything typed
+ const dirty = Boolean(media.file) || typed;
+
+ useEffect(() => {
+ if (typed) writeDraft<SinglePostDraft>(DRAFT_KEY, { contentType, fields });
+ else clearDraft(DRAFT_KEY);
+ }, [contentType, fields, typed]);
const setField = <K extends keyof SinglePostFields>(name: K, value: SinglePostFields[K]) => setFields(prev => ({ ...prev, [name]: value }));
@@ -35,6 +59,8 @@ export function useSinglePostForm() {
media.clearCover();
setFields(INITIAL_FIELDS);
setContentType('');
+ setRestored(false);
+ clearDraft(DRAFT_KEY);
};
const scheduleIncomplete = fields.scheduleMode && (!fields.scheduleDate || !fields.scheduleTime);
@@ -42,7 +68,7 @@ export function useSinglePostForm() {
return {
...media, selectedAccount, setSelectedAccount, contentType, changeContentType,
- fields, setField, resetForm, canPublish,
+ fields, setField, resetForm, canPublish, dirty, restored, dismissRestored: () => setRestored(false),
};
}
diff --git a/frontend/src/features/publishing/useSinglePublish.ts b/frontend/src/features/publishing/useSinglePublish.ts
index 20fc099..5a6c46c 100644
--- a/frontend/src/features/publishing/useSinglePublish.ts
+++ b/frontend/src/features/publishing/useSinglePublish.ts
@@ -1,9 +1,10 @@
-import { useState } from 'react';
+import { useRef, useState } from 'react';
import { usePublishProgress } from './usePublishProgress';
import { publishSinglePost, scheduleSinglePost } from './singlePostFlow.ts';
-import { singlePostError } from './publishHelpers.ts';
+import { singlePostProblem } from './publishHelpers.ts';
import type { CloudinaryUploadConfig } from '../../services/api';
import type { AppContextValue } from '../../context/AppContext';
+import type { FieldProblem, SinglePostField } from './publishHelpers.ts';
import type { PublishProgressState } from './usePublishProgress';
import type { SinglePostForm } from './useSinglePostForm';
@@ -17,18 +18,28 @@ export interface SinglePublishOptions {
interface SinglePublishRun extends SinglePublishOptions {
progress: PublishProgressState;
setUploading: (uploading: boolean) => void;
+ signal: AbortSignal;
}
+// where focus goes for each problem, so the person lands on what to fix
+export const SINGLE_POST_FIELD_IDS: Record<SinglePostField, string> = {
+ account: 'post-account',
+ contentType: 'post-type',
+ file: 'post-file',
+ server: 'post-publish',
+ schedule: 'post-date',
+};
+
function beginRun(run: SinglePublishRun): void {
run.setUploading(true);
run.progress.setPublishStatus('uploading-cloudinary');
run.progress.setActiveStep(2);
}
-function failRun(run: SinglePublishRun, err: Error, title: string): void {
+// the failure is shown on the result screen with Try again, so no toast repeats it
+function failRun(run: SinglePublishRun, err: Error): void {
run.progress.setPublishStatus('error');
run.progress.setStatusMessage(err.message);
- run.showToast(`${title}. ${err.message}`, 'error');
}
async function schedulePost(run: SinglePublishRun): Promise<void> {
@@ -42,7 +53,7 @@ async function schedulePost(run: SinglePublishRun): Promise<void> {
run.showToast('Post scheduled');
run.onScheduled();
} catch (err) {
- failRun(run, err as Error, 'Scheduling failed');
+ failRun(run, err as Error);
} finally {
run.setUploading(false);
}
@@ -53,13 +64,13 @@ async function publishNow(run: SinglePublishRun): Promise<void> {
beginRun(run);
progress.setStatusMessage('Uploading media');
try {
- const mediaId = await publishSinglePost(run.form, run.cloudConfig, progress);
+ const mediaId = await publishSinglePost(run.form, run.cloudConfig, progress, run.signal);
progress.setPublishStatus('done');
progress.setPublishedMediaId(mediaId);
progress.setStatusMessage('Published');
run.showToast('Published to Instagram');
} catch (err) {
- failRun(run, err as Error, 'Publishing failed');
+ failRun(run, err as Error);
} finally {
run.setUploading(false);
}
@@ -68,15 +79,27 @@ async function publishNow(run: SinglePublishRun): Promise<void> {
export function useSinglePublish({ form, cloudConfig, showToast, onScheduled }: SinglePublishOptions) {
const progress = usePublishProgress();
const [uploading, setUploading] = useState(false);
+ const [tried, setTried] = useState(false);
+ const controllerRef = useRef<AbortController | null>(null);
+
+ // a problem shows once publishing was tried, then follows the form so it clears as soon as it is fixed
+ const problem: FieldProblem<SinglePostField> | null = tried
+ ? singlePostProblem({ ...form, hasCloudConfig: Boolean(cloudConfig), now: new Date() })
+ : null;
+ const errorFor = (field: SinglePostField) => (problem?.field === field ? problem.message : undefined);
// reads the form as it is at the moment of the click
const handlePublish = async () => {
- const error = singlePostError({ ...form, hasCloudConfig: Boolean(cloudConfig), now: new Date() });
- if (error) {
- showToast(error, 'error');
+ if (uploading) return;
+ setTried(true);
+ const found = singlePostProblem({ ...form, hasCloudConfig: Boolean(cloudConfig), now: new Date() });
+ if (found) {
+ document.getElementById(SINGLE_POST_FIELD_IDS[found.field])?.focus();
return;
}
- const run: SinglePublishRun = { form, cloudConfig, progress, setUploading, showToast, onScheduled };
+ const controller = new AbortController();
+ controllerRef.current = controller;
+ const run: SinglePublishRun = { form, cloudConfig, progress, setUploading, showToast, onScheduled, signal: controller.signal };
if (form.fields.scheduleMode) {
await schedulePost(run);
return;
@@ -84,7 +107,15 @@ export function useSinglePublish({ form, cloudConfig, showToast, onScheduled }:
await publishNow(run);
};
- return { ...progress, uploading, handlePublish };
+ // only the wait for Instagram can stop; an upload or a publish request already sent finishes on its own
+ const stopWaiting = () => controllerRef.current?.abort();
+
+ const reset = () => {
+ setTried(false);
+ progress.resetProgress();
+ };
+
+ return { ...progress, uploading, handlePublish, stopWaiting, problem, errorFor, reset };
}
export type SinglePublish = ReturnType<typeof useSinglePublish>;
diff --git a/frontend/src/features/settings/AppearanceSection.tsx b/frontend/src/features/settings/AppearanceSection.tsx
index c9c363a..3823b32 100644
--- a/frontend/src/features/settings/AppearanceSection.tsx
+++ b/frontend/src/features/settings/AppearanceSection.tsx
@@ -1,24 +1,32 @@
import React from 'react';
import { Monitor, Moon, Sun } from 'lucide-react';
-import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import SurfaceBox from '@/components/SurfaceBox';
+import SegmentedChoice from '@/components/SegmentedChoice';
import { FieldRow } from '@/components/DetailPanel';
import { useSmoothTheme } from '@/hooks/use-smooth-theme';
import SettingsSection from './SettingsSection';
+type ThemeChoice = 'light' | 'dark' | 'system';
+
+const THEMES = [
+ { value: 'light' as const, label: 'Light', icon: <Sun /> },
+ { value: 'dark' as const, label: 'Dark', icon: <Moon /> },
+ { value: 'system' as const, label: 'System', icon: <Monitor /> },
+];
+
+// a theme applies the moment it is picked, so this section has no Save button
export default function AppearanceSection() {
const { theme, setTheme } = useSmoothTheme();
return (
<SettingsSection id="appearance" title="Appearance" description="Choose a theme or follow your system setting.">
<SurfaceBox>
- <FieldRow label="Theme" hint="Dusk is the dark theme, Paper the light one.">
- <Tabs value={theme ?? 'system'} onValueChange={setTheme}>
- <TabsList variant="segmented" className="w-full sm:w-fit">
- <TabsTrigger value="light"><Sun />Light</TabsTrigger>
- <TabsTrigger value="dark"><Moon />Dark</TabsTrigger>
- <TabsTrigger value="system"><Monitor />System</TabsTrigger>
- </TabsList>
- </Tabs>
+ <FieldRow label="Theme" htmlFor="theme" group hint="System follows the light or dark setting of your device. The change applies at once.">
+ <SegmentedChoice<ThemeChoice>
+ name="theme"
+ options={THEMES}
+ value={(theme as ThemeChoice | undefined) ?? 'system'}
+ onChange={setTheme}
+ />
</FieldRow>
</SurfaceBox>
</SettingsSection>
diff --git a/frontend/src/features/settings/GithubRepoForm.tsx b/frontend/src/features/settings/GithubRepoForm.tsx
index 1fe222c..64ef5a7 100644
--- a/frontend/src/features/settings/GithubRepoForm.tsx
+++ b/frontend/src/features/settings/GithubRepoForm.tsx
@@ -3,36 +3,60 @@ import { Save } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
+import { Badge } from '@/components/ui/badge';
+import { FieldRow } from '@/components/DetailPanel';
export interface GithubRepoFormProps {
owner: string;
repo: string;
+ savedOwner: string;
+ savedRepo: string;
+ unsaved: boolean;
+ ownerError: string | null;
onOwnerChange: (value: string) => void;
+ onOwnerBlur: () => void;
onRepoChange: (value: string) => void;
onSave: (e: React.FormEvent<HTMLFormElement>) => void;
saving: boolean;
- canSave: boolean;
}
-export default function GithubRepoForm({ owner, repo, onOwnerChange, onRepoChange, onSave, saving, canSave }: GithubRepoFormProps) {
+// an explicit Save, because the guide's links follow the saved name; an Unsaved badge shows typing not yet saved
+export default function GithubRepoForm({
+ owner, repo, unsaved, ownerError, onOwnerChange, onOwnerBlur, onRepoChange, onSave, saving,
+}: Omit<GithubRepoFormProps, 'savedOwner' | 'savedRepo'>) {
return (
- <form onSubmit={onSave} className="flex flex-col gap-2 rounded-field bg-surface-sunken/60 p-4">
- <label htmlFor="gh-user" className="text-sm font-medium text-ink">Your GitHub username</label>
- <p className="text-caption text-ink-faint">Type it once and every button below opens the right page in your GitHub.</p>
- <div className="flex flex-wrap gap-2">
- <Input id="gh-user" value={owner} onChange={e => onOwnerChange(e.target.value)} placeholder="your-github-username" autoComplete="off" className="max-w-xs flex-1 bg-surface-raised" />
- <Button type="submit" variant="outline" disabled={saving || !canSave}>
- {saving ? <Spinner className="size-4" /> : <Save data-icon="inline-start" />}
- Save
- </Button>
- </div>
- <details className="text-caption text-ink-faint">
+ <form onSubmit={onSave} noValidate className="flex flex-col gap-3 rounded-field bg-surface-sunken/60 p-4">
+ <FieldRow
+ label="Your GitHub username"
+ htmlFor="gh-user"
+ hint="Type it once and every button below opens the right page in your GitHub. A pasted profile address works too."
+ error={ownerError ?? undefined}
+ >
+ <Input
+ id="gh-user"
+ value={owner}
+ onChange={e => onOwnerChange(e.target.value)}
+ onBlur={onOwnerBlur}
+ placeholder="your-github-username"
+ autoComplete="off"
+ spellCheck={false}
+ className="max-w-xs bg-surface-raised"
+ />
+ </FieldRow>
+ <details className="text-small text-ink-muted">
<summary className="cursor-pointer select-none">Renamed your copy?</summary>
- <div className="mt-2 flex items-center gap-2">
+ <div className="mt-2 flex flex-wrap items-center gap-2">
<label htmlFor="gh-repo" className="shrink-0">Repository name</label>
- <Input id="gh-repo" value={repo} onChange={e => onRepoChange(e.target.value)} placeholder="twiligent" autoComplete="off" className="h-(--control-h-sm) max-w-48 bg-surface-raised" />
+ <Input id="gh-repo" value={repo} onChange={e => onRepoChange(e.target.value)} placeholder="twiligent" autoComplete="off" className="max-w-48 bg-surface-raised" />
</div>
</details>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button type="submit" variant="outline" disabled={saving}>
+ {saving ? <Spinner className="size-4" /> : <Save data-icon="inline-start" />}
+ {saving ? 'Saving' : 'Save username'}
+ </Button>
+ {unsaved && <Badge variant="warning">Not saved yet</Badge>}
+ </div>
</form>
);
}
diff --git a/frontend/src/features/settings/PasswordSection.tsx b/frontend/src/features/settings/PasswordSection.tsx
index 296c29a..7d80345 100644
--- a/frontend/src/features/settings/PasswordSection.tsx
+++ b/frontend/src/features/settings/PasswordSection.tsx
@@ -5,7 +5,8 @@ import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import SurfaceBox from '@/components/SurfaceBox';
import { FieldRow } from '@/components/DetailPanel';
-import { PASSWORD_MIN_LENGTH, newPasswordProblem } from '@/lib/passwords';
+import { PASSWORD_MIN_LENGTH, newPasswordError } from '@/lib/passwords';
+import type { PasswordProblem } from '@/lib/passwords';
import { passwordErrorMessage } from '@/lib/authErrors';
import type { AuthErrorLike } from '@/lib/authErrors';
import { useAuth } from '../../context/AuthContext';
@@ -18,12 +19,17 @@ export default function PasswordSection() {
const [password, setPassword] = useState('');
const [confirmation, setConfirmation] = useState('');
const [saving, setSaving] = useState(false);
+ const [tried, setTried] = useState(false);
+ // shown once a save was tried, then it follows the fields so it clears as soon as they are right
+ const problem: PasswordProblem | null = tried ? newPasswordError(password, confirmation) : null;
async function handleSave(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
- const problem = newPasswordProblem(password, confirmation);
- if (problem) {
- showToast(problem, 'error');
+ if (saving) return;
+ setTried(true);
+ const found = newPasswordError(password, confirmation);
+ if (found) {
+ document.getElementById(found.field === 'password' ? 'new-password' : 'confirm-password')?.focus();
return;
}
setSaving(true);
@@ -32,6 +38,7 @@ export default function PasswordSection() {
if (error) throw error;
setPassword('');
setConfirmation('');
+ setTried(false);
showToast('Password saved. You can now sign in with your email and this password.');
} catch (err) {
showToast(`Couldn't save the password. ${passwordErrorMessage(err as AuthErrorLike)}`, 'error');
@@ -47,10 +54,10 @@ export default function PasswordSection() {
description="Sign in with your email and a password. If you joined with Google, this adds a password to the same account."
>
<SurfaceBox>
- <form onSubmit={handleSave} className="flex flex-col gap-4">
+ <form onSubmit={handleSave} noValidate className="flex flex-col gap-4">
{/* lets password managers save the new password against the right account */}
<input type="email" name="username" autoComplete="username" value={user?.email ?? ''} readOnly hidden />
- <FieldRow label="New password" htmlFor="new-password" hint={`At least ${PASSWORD_MIN_LENGTH} characters.`}>
+ <FieldRow label="New password" htmlFor="new-password" hint={`At least ${PASSWORD_MIN_LENGTH} characters.`} error={problem?.field === 'password' ? problem.message : undefined}>
<Input
id="new-password"
type="password"
@@ -62,7 +69,7 @@ export default function PasswordSection() {
className="max-w-sm"
/>
</FieldRow>
- <FieldRow label="Confirm the new password" htmlFor="confirm-password">
+ <FieldRow label="Confirm the new password" htmlFor="confirm-password" error={problem?.field === 'confirmation' ? problem.message : undefined}>
<Input
id="confirm-password"
type="password"
@@ -74,9 +81,9 @@ export default function PasswordSection() {
className="max-w-sm"
/>
</FieldRow>
- <Button type="submit" variant="outline" className="self-start" disabled={saving || !password || !confirmation}>
+ <Button type="submit" variant="outline" className="self-start" disabled={saving}>
{saving ? <Spinner className="size-4" /> : <KeyRound data-icon="inline-start" />}
- Save password
+ {saving ? 'Saving password' : 'Save password'}
</Button>
</form>
</SurfaceBox>
diff --git a/frontend/src/features/settings/PlatformRequirementsSection.tsx b/frontend/src/features/settings/PlatformRequirementsSection.tsx
index 49e9768..0f0ea8c 100644
--- a/frontend/src/features/settings/PlatformRequirementsSection.tsx
+++ b/frontend/src/features/settings/PlatformRequirementsSection.tsx
@@ -9,7 +9,7 @@ export default function PlatformRequirementsSection() {
<SurfaceBox content={false} className="divide-y divide-divider">
<div className="flex flex-col gap-1 px-5 py-4">
<p className="text-sm font-medium text-ink">YouTube</p>
- <p className="text-sm text-ink-muted">Add a channel link or @handle in Accounts. The API key is already set on the server.</p>
+ <p className="max-w-prose text-body text-ink-muted">Add a channel link or @handle in Accounts. The API key is already set on the server.</p>
</div>
<div className="flex flex-col gap-2 px-5 py-4">
<p className="text-sm font-medium text-ink">Instagram</p>
@@ -23,7 +23,7 @@ export default function PlatformRequirementsSection() {
</div>
<div className="flex flex-col gap-1 px-5 py-4">
<p className="text-sm font-medium text-ink">Cloudinary</p>
- <p className="text-sm text-ink-muted">Instagram needs every file at a public URL before publishing. Cloudinary hosts uploads for that; its cloud name and upload preset are set on the server.</p>
+ <p className="max-w-prose text-body text-ink-muted">Instagram needs every file at a public URL before publishing. Cloudinary hosts uploads for that; its cloud name and upload preset are set on the server.</p>
</div>
</SurfaceBox>
</SettingsSection>
diff --git a/frontend/src/features/settings/SchedulingSection.tsx b/frontend/src/features/settings/SchedulingSection.tsx
index b3e816c..2dbe7ba 100644
--- a/frontend/src/features/settings/SchedulingSection.tsx
+++ b/frontend/src/features/settings/SchedulingSection.tsx
@@ -47,7 +47,7 @@ function Steps({ steps }: StepsProps) {
export default function SchedulingSection({ github }: SchedulingSectionProps) {
const pendingStep: HowItWorksStep = {
title: 'If a post stays Pending',
- body: <>A post still Pending 30 minutes after its time, or still Publishing 50 minutes after it started, means the scheduler on this server is not running. Email the administrator at <a href={adminMailto('Scheduled posts are not publishing on Twiligent')}>{ADMIN_EMAIL}</a> with the time of the post. You can edit or delete a Pending post at any time.</>,
+ body: <>A post still Pending 30 minutes after its time, or still Publishing 50 minutes after it started, means the scheduler on this server is not running. Email the administrator at <a href={adminMailto('Scheduled posts are not publishing on Twiligent')} className="font-medium text-brand-text underline underline-offset-4">{ADMIN_EMAIL}</a> with the time of the post. You can edit or delete a Pending post at any time.</>,
};
return (
@@ -60,13 +60,13 @@ export default function SchedulingSection({ github }: SchedulingSectionProps) {
<div className="grid gap-3 sm:grid-cols-2">
<div className="flex flex-col gap-2 rounded-field border border-line p-4">
<p className="flex items-center gap-2 text-sm font-semibold text-ink"><Users className="size-4 stroke-[1.75] text-ink-faint" />You sign in to this Twiligent</p>
- <p className="text-sm text-ink-muted">Nothing to set up. The server publishes your scheduled posts. You do not need GitHub, Supabase or any keys.</p>
+ <p className="max-w-prose text-body text-ink-muted">Nothing to set up. The server publishes your scheduled posts. You do not need GitHub, Supabase or any keys.</p>
</div>
<div className="flex flex-col gap-2 rounded-field border border-line p-4">
<p className="flex items-center gap-2 text-sm font-semibold text-ink"><Server className="size-4 stroke-[1.75] text-ink-faint" />You run your own Twiligent</p>
- <p className="text-sm text-ink-muted">Deploying the backend is enough; scheduling starts with it. The GitHub backup below is optional.</p>
- <a href={docsUrl('/self-host')} target="_blank" rel="noopener noreferrer" className="mt-auto inline-flex items-center gap-1 text-sm font-medium text-brand-text underline-offset-4 hover:underline">
- Self-hosting guide<ArrowRight className="size-3.5" />
+ <p className="max-w-prose text-body text-ink-muted">Deploying the backend is enough; scheduling starts with it. The GitHub backup below is optional.</p>
+ <a href={docsUrl('/self-host')} target="_blank" rel="noopener noreferrer" className="mt-auto inline-flex items-center gap-1 text-sm font-medium text-brand-text underline underline-offset-4">
+ Self-hosting guide<span className="sr-only"> (opens in a new tab)</span><ArrowRight className="size-3.5" aria-hidden="true" />
</a>
</div>
</div>
@@ -83,7 +83,12 @@ export default function SchedulingSection({ github }: SchedulingSectionProps) {
<SchedulingSetupGuide
owner={github.owner}
repo={github.repo}
+ savedOwner={github.savedOwner}
+ savedRepo={github.savedRepo}
+ unsaved={github.unsaved}
+ ownerError={github.ownerError}
onOwnerChange={github.setOwner}
+ onOwnerBlur={github.tidyOwner}
onRepoChange={github.setRepo}
onSave={github.handleSave}
saving={github.saving}
diff --git a/frontend/src/features/settings/SchedulingSetupGuide.tsx b/frontend/src/features/settings/SchedulingSetupGuide.tsx
index 10ebdab..a1ce0c0 100644
--- a/frontend/src/features/settings/SchedulingSetupGuide.tsx
+++ b/frontend/src/features/settings/SchedulingSetupGuide.tsx
@@ -10,14 +10,14 @@ import SchedulingSetupSteps from './SchedulingSetupSteps';
import type { GithubRepoFormProps } from './GithubRepoForm';
import { docsUrl } from '@/lib/docs';
-export type SchedulingSetupGuideProps = Omit<GithubRepoFormProps, 'canSave'>;
+export type SchedulingSetupGuideProps = GithubRepoFormProps;
function SetupNotes() {
return (
<div className="flex flex-col gap-2 rounded-field border border-line p-4">
<p className="text-sm font-semibold text-ink">That is it</p>
- <p className="text-sm text-ink-muted">GitHub now asks for a run every 15 minutes, and you do not need to keep anything open. Three things to know:</p>
- <ul className="flex list-disc flex-col gap-1 pl-5 text-sm text-ink-muted marker:text-ink-faint">
+ <p className="max-w-prose text-body text-ink-muted">GitHub now asks for a run every 15 minutes, and you do not need to keep anything open. Three things to know:</p>
+ <ul className="flex max-w-prose list-disc flex-col gap-1 pl-5 text-body text-ink-muted marker:text-ink-faint">
<li>GitHub starts scheduled runs when it has room, often hours late and sometimes not at all, so this backup catches posts the server missed later, not within 15 minutes.</li>
<li>If nothing changes in your copy for 60 days, GitHub pauses the schedule and emails you. Repeat step 4 to switch it back on.</li>
<li>If you made your copy private, GitHub's free minutes run out. Keep it public, or change the schedule in <code className="font-mono text-small text-ink">.github/workflows/publish-scheduled.yml</code> to <code className="font-mono text-small text-ink">'7,37 * * * *'</code>, every 30 minutes.</li>
@@ -26,7 +26,9 @@ function SetupNotes() {
);
}
-export default function SchedulingSetupGuide({ owner, repo, onOwnerChange, onRepoChange, onSave, saving }: SchedulingSetupGuideProps) {
+export default function SchedulingSetupGuide({
+ owner, repo, savedOwner, savedRepo, unsaved, ownerError, onOwnerChange, onOwnerBlur, onRepoChange, onSave, saving,
+}: SchedulingSetupGuideProps) {
const [done, setDone] = useState<SetupProgress>(() => readProgress(browserStorage));
useEffect(() => {
@@ -34,8 +36,8 @@ export default function SchedulingSetupGuide({ owner, repo, onOwnerChange, onRep
}, [done]);
const toggle = (key: string) => () => setDone(prev => ({ ...prev, [key]: !prev[key] }));
- const user = owner.trim();
- const base = repoBaseUrl(owner, repo);
+ const user = savedOwner.trim() || owner.trim();
+ const base = repoBaseUrl(savedOwner, savedRepo);
const completed = completedSteps(done);
// members never need these steps; the guide opens only once someone has started
const [open, setOpen] = useState(() => completed > 0 || Boolean(user));
@@ -52,7 +54,7 @@ export default function SchedulingSetupGuide({ owner, repo, onOwnerChange, onRep
)}
>
<div className="flex flex-col gap-5">
- <p className="text-sm text-ink-muted">
+ <p className="max-w-prose text-body text-ink-muted">
A second copy of the publisher that runs on GitHub for free, so posts still go out if the server is ever paused, though later: GitHub often starts these runs hours after their time. Step 2 needs the secret key of the Supabase project behind this Twiligent, which only its administrator has. If you only sign in here, skip this: the server already publishes your posts.
</p>
<div className="flex flex-wrap items-center gap-2">
@@ -68,11 +70,13 @@ export default function SchedulingSetupGuide({ owner, repo, onOwnerChange, onRep
<GithubRepoForm
owner={owner}
repo={repo}
+ unsaved={unsaved}
+ ownerError={ownerError}
onOwnerChange={onOwnerChange}
+ onOwnerBlur={onOwnerBlur}
onRepoChange={onRepoChange}
onSave={onSave}
saving={saving}
- canSave={Boolean(user)}
/>
<SchedulingSetupSteps done={done} toggle={toggle} base={base} />
<SetupNotes />
diff --git a/frontend/src/features/settings/ServerKeysSection.tsx b/frontend/src/features/settings/ServerKeysSection.tsx
index af4a878..7690a9f 100644
--- a/frontend/src/features/settings/ServerKeysSection.tsx
+++ b/frontend/src/features/settings/ServerKeysSection.tsx
@@ -62,9 +62,9 @@ export default function ServerKeysSection({ serverStatus, refreshAll, refreshing
</Button>
</div>
{testResult && (
- <Alert variant={testResult.success ? 'success' : 'destructive'}>
+ <Alert variant={testResult.success ? 'success' : 'destructive'} role={testResult.success ? 'status' : 'alert'}>
{testResult.success ? <CheckCircle2 /> : <AlertTriangle />}
- <AlertDescription>{testResult.success ? '' : 'Error: '}{testResult.message}</AlertDescription>
+ <AlertDescription>{!testResult.success && <span className="sr-only">Error: </span>}{testResult.message}</AlertDescription>
</Alert>
)}
</SettingsSection>
diff --git a/frontend/src/features/settings/SettingsSection.tsx b/frontend/src/features/settings/SettingsSection.tsx
index 7d32544..9650c71 100644
--- a/frontend/src/features/settings/SettingsSection.tsx
+++ b/frontend/src/features/settings/SettingsSection.tsx
@@ -12,7 +12,7 @@ export default function SettingsSection({ id, title, description, children }: Se
<section id={id} aria-labelledby={`${id}-title`} className="grid scroll-mt-20 grid-cols-1 gap-4 border-t border-line pt-8 first:border-t-0 first:pt-0 lg:grid-cols-[16rem_1fr] lg:gap-10">
<div className="flex flex-col gap-1">
<h2 id={`${id}-title`} className="font-heading text-section font-semibold text-ink">{title}</h2>
- {description && <p className="text-small text-ink-muted">{description}</p>}
+ {description && <p className="max-w-prose text-body text-ink-muted">{description}</p>}
</div>
<div className="flex min-w-0 flex-col gap-4">{children}</div>
</section>
diff --git a/frontend/src/features/settings/SetupStep.tsx b/frontend/src/features/settings/SetupStep.tsx
index 5022cb3..2607ad0 100644
--- a/frontend/src/features/settings/SetupStep.tsx
+++ b/frontend/src/features/settings/SetupStep.tsx
@@ -29,11 +29,11 @@ export default function SetupStep({ number, icon, title, done, onToggle, childre
<div className="flex flex-wrap items-start justify-between gap-2">
<p className="text-sm font-semibold text-ink"><span className="text-ink-faint">Step {number}. </span>{title}</p>
<label className="flex cursor-pointer items-center gap-2 text-small text-ink-muted select-none">
- <input type="checkbox" checked={done} onChange={onToggle} className="size-4 accent-[var(--brand)]" />
- Done
+ <input type="checkbox" checked={done} onChange={onToggle} aria-label={`Step ${number} done`} className="size-4 accent-[var(--brand)]" />
+ <span aria-hidden="true">Done</span>
</label>
</div>
- <div className="flex flex-col gap-3 text-sm text-ink-muted [&_strong]:font-semibold [&_strong]:text-ink">{children}</div>
+ <div className="flex max-w-prose flex-col gap-3 text-body text-ink-muted [&_strong]:font-semibold [&_strong]:text-ink">{children}</div>
{check && (
<p className="flex items-start gap-1.5 text-small text-success">
<Check className="mt-0.5 size-3.5 shrink-0" />
diff --git a/frontend/src/features/settings/settingsData.ts b/frontend/src/features/settings/settingsData.ts
index 821342f..d2f15a8 100644
--- a/frontend/src/features/settings/settingsData.ts
+++ b/frontend/src/features/settings/settingsData.ts
@@ -76,6 +76,19 @@ export async function loadServerSettings(
}
}
+// people paste "@name" or the address of their profile or repository; only the user name is kept
+export function githubOwner(input: string): string {
+ const text = input.trim();
+ const fromUrl = text.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/?#\s]+)/i);
+ return (fromUrl ? fromUrl[1] : text).replace(/^@/, '').trim();
+}
+
+// a pasted repository address also names the repository, which the guide links need
+export function githubRepoFromUrl(input: string): string | null {
+ const match = input.trim().match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/[^/?#\s]+\/([^/?#\s]+)/i);
+ return match ? match[1].replace(/\.git$/i, '') : null;
+}
+
// only the repository is kept; it fills the guide links and needs no token
export function githubSettingsPayload(owner: string, repo: string): GitHubSettingsRequest {
return { repoOwner: owner.trim(), repoName: (repo || 'twiligent').trim(), branch: 'main' };
diff --git a/frontend/src/features/settings/useServerSettings.ts b/frontend/src/features/settings/useServerSettings.ts
index 5432969..720ab6f 100644
--- a/frontend/src/features/settings/useServerSettings.ts
+++ b/frontend/src/features/settings/useServerSettings.ts
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react';
import type { FormEvent } from 'react';
import { api } from '../../services/api';
-import { githubSettingsPayload, loadServerSettings } from './settingsData';
+import { githubOwner, githubRepoFromUrl, githubSettingsPayload, loadServerSettings } from './settingsData';
import type { AppContextValue } from '../../context/AppContext';
import type { KeysStatusResponse } from '@shared/types/domain.ts';
@@ -10,20 +10,29 @@ type ShowToast = AppContextValue['showToast'];
interface GithubRepoSaveDeps {
owner: string;
repo: string;
+ onSaved: (owner: string, repo: string) => void;
+ onMissingOwner: () => void;
showToast: ShowToast;
}
-function useGithubRepoSave({ owner, repo, showToast }: GithubRepoSaveDeps) {
+function useGithubRepoSave({ owner, repo, onSaved, onMissingOwner, showToast }: GithubRepoSaveDeps) {
const [saving, setSaving] = useState(false);
const handleSave = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
+ if (saving) return;
+ const payload = githubSettingsPayload(githubOwner(owner), repo);
+ if (!payload.repoOwner) {
+ onMissingOwner();
+ return;
+ }
setSaving(true);
try {
- await api.saveGithubSettings(githubSettingsPayload(owner, repo));
+ await api.saveGithubSettings(payload);
+ onSaved(payload.repoOwner, payload.repoName ?? 'twiligent');
showToast('GitHub username saved. The buttons in the guide now open your copy.');
} catch (err) {
- showToast(`Couldn't save the repository. ${(err as Error).message}`, 'error');
+ showToast(`Couldn't save the GitHub username. ${(err as Error).message}`, 'error');
} finally {
setSaving(false);
}
@@ -37,6 +46,9 @@ export function useServerSettings(showToast: ShowToast) {
const [loading, setLoading] = useState(true);
const [ghRepoOwner, setGhRepoOwner] = useState('');
const [ghRepoName, setGhRepoName] = useState('');
+ // the guide's links follow what is saved, not what is being typed
+ const [saved, setSaved] = useState({ owner: '', repo: '' });
+ const [ownerError, setOwnerError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
@@ -46,17 +58,49 @@ export function useServerSettings(showToast: ShowToast) {
applyGithub: (owner, name) => {
setGhRepoOwner(owner);
setGhRepoName(name);
+ setSaved({ owner, repo: name });
},
finish: () => setLoading(false),
});
return () => { cancelled = true; };
}, []);
- const { saving, handleSave } = useGithubRepoSave({ owner: ghRepoOwner, repo: ghRepoName, showToast });
+ const { saving, handleSave } = useGithubRepoSave({
+ owner: ghRepoOwner,
+ repo: ghRepoName,
+ onSaved: (owner, repo) => {
+ setGhRepoOwner(owner);
+ setGhRepoName(repo);
+ setSaved({ owner, repo });
+ setOwnerError(null);
+ },
+ onMissingOwner: () => {
+ setOwnerError('Type your GitHub username, such as octocat.');
+ document.getElementById('gh-user')?.focus();
+ },
+ showToast,
+ });
+
+ const setOwner = (value: string) => {
+ setGhRepoOwner(value);
+ setOwnerError(null);
+ };
+
+ // a pasted address is reduced to the user name when the field is left, and fills the repository name too
+ const tidyOwner = () => {
+ const repo = githubRepoFromUrl(ghRepoOwner);
+ if (repo) setGhRepoName(repo);
+ setGhRepoOwner(githubOwner(ghRepoOwner));
+ };
+
+ const unsaved = githubOwner(ghRepoOwner) !== saved.owner || (ghRepoName || 'twiligent') !== (saved.repo || 'twiligent');
return {
serverStatus, loading,
- github: { owner: ghRepoOwner, repo: ghRepoName, setOwner: setGhRepoOwner, setRepo: setGhRepoName, saving, handleSave },
+ github: {
+ owner: ghRepoOwner, repo: ghRepoName, savedOwner: saved.owner, savedRepo: saved.repo, unsaved, ownerError,
+ setOwner, setRepo: setGhRepoName, tidyOwner, saving, handleSave,
+ },
};
}
diff --git a/frontend/src/hooks/use-unsaved-changes.ts b/frontend/src/hooks/use-unsaved-changes.ts
new file mode 100644
index 0000000..6c016db
--- /dev/null
+++ b/frontend/src/hooks/use-unsaved-changes.ts
@@ -0,0 +1,37 @@
+import { useCallback, useEffect } from 'react';
+import { useBlocker } from 'react-router-dom';
+import type { BlockerFunction } from 'react-router-dom';
+
+export interface UnsavedChangesGuard {
+ blocked: boolean;
+ stay: () => void;
+ leave: () => void;
+}
+
+// asks before a navigation inside the app or a page close throws away typed work; query and hash changes on the
+// same page are left alone, so filters and tabs never trigger it
+export function useUnsavedChanges(when: boolean): UnsavedChangesGuard {
+ const shouldBlock = useCallback<BlockerFunction>(
+ ({ currentLocation, nextLocation }) => when && currentLocation.pathname !== nextLocation.pathname,
+ [when],
+ );
+ const blocker = useBlocker(shouldBlock);
+
+ useEffect(() => {
+ if (!when) return;
+ const warn = (event: BeforeUnloadEvent) => { event.preventDefault(); };
+ window.addEventListener('beforeunload', warn);
+ return () => window.removeEventListener('beforeunload', warn);
+ }, [when]);
+
+ // the work can be saved or finished while the question is open, and then there is nothing left to ask about
+ useEffect(() => {
+ if (!when && blocker.state === 'blocked') blocker.proceed();
+ }, [when, blocker]);
+
+ return {
+ blocked: blocker.state === 'blocked',
+ stay: () => { if (blocker.state === 'blocked') blocker.reset(); },
+ leave: () => { if (blocker.state === 'blocked') blocker.proceed(); },
+ };
+}
diff --git a/frontend/src/lib/fieldIds.ts b/frontend/src/lib/fieldIds.ts
new file mode 100644
index 0000000..5a2c9a3
--- /dev/null
+++ b/frontend/src/lib/fieldIds.ts
@@ -0,0 +1,9 @@
+// the ids FieldRow gives a field's hint and error, so a control outside a FieldRow can point at them too
+
+export function fieldHintId(htmlFor: string): string {
+ return `${htmlFor}-hint`;
+}
+
+export function fieldErrorId(htmlFor: string): string {
+ return `${htmlFor}-error`;
+}
diff --git a/frontend/src/lib/passwords.ts b/frontend/src/lib/passwords.ts
index 639f3dd..7002e41 100644
--- a/frontend/src/lib/passwords.ts
+++ b/frontend/src/lib/passwords.ts
@@ -1,9 +1,18 @@
// Supabase's default minimum; a project set higher still answers with its own message
export const PASSWORD_MIN_LENGTH = 6;
-// what is wrong with a new password before it is sent, or null when it can be saved
-export function newPasswordProblem(password: string, confirmation: string): string | null {
- if (password.length < PASSWORD_MIN_LENGTH) return `Use at least ${PASSWORD_MIN_LENGTH} characters.`;
- if (password !== confirmation) return 'The two passwords do not match.';
+export interface PasswordProblem {
+ field: 'password' | 'confirmation';
+ message: string;
+}
+
+// what is wrong with a new password before it is sent and which field to fix, or null when it can be saved
+export function newPasswordError(password: string, confirmation: string): PasswordProblem | null {
+ if (password.length < PASSWORD_MIN_LENGTH) return { field: 'password', message: `Use at least ${PASSWORD_MIN_LENGTH} characters.` };
+ if (password !== confirmation) return { field: 'confirmation', message: 'The two passwords do not match. Type the same password in both fields.' };
return null;
}
+
+export function newPasswordProblem(password: string, confirmation: string): string | null {
+ return newPasswordError(password, confirmation)?.message ?? null;
+}
diff --git a/frontend/src/lib/sessionDraft.ts b/frontend/src/lib/sessionDraft.ts
new file mode 100644
index 0000000..5cf2bab
--- /dev/null
+++ b/frontend/src/lib/sessionDraft.ts
@@ -0,0 +1,43 @@
+// typed work kept in the tab's session storage, so a reload or a wrong click does not lose it; storage can be
+// missing or full (private windows, blocked site data), and then the draft is simply not kept
+
+export interface DraftStorage {
+ getItem: (key: string) => string | null;
+ setItem: (key: string, value: string) => void;
+ removeItem: (key: string) => void;
+}
+
+const PREFIX = 'twiligent:draft:';
+
+function defaultStorage(): DraftStorage | null {
+ try {
+ return typeof sessionStorage === 'undefined' ? null : sessionStorage;
+ } catch {
+ return null;
+ }
+}
+
+export function readDraft<T>(key: string, storage: DraftStorage | null = defaultStorage()): T | null {
+ try {
+ const raw = storage?.getItem(PREFIX + key);
+ return raw ? (JSON.parse(raw) as T) : null;
+ } catch {
+ return null;
+ }
+}
+
+export function writeDraft<T>(key: string, value: T, storage: DraftStorage | null = defaultStorage()): void {
+ try {
+ storage?.setItem(PREFIX + key, JSON.stringify(value));
+ } catch {
+ // a full or blocked storage only means the draft is not kept
+ }
+}
+
+export function clearDraft(key: string, storage: DraftStorage | null = defaultStorage()): void {
+ try {
+ storage?.removeItem(PREFIX + key);
+ } catch {
+ // nothing to clear when storage is blocked
+ }
+}
diff --git a/frontend/src/pages/Login.tsx b/frontend/src/pages/Login.tsx
index 6752051..3f83143 100644
--- a/frontend/src/pages/Login.tsx
+++ b/frontend/src/pages/Login.tsx
@@ -1,4 +1,4 @@
-import { Suspense, lazy, useState } from 'react';
+import { Suspense, lazy, useEffect, useRef, useState } from 'react';
import type { FormEvent } from 'react';
import { Navigate, useNavigate, useSearchParams } from 'react-router-dom';
import { toast } from 'sonner';
@@ -11,16 +11,19 @@ import { GOOGLE_CLIENT_ID } from '@/lib/googleIdentity';
import { emailErrorNotice, isExistingAccount, passwordErrorMessage } from '@/lib/authErrors';
import type { AuthErrorLike } from '@/lib/authErrors';
import { PASSWORD_MIN_LENGTH, newPasswordProblem } from '@/lib/passwords';
+import { CODE_LENGTH } from '@/lib/authErrors';
+import { looksLikeEmail } from '@/lib/emailAddress';
import { signInPageOutcome } from '@/lib/signInPage';
import { FieldRow } from '@/components/DetailPanel';
+import { useDocumentTitle } from '@/hooks/use-document-title';
import { useCountdown } from './useCountdown';
import LoginEmailStart from './LoginEmailStart';
import LoginPasswordForm from './LoginPasswordForm';
import LoginCodeForm from './LoginCodeForm';
import LoginEmailForm from './LoginEmailForm';
import PasswordInput from './PasswordInput';
-import { LOGIN_COPY, PRIVACY_URL, SIGN_UP_TITLE } from './loginCopy';
-import type { LoginView } from './loginCopy';
+import { FAILURE_FIELD, LOGIN_COPY, PRIVACY_URL, SIGN_UP_TITLE } from './loginCopy';
+import type { LoginField, LoginView } from './loginCopy';
// the dashboard picture behind the card is decoration, so it loads after the card and never delays signing in
const LoginBackdrop = lazy(() => import('./LoginBackdrop'));
@@ -59,7 +62,37 @@ function OrDivider() {
}
const QUIET_LINK =
- 'rounded-sm text-caption text-ink-muted transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring';
+ 'inline-flex min-h-6 items-center rounded-sm text-small text-ink-muted transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring';
+
+const VIEWS_WITH_EMAIL: LoginView[] = ['start', 'password', 'signup', 'forgot'];
+const VIEWS_WITH_CODE: LoginView[] = ['code', 'verify', 'reset'];
+
+export interface LoginProblem {
+ field: LoginField;
+ message: string;
+}
+
+// what is missing before a view can be sent, or null; checked on submit so the button never greys out silently
+function loginProblem(view: LoginView, email: string, code: string, password: string): LoginProblem | null {
+ if (VIEWS_WITH_EMAIL.includes(view) && !looksLikeEmail(email)) {
+ return { field: 'email', message: 'Enter your full email address, such as [email protected].' };
+ }
+ if ((view === 'password' || view === 'signup') && !password) return { field: 'password', message: 'Enter your password.' };
+ if (view === 'signup') {
+ const problem = newPasswordProblem(password, password);
+ if (problem) return { field: 'password', message: problem };
+ }
+ if (VIEWS_WITH_CODE.includes(view) && code.length !== CODE_LENGTH) {
+ return { field: 'code', message: `Enter the ${CODE_LENGTH}-digit code from the email.` };
+ }
+ if (view === 'reset') {
+ const problem = newPasswordProblem(password, password);
+ if (problem) return { field: 'password', message: problem };
+ }
+ return null;
+}
+
+const FIELD_IDS: Record<LoginField, string> = { email: 'email', code: 'code', password: 'password' };
// the Activepieces sign-in in Twiligent's brand: one card over a blurred picture of the app, Google first,
// then an email that receives a sign-in code, with the password behind a quiet link
@@ -81,13 +114,51 @@ export default function Login() {
const [resendIn, startResendWait] = useCountdown();
const [emailLimitMessage, setEmailLimitMessage] = useState<string | null>(null);
const [signingIn, setSigningIn] = useState(false);
+ const [problem, setProblem] = useState<LoginProblem | null>(null);
+ const titleRef = useRef<HTMLHeadingElement>(null);
+ const firstView = useRef(true);
const copy = LOGIN_COPY[view];
+ const errorFor = (field: LoginField) => (problem?.field === field ? problem.message : undefined);
+
+ // the button that changed the view is gone; when the new view does not focus a field itself, its title takes focus
+ useEffect(() => {
+ if (firstView.current) {
+ firstView.current = false;
+ return;
+ }
+ const frame = requestAnimationFrame(() => {
+ if (!document.activeElement || document.activeElement === document.body) titleRef.current?.focus();
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [view]);
+
+ function changeEmail(value: string) {
+ setEmail(value);
+ if (problem?.field === 'email') setProblem(null);
+ }
+
+ function changePassword(value: string) {
+ setPassword(value);
+ if (problem?.field === 'password') setProblem(null);
+ }
+
+ function changeCode(value: string) {
+ setCode(value);
+ if (problem?.field === 'code') setProblem(null);
+ }
+
+ function showProblem(found: LoginProblem) {
+ setProblem(found);
+ requestAnimationFrame(() => document.getElementById(FIELD_IDS[found.field])?.focus());
+ }
const title = view === 'start' && signingUp ? SIGN_UP_TITLE : copy.title;
+ useDocumentTitle(view === 'start' ? (signingUp ? 'Create an account' : 'Sign in') : copy.title);
const back = BACK_TO[view];
function showView(next: LoginView) {
setView(next);
setShowPassword(false);
+ setProblem(null);
}
function openCodeStep(next: 'code' | 'verify' | 'reset') {
@@ -96,14 +167,15 @@ export default function Login() {
showView(next);
}
- function showEmailError(prefix: string, err: unknown) {
+ // a failure is shown under the field it concerns and stays there until that field changes
+ function showEmailError(prefix: string, err: unknown, field: LoginField) {
const notice = emailErrorNotice(err as AuthErrorLike, !!GOOGLE_CLIENT_ID);
// the warning on the first view says it already, next to the ways in that still work
if (notice.emailLimitReached) {
setEmailLimitMessage(notice.message);
showView('start');
} else {
- toast.error(`${prefix} ${notice.message}`);
+ showProblem({ field, message: `${prefix} ${notice.message}` });
}
}
@@ -142,8 +214,8 @@ export default function Login() {
return;
}
if (isExistingAccount(data.user)) {
- toast.error('This email already has an account. Sign in instead.');
showView('password');
+ showProblem({ field: 'password', message: 'This email already has an account. Enter its password to sign in.' });
return;
}
openCodeStep('verify');
@@ -193,18 +265,26 @@ export default function Login() {
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
+ if (loading) return;
+ const found = loginProblem(view, email.trim(), code, password);
+ if (found) {
+ showProblem(found);
+ return;
+ }
+ setProblem(null);
setSigningIn(true);
setLoading(true);
try {
await SUBMIT[view]();
} catch (err) {
- showEmailError(FAILURE_PREFIX[view], err);
+ showEmailError(FAILURE_PREFIX[view], err, FAILURE_FIELD[view]);
} finally {
setLoading(false);
}
}
async function handleResend() {
+ if (resending) return;
setResending(true);
try {
const address = email.trim();
@@ -218,7 +298,7 @@ export default function Login() {
startResendWait(RESEND_WAIT_SECONDS);
toast.success('New code sent');
} catch (err) {
- showEmailError("Couldn't send a new code.", err);
+ showEmailError("Couldn't send a new code.", err, 'code');
} finally {
setResending(false);
}
@@ -232,7 +312,7 @@ export default function Login() {
if (error) throw error;
navigate('/');
} catch (err) {
- toast.error(`Couldn't sign in with Google. ${(err as Error).message}`);
+ setProblem({ field: 'email', message: `Couldn't sign in with Google. ${(err as Error).message}` });
} finally {
setLoading(false);
}
@@ -240,7 +320,7 @@ export default function Login() {
// the public site's Sign in and Get started buttons land here, so a stored session opens the dashboard
const outcome = signInPageOutcome(session === undefined ? undefined : !!session, signingIn);
- if (outcome === 'wait') return null;
+ if (outcome === 'wait') return <p role="status" className="sr-only">Checking whether you are signed in</p>;
if (outcome === 'dashboard') return <Navigate to="/" replace />;
return (
@@ -263,8 +343,10 @@ export default function Login() {
</button>
)}
<h1
+ ref={titleRef}
id="login-title"
- className="mt-6 mb-6 text-center font-heading text-[1.375rem] leading-snug font-semibold tracking-[-0.02em] text-balance text-ink"
+ tabIndex={-1}
+ className="mt-6 mb-6 text-center font-heading text-page-title font-semibold text-balance text-ink outline-none"
>
{title}
</h1>
@@ -272,7 +354,7 @@ export default function Login() {
{view === 'start' && (
<>
{emailLimitMessage && (
- <Alert variant="warning" className="mb-5">
+ <Alert variant="warning" className="mb-5" role="alert">
<MailWarning />
<AlertTitle>Email codes are paused until tomorrow</AlertTitle>
<AlertDescription>{emailLimitMessage}</AlertDescription>
@@ -283,16 +365,16 @@ export default function Login() {
<GoogleSignInButton
text={signingUp ? 'signup_with' : 'continue_with'}
onCredential={handleGoogleCredential}
- onError={err => toast.error(err.message)}
+ onError={err => setProblem({ field: 'email', message: `Couldn't sign in with Google. ${err.message}` })}
/>
<OrDivider />
</>
)}
- <LoginEmailStart email={email} onEmailChange={setEmail} loading={loading} onSubmit={handleSubmit} />
+ <LoginEmailStart email={email} onEmailChange={changeEmail} loading={loading} onSubmit={handleSubmit} error={errorFor('email')} />
<button type="button" onClick={() => showView('password')} className={`mx-auto mt-5 ${QUIET_LINK}`}>
Use password
</button>
- <p className="mt-8 border-t border-line-strong/60 pt-5 text-center text-[0.6875rem] leading-relaxed text-ink-muted">
+ <p className="mt-8 border-t border-line-strong/60 pt-5 text-center text-caption text-ink-muted">
By continuing, you agree to the{' '}
<a href={PRIVACY_URL} target="_blank" rel="noopener noreferrer" className="underline underline-offset-4 hover:text-ink">
privacy policy
@@ -308,8 +390,10 @@ export default function Login() {
copy={copy}
email={email}
password={password}
- onEmailChange={setEmail}
- onPasswordChange={setPassword}
+ onEmailChange={changeEmail}
+ onPasswordChange={changePassword}
+ emailError={errorFor('email')}
+ passwordError={errorFor('password')}
showPassword={showPassword}
onTogglePassword={() => setShowPassword(visible => !visible)}
loading={loading}
@@ -320,7 +404,7 @@ export default function Login() {
)}
{view === 'forgot' && (
- <LoginEmailForm copy={copy} email={email} onEmailChange={setEmail} loading={loading} onSubmit={handleSubmit} />
+ <LoginEmailForm copy={copy} email={email} onEmailChange={changeEmail} loading={loading} onSubmit={handleSubmit} error={errorFor('email')} />
)}
{(view === 'code' || view === 'verify' || view === 'reset') && (
@@ -328,20 +412,20 @@ export default function Login() {
copy={copy}
email={email.trim()}
code={code}
- onCodeChange={setCode}
+ onCodeChange={changeCode}
+ error={errorFor('code')}
loading={loading}
onSubmit={handleSubmit}
resendIn={resendIn}
resending={resending}
onResend={handleResend}
- ready={view !== 'reset' || password.length >= PASSWORD_MIN_LENGTH}
>
{view === 'reset' && (
- <FieldRow label="New password" htmlFor="password">
+ <FieldRow label="New password" htmlFor="password" hint={`At least ${PASSWORD_MIN_LENGTH} characters.`} error={errorFor('password')}>
<PasswordInput
id="password"
value={password}
- onChange={setPassword}
+ onChange={changePassword}
placeholder={`At least ${PASSWORD_MIN_LENGTH} characters`}
autoComplete="new-password"
showPassword={showPassword}
diff --git a/frontend/src/pages/LoginBackdrop.tsx b/frontend/src/pages/LoginBackdrop.tsx
index 0ae2c7b..a032117 100644
--- a/frontend/src/pages/LoginBackdrop.tsx
+++ b/frontend/src/pages/LoginBackdrop.tsx
@@ -33,6 +33,7 @@ export default function LoginBackdrop() {
return (
<div
aria-hidden="true"
+ inert
className="pointer-events-none fixed inset-0 flex animate-in overflow-hidden duration-500 select-none fade-in"
>
<aside className="hidden w-(--sidebar-w) shrink-0 flex-col gap-5 border-r border-sidebar-border bg-sidebar px-3 py-4 md:flex">
@@ -64,7 +65,7 @@ export default function LoginBackdrop() {
<div className="flex h-(--topbar-h) shrink-0 items-center border-b border-line px-6 text-sm font-medium text-ink">
Overview
</div>
- <main className="flex flex-col gap-6 p-8">
+ <div className="flex flex-col gap-6 p-8">
<PageHeader
size="display"
title="Good morning, Asha"
@@ -103,7 +104,7 @@ export default function LoginBackdrop() {
))}
</SurfaceBox>
</div>
- </main>
+ </div>
</div>
</div>
);
diff --git a/frontend/src/pages/LoginCodeForm.tsx b/frontend/src/pages/LoginCodeForm.tsx
index e55255a..9c0e9db 100644
--- a/frontend/src/pages/LoginCodeForm.tsx
+++ b/frontend/src/pages/LoginCodeForm.tsx
@@ -20,16 +20,16 @@ export interface LoginCodeFormProps {
onResend: () => void;
// more fields after the code, such as the new password on the reset step
children?: ReactNode;
- // false while those fields are not ready; the code length is checked here
- ready?: boolean;
+ error?: string;
}
+// the button stays enabled: a short code is explained under the field instead of a silent grey button
export default function LoginCodeForm({
- copy, email, code, onCodeChange, loading, onSubmit, resendIn, resending, onResend, children, ready = true,
+ copy, email, code, onCodeChange, loading, onSubmit, resendIn, resending, onResend, children, error,
}: LoginCodeFormProps) {
return (
- <form onSubmit={onSubmit} className="flex flex-col gap-4">
- <FieldRow label="Verification code" htmlFor="code">
+ <form onSubmit={onSubmit} noValidate className="flex flex-col gap-4">
+ <FieldRow label="Verification code" htmlFor="code" error={error}>
<Input
id="code"
className="h-(--control-h-lg) text-center font-mono text-lg tracking-[0.4em]"
@@ -39,7 +39,6 @@ export default function LoginCodeForm({
required
inputMode="numeric"
autoComplete="one-time-code"
- pattern={`\\d{${CODE_LENGTH}}`}
maxLength={CODE_LENGTH + 4}
aria-describedby="code-help"
autoFocus
@@ -49,14 +48,15 @@ export default function LoginCodeForm({
Sent to <span className="font-medium text-ink">{email}</span>. If it has not arrived, check your spam folder.
</p>
{children}
- <Button type="submit" size="lg" className="mt-2 w-full" disabled={loading || !ready || code.length !== CODE_LENGTH}>
+ <Button type="submit" size="lg" className="mt-2 w-full" disabled={loading}>
{loading && <Spinner className="size-4" />}
{loading ? copy.busy : copy.submit}
</Button>
<Button type="button" variant="ghost" size="sm" className="self-center" onClick={onResend} disabled={resending || resendIn > 0}>
{resending ? <Spinner className="size-4" /> : <RotateCw data-icon="inline-start" />}
- {resendIn > 0 ? `Send a new code in ${resendIn}s` : 'Send a new code'}
+ {resending ? 'Sending a new code' : resendIn > 0 ? `Send a new code in ${resendIn}s` : 'Send a new code'}
</Button>
+ {resendIn > 0 && <p className="-mt-2 text-center text-small text-ink-muted">Email providers allow one code a minute.</p>}
</form>
);
}
diff --git a/frontend/src/pages/LoginEmailForm.tsx b/frontend/src/pages/LoginEmailForm.tsx
index fc5d95d..e627445 100644
--- a/frontend/src/pages/LoginEmailForm.tsx
+++ b/frontend/src/pages/LoginEmailForm.tsx
@@ -11,12 +11,13 @@ export interface LoginEmailFormProps {
onEmailChange: (value: string) => void;
loading: boolean;
onSubmit: (e: FormEvent<HTMLFormElement>) => void;
+ error?: string;
}
-export default function LoginEmailForm({ copy, email, onEmailChange, loading, onSubmit }: LoginEmailFormProps) {
+export default function LoginEmailForm({ copy, email, onEmailChange, loading, onSubmit, error }: LoginEmailFormProps) {
return (
- <form onSubmit={onSubmit} className="flex flex-col gap-4">
- <FieldRow label="Email" htmlFor="email">
+ <form onSubmit={onSubmit} noValidate className="flex flex-col gap-4">
+ <FieldRow label="Email" htmlFor="email" error={error}>
<Input
id="email"
type="email"
diff --git a/frontend/src/pages/LoginEmailStart.tsx b/frontend/src/pages/LoginEmailStart.tsx
index bc907e8..a69c30f 100644
--- a/frontend/src/pages/LoginEmailStart.tsx
+++ b/frontend/src/pages/LoginEmailStart.tsx
@@ -2,35 +2,39 @@ import type { FormEvent } from 'react';
import { ArrowRight, Mail } from 'lucide-react';
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
import { Spinner } from '@/components/ui/spinner';
-import { looksLikeEmail } from '@/lib/emailAddress';
+import { fieldErrorId } from '@/lib/fieldIds';
export interface LoginEmailStartProps {
email: string;
onEmailChange: (value: string) => void;
loading: boolean;
onSubmit: (e: FormEvent<HTMLFormElement>) => void;
+ error?: string;
}
-// one field for the address with the Continue arrow inside it; the arrow wakes up once the address looks complete
-export default function LoginEmailStart({ email, onEmailChange, loading, onSubmit }: LoginEmailStartProps) {
+// one field for the address with the Continue arrow inside it; a missing or incomplete address is explained under
+// the field when the arrow is pressed, rather than the arrow greying out without saying why
+export default function LoginEmailStart({ email, onEmailChange, loading, onSubmit, error }: LoginEmailStartProps) {
return (
- <form onSubmit={onSubmit}>
- {/* the group dims itself when anything in it is disabled, and only the arrow should; its focus is one red border
- with a faint halo instead of the default wide ring */}
- <InputGroup className="h-12 rounded-field bg-surface-raised has-disabled:bg-surface-raised has-disabled:opacity-100 dark:has-disabled:bg-surface-raised has-[[data-slot=input-group-control]:focus-visible]:ring-2 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/15">
+ <form onSubmit={onSubmit} noValidate className="flex flex-col gap-2">
+ <label htmlFor="email" className="text-sm font-medium text-ink">Email</label>
+ {/* the group dims itself when anything in it is disabled, and only the arrow should; focus shows on the
+ group's own border and faint halo, because the input inside it has none of its own */}
+ <InputGroup className="h-12 rounded-field bg-surface-raised has-disabled:bg-surface-raised has-disabled:opacity-100 dark:has-disabled:bg-surface-raised">
<InputGroupAddon>
- <Mail className="ml-1.5 text-ink-faint" />
+ <Mail className="ml-1.5 text-ink-faint" aria-hidden="true" />
</InputGroupAddon>
<InputGroupInput
id="email"
type="email"
- aria-label="Email"
placeholder="[email protected]"
value={email}
onChange={e => onEmailChange(e.target.value)}
required
autoComplete="email"
autoFocus
+ aria-invalid={error ? true : undefined}
+ aria-describedby={error ? fieldErrorId('email') : undefined}
className="focus-visible:outline-none"
/>
<InputGroupAddon align="inline-end">
@@ -40,12 +44,15 @@ export default function LoginEmailStart({ email, onEmailChange, loading, onSubmi
size="icon-sm"
className="mr-1.5 size-9 rounded-control"
aria-label="Continue with email"
- disabled={loading || !looksLikeEmail(email)}
+ disabled={loading}
>
{loading ? <Spinner className="size-4" /> : <ArrowRight />}
</InputGroupButton>
</InputGroupAddon>
</InputGroup>
+ {error && (
+ <p id={fieldErrorId('email')} className="text-sm text-danger"><span className="sr-only">Error: </span>{error}</p>
+ )}
</form>
);
}
diff --git a/frontend/src/pages/LoginPasswordForm.tsx b/frontend/src/pages/LoginPasswordForm.tsx
index 4b7f3af..6ab42bd 100644
--- a/frontend/src/pages/LoginPasswordForm.tsx
+++ b/frontend/src/pages/LoginPasswordForm.tsx
@@ -3,6 +3,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import { FieldRow } from '@/components/DetailPanel';
+import { fieldErrorId } from '@/lib/fieldIds';
import { PASSWORD_MIN_LENGTH } from '@/lib/passwords';
import PasswordInput from './PasswordInput';
import type { LoginCopy } from './loginCopy';
@@ -15,6 +16,8 @@ export interface LoginPasswordFormProps {
password: string;
onEmailChange: (value: string) => void;
onPasswordChange: (value: string) => void;
+ emailError?: string;
+ passwordError?: string;
showPassword: boolean;
onTogglePassword: () => void;
loading: boolean;
@@ -31,6 +34,8 @@ export default function LoginPasswordForm({
password,
onEmailChange,
onPasswordChange,
+ emailError,
+ passwordError,
showPassword,
onTogglePassword,
loading,
@@ -39,10 +44,10 @@ export default function LoginPasswordForm({
onSwitch,
}: LoginPasswordFormProps) {
const quietLink =
- 'rounded-sm text-caption text-ink-muted transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring';
+ 'inline-flex min-h-6 items-center rounded-sm text-small text-ink-muted transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring';
return (
- <form onSubmit={onSubmit} className="flex flex-col gap-4">
- <FieldRow label="Email" htmlFor="email">
+ <form onSubmit={onSubmit} noValidate className="flex flex-col gap-4">
+ <FieldRow label="Email" htmlFor="email" error={emailError}>
<Input
id="email"
type="email"
@@ -74,13 +79,17 @@ export default function LoginPasswordForm({
autoComplete={isSignUp ? 'new-password' : 'current-password'}
showPassword={showPassword}
onTogglePassword={onTogglePassword}
+ error={passwordError}
/>
+ {passwordError && (
+ <p id={fieldErrorId('password')} className="text-sm text-danger"><span className="sr-only">Error: </span>{passwordError}</p>
+ )}
</div>
<Button type="submit" size="lg" className="mt-1 w-full" disabled={loading}>
{loading && <Spinner className="size-4" />}
{loading ? copy.busy : copy.submit}
</Button>
- <p className="text-center text-caption text-ink-muted">
+ <p className="text-center text-small text-ink-muted">
{isSignUp ? 'Already have an account?' : 'No account yet?'}{' '}
<button type="button" onClick={onSwitch} className={`font-medium text-ink ${quietLink}`}>
{isSignUp ? 'Sign in' : 'Create one with a password'}
diff --git a/frontend/src/pages/PasswordInput.tsx b/frontend/src/pages/PasswordInput.tsx
index f7735b8..1873453 100644
--- a/frontend/src/pages/PasswordInput.tsx
+++ b/frontend/src/pages/PasswordInput.tsx
@@ -11,9 +11,15 @@ export interface PasswordInputProps {
autoComplete: 'current-password' | 'new-password';
showPassword: boolean;
onTogglePassword: () => void;
+ error?: string;
+ 'aria-describedby'?: string;
+ 'aria-invalid'?: boolean;
}
-export default function PasswordInput({ id, value, onChange, placeholder, autoComplete, showPassword, onTogglePassword }: PasswordInputProps) {
+// the error text is rendered by the caller (FieldRow or the password form); this wires the input to it
+export default function PasswordInput({
+ id, value, onChange, placeholder, autoComplete, showPassword, onTogglePassword, error, ...aria
+}: PasswordInputProps) {
return (
<div className="relative">
<Input
@@ -26,6 +32,8 @@ export default function PasswordInput({ id, value, onChange, placeholder, autoCo
required
minLength={PASSWORD_MIN_LENGTH}
autoComplete={autoComplete}
+ aria-invalid={error || aria['aria-invalid'] ? true : undefined}
+ aria-describedby={aria['aria-describedby'] ?? (error ? `${id}-error` : undefined)}
/>
<Button
type="button"
diff --git a/frontend/src/pages/loginCopy.ts b/frontend/src/pages/loginCopy.ts
index 8a5ccbb..1fd77cf 100644
--- a/frontend/src/pages/loginCopy.ts
+++ b/frontend/src/pages/loginCopy.ts
@@ -13,7 +13,7 @@ export interface LoginCopy {
export const LOGIN_COPY: Record<LoginView, LoginCopy> = {
start: { title: 'Every channel, folded into one clear picture.', submit: 'Continue', busy: 'Sending code' },
- code: { title: 'Check your email', submit: 'Continue', busy: 'Checking' },
+ code: { title: 'Check your email', submit: 'Sign in', busy: 'Signing in' },
password: { title: 'Sign in with password', submit: 'Sign in', busy: 'Signing in' },
signup: { title: 'Create an account with a password', submit: 'Create account', busy: 'Creating account' },
verify: { title: 'Confirm your email', submit: 'Confirm email', busy: 'Confirming' },
@@ -21,5 +21,19 @@ export const LOGIN_COPY: Record<LoginView, LoginCopy> = {
reset: { title: 'Choose a new password', submit: 'Save password and sign in', busy: 'Saving' },
};
+// the field a sign-in problem belongs to, shown under that field
+export type LoginField = 'email' | 'code' | 'password';
+
+// where a failure from the server is shown on each view
+export const FAILURE_FIELD: Record<LoginView, LoginField> = {
+ start: 'email',
+ code: 'code',
+ password: 'password',
+ signup: 'password',
+ verify: 'code',
+ forgot: 'email',
+ reset: 'code',
+};
+
// the public site's Get started buttons open /login?mode=signup; the same code creates the account
export const SIGN_UP_TITLE = 'Create your Twiligent account';
diff --git a/frontend/tests/features/accounts/accountManagerData.test.ts b/frontend/tests/features/accounts/accountManagerData.test.ts
index 4e8d0a8..2be4df0 100644
--- a/frontend/tests/features/accounts/accountManagerData.test.ts
+++ b/frontend/tests/features/accounts/accountManagerData.test.ts
@@ -1,8 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
- TESTER_HINT, instagramErrorMessage, readOAuthReturn, accountMetrics, accountCardHandle, visibleSections,
-} from '../../../src/features/accounts/accountManagerData.ts';
+ TESTER_HINT, instagramErrorMessage, readOAuthReturn, accountMetrics, accountCardHandle, visibleSections, redditUsername, redditFieldsProblem, channelFieldProblem } from '../../../src/features/accounts/accountManagerData.ts';
const params = (query: string) => new URLSearchParams(query);
@@ -55,3 +54,17 @@ test('only platforms with accounts get a section, in a fixed order', () => {
const groups = { youtube: [], instagram: [{ id: 1 }], reddit: [{ id: 2 }] };
assert.deepEqual(visibleSections(groups).map(section => section.key), ['instagram', 'reddit']);
});
+
+test('a Reddit username is taken from u/name, @name or a pasted profile address', () => {
+ assert.equal(redditUsername(' u/spez '), 'spez');
+ assert.equal(redditUsername('@spez'), 'spez');
+ assert.equal(redditUsername('https://www.reddit.com/user/spez/'), 'spez');
+});
+
+test('adding an account names the missing field first', () => {
+ assert.equal(redditFieldsProblem('u/', 'abc')?.field, 'username');
+ assert.equal(redditFieldsProblem('spez', ' ')?.field, 'cookie');
+ assert.equal(redditFieldsProblem('spez', 'abc'), null);
+ assert.equal(channelFieldProblem(' ')?.field, 'channel');
+ assert.equal(channelFieldProblem('@channel'), null);
+});
diff --git a/frontend/tests/features/analytics/tracked/viewsInput.test.ts b/frontend/tests/features/analytics/tracked/viewsInput.test.ts
new file mode 100644
index 0000000..30dfb07
--- /dev/null
+++ b/frontend/tests/features/analytics/tracked/viewsInput.test.ts
@@ -0,0 +1,15 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { normalizeViewsText } from '../../../../src/features/analytics/tracked/viewsInput.ts';
+
+test('views copied with separators or a K or M suffix become a plain number', () => {
+ assert.equal(normalizeViewsText('12,500'), '12500');
+ assert.equal(normalizeViewsText(' 12 500 '), '12500');
+ assert.equal(normalizeViewsText('12.5K'), '12500');
+ assert.equal(normalizeViewsText('1.2m views'), '1200000');
+ assert.equal(normalizeViewsText(''), '');
+});
+
+test('text that is not a number is passed on unchanged, so the views check can explain it', () => {
+ assert.equal(normalizeViewsText('lots'), 'lots');
+});
diff --git a/frontend/tests/features/automations/automationData.test.ts b/frontend/tests/features/automations/automationData.test.ts
index c231b2e..5e4ff2b 100644
--- a/frontend/tests/features/automations/automationData.test.ts
+++ b/frontend/tests/features/automations/automationData.test.ts
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
import {
ACTIVITY_FILTERS, DEFAULT_FOLLOW_PROMPT, DEFAULT_NOT_FOLLOWING, DEFAULT_PUBLIC_REPLY, MAX_MESSAGE_BYTES, accountStatus, canRetry, canRetryPublic,
composeReply, emptyRuleForm, formToRequest, gateDetail, matchModeLabel, messageBytes, needsMessageEvents, parseKeywords, periodStart,
- publicReplyTexts, publicStatusDisplay, ruleFormProblem, ruleScopeLabel, ruleToForm, statusDisplay, summarizeStats,
+ publicReplyTexts, publicStatusDisplay, ruleFormProblem, ruleFormError, normalizeLink, ruleScopeLabel, ruleToForm, statusDisplay, summarizeStats,
} from '../../../src/features/automations/automationData.ts';
import type { RuleForm } from '../../../src/features/automations/automationData.ts';
import type { AutomationAccountState, AutomationRule } from '../../../../shared/types/automation.ts';
@@ -143,7 +143,8 @@ test('the form names the first thing to fix, in the order of the fields', () =>
assert.equal(ruleFormProblem(form({ scope: 'selected' })), 'Choose at least one post, or answer comments on every post');
assert.equal(ruleFormProblem(form({ replyText: '' })), 'Write the reply to send');
assert.equal(ruleFormProblem(form({ linkUrl: 'http://e.com' })), 'The link must start with https://');
- assert.equal(ruleFormProblem(form({ linkUrl: 'e.com' })), 'The link must be a full address starting with https://');
+ assert.equal(ruleFormProblem(form({ linkUrl: 'e.com' })), null);
+ assert.equal(ruleFormProblem(form({ linkUrl: 'guide' })), 'The link must be a full address, such as https://example.com/guide');
assert.equal(ruleFormProblem(form({ hourlyLimit: '0' })), 'The hourly limit must be a whole number from 1 to 750');
assert.equal(ruleFormProblem(form({ hourlyLimit: '2.5' })), 'The hourly limit must be a whole number from 1 to 750');
assert.match(ruleFormProblem(form({ replyText: 'é'.repeat(MAX_MESSAGE_BYTES / 2 + 1) }))!, /is 1002 bytes; Instagram accepts at most 1000/);
@@ -205,3 +206,21 @@ test('an account needs message events only while one of its followers-only rules
assert.equal(needsMessageEvents(rules, 'ig1'), false);
assert.equal(needsMessageEvents(rules, 'ig2'), true);
});
+
+test('a link typed without a scheme is saved as an https address', () => {
+ assert.equal(normalizeLink(' example.com/guide '), 'https://example.com/guide');
+ assert.equal(normalizeLink('//example.com'), 'https://example.com');
+ assert.equal(normalizeLink('https://example.com'), 'https://example.com');
+ assert.equal(normalizeLink(''), '');
+ assert.equal(formToRequest(form({ linkUrl: 'example.com/guide' })).linkUrl, 'https://example.com/guide');
+});
+
+test('each rule problem names the field it belongs to', () => {
+ assert.deepEqual(ruleFormError(form({ name: '' })), { field: 'name', message: 'Give the rule a name' });
+ assert.equal(ruleFormError(form({ keywordsText: '' }))?.field, 'keywordsText');
+ assert.equal(ruleFormError(form({ linkUrl: 'http://e.com' }))?.field, 'linkUrl');
+ assert.equal(ruleFormError(form({ hourlyLimit: '0' }))?.field, 'hourlyLimit');
+ assert.equal(ruleFormError(form({ privateReplyEnabled: false, publicReplyEnabled: false }))?.field, 'replies');
+ assert.equal(ruleFormError(form({ requireFollow: true, notFollowingText: '' }))?.field, 'notFollowingText');
+ assert.equal(ruleFormError(form()), null);
+});
diff --git a/frontend/tests/features/publishing/publishHelpers.test.ts b/frontend/tests/features/publishing/publishHelpers.test.ts
index be3ab12..baf0b46 100644
--- a/frontend/tests/features/publishing/publishHelpers.test.ts
+++ b/frontend/tests/features/publishing/publishHelpers.test.ts
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import {
parseUserTags, parseCollaborators, buildScheduledPostPayload, buildContainerPayload, bulkPostDetails,
singleUploadMessage, singlePostError, bulkStartError, bulkBaseTime, editPostError, bulkScheduledTime,
+ singlePostProblem, bulkStartProblem, editPostProblem, thumbOffsetMs, instagramUsername,
} from '../../../src/features/publishing/publishHelpers.ts';
import type { AccountPostDetails, BulkSettings, UploadFailure } from '../../../src/features/publishing/publishHelpers.ts';
import type { ScheduleFieldValues } from '../../../src/features/publishing/scheduleHelpers.ts';
@@ -10,7 +11,7 @@ import type { ScheduleFieldValues } from '../../../src/features/publishing/sched
const scheduledAt = new Date('2030-05-01T08:00:00Z');
const fullPost: AccountPostDetails = {
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',
+ shareToFeed: false, collaborators: 'one, two ,', audioName: 'Song', thumbOffset: '1.5', locationId: '42',
userTags: '@ann 0.2 0.3, bob', altText: 'Alt',
};
const bulkSettings: BulkSettings = {
@@ -118,3 +119,34 @@ 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');
});
+
+test('collaborators may be typed with an @ or pasted as a profile address', () => {
+ assert.deepEqual(parseCollaborators('@one, https://www.instagram.com/two/'), ['one', 'two']);
+ assert.equal(instagramUsername(' @three '), 'three');
+});
+
+test('the thumbnail offset is typed in seconds and sent in milliseconds', () => {
+ assert.equal(thumbOffsetMs('1.5'), 1500);
+ assert.equal(thumbOffsetMs('2,25'), 2250);
+ assert.equal(thumbOffsetMs(''), null);
+ assert.equal(thumbOffsetMs('-1'), null);
+});
+
+test('each publishing problem names the field to fix, in the order of the form', () => {
+ const now = new Date('2030-05-01T00:00:00');
+ const fields = { scheduleMode: true, scheduleDate: '2030-05-02', scheduleTime: '08:00' } as ScheduleFieldValues;
+ const file = {} as File;
+ const base = { selectedAccount: 'ig1', file, contentType: 'IMAGE', hasCloudConfig: true, fields, now };
+ assert.equal(singlePostProblem({ ...base, selectedAccount: '' })?.field, 'account');
+ assert.equal(singlePostProblem({ ...base, contentType: '' })?.field, 'contentType');
+ assert.equal(singlePostProblem({ ...base, file: null })?.field, 'file');
+ assert.equal(singlePostProblem({ ...base, hasCloudConfig: false })?.field, 'server');
+ assert.equal(singlePostProblem({ ...base, fields: { ...fields, scheduleDate: '2030-04-30' } })?.field, 'schedule');
+ assert.equal(singlePostProblem(base), null);
+ assert.equal(bulkStartProblem({ settings: bulkSettings, fileCount: 0, hasCloudConfig: true, now })?.field, 'files');
+ assert.equal(bulkStartProblem({ settings: { ...bulkSettings, account: '' }, fileCount: 2, hasCloudConfig: true, now })?.field, 'account');
+ assert.equal(bulkStartProblem({ settings: bulkSettings, fileCount: 2, hasCloudConfig: true, now }), null);
+ assert.equal(editPostProblem({ postId: 'p', date: '2030-05-02', time: '', now })?.field, 'time');
+ assert.equal(editPostProblem({ postId: 'p', date: '', time: '08:00', now })?.field, 'date');
+ assert.equal(editPostProblem({ postId: 'p', date: '2030-05-02', time: '08:00', now }), null);
+});
diff --git a/frontend/tests/features/publishing/scheduleHelpers.test.ts b/frontend/tests/features/publishing/scheduleHelpers.test.ts
index 0b16361..6bb7ac2 100644
--- a/frontend/tests/features/publishing/scheduleHelpers.test.ts
+++ b/frontend/tests/features/publishing/scheduleHelpers.test.ts
@@ -2,7 +2,7 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
OVERDUE_MS, PUBLISH_LEASE_MS, isRetrying, scheduledStatusChips, filterScheduledPosts, overduePostsOf, isPastDue, overdueLead, deleteAllMessage,
- formatScheduleDate, toLocalDateInput, toLocalTimeInput, utcDateInput, defaultBulkStartDate, goesLiveLabel,
+ formatScheduleDate, toLocalDateInput, toLocalTimeInput, todayInput, defaultBulkStartDate, goesLiveLabel,
} from '../../../src/features/publishing/scheduleHelpers.ts';
import type { ScheduleTiming } from '../../../src/features/publishing/scheduleHelpers.ts';
@@ -68,11 +68,10 @@ test('local inputs use the local calendar and clock', () => {
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 default bulk start and the earliest day follow the local calendar, even late in the evening', () => {
+ const lateEvening = new Date(2030, 0, 5, 23, 30);
+ assert.equal(defaultBulkStartDate(lateEvening), '2030-01-06');
+ assert.equal(todayInput(lateEvening), '2030-01-05');
});
test('the goes live label follows the schedule fields', () => {
diff --git a/frontend/tests/features/settings/settingsData.test.ts b/frontend/tests/features/settings/settingsData.test.ts
index 504e6e2..34a3e47 100644
--- a/frontend/tests/features/settings/settingsData.test.ts
+++ b/frontend/tests/features/settings/settingsData.test.ts
@@ -1,7 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
- loadServerSettings, githubSettingsPayload, healthCheckResult, healthCheckFailure,
+ loadServerSettings, githubSettingsPayload, healthCheckResult, healthCheckFailure, githubOwner, githubRepoFromUrl,
} from '../../../src/features/settings/settingsData.ts';
import type { ServerSettingsClient } from '../../../src/features/settings/settingsData.ts';
import type { GitHubSettingsResponse, KeysStatusResponse } from '../../../../shared/types/domain.ts';
@@ -96,3 +96,12 @@ test('health results explain what to check', () => {
assert.equal(healthCheckFailure(new Error('timeout')).success, false);
assert.ok(healthCheckFailure(new Error('timeout')).message.startsWith('The API could not be reached: timeout.'));
});
+
+test('a GitHub user name is taken from an @name or a pasted profile or repository address', () => {
+ assert.equal(githubOwner(' @octocat '), 'octocat');
+ assert.equal(githubOwner('https://github.com/octocat'), 'octocat');
+ assert.equal(githubOwner('github.com/octocat/twiligent'), 'octocat');
+ assert.equal(githubOwner('octocat'), 'octocat');
+ assert.equal(githubRepoFromUrl('https://github.com/octocat/my-twiligent.git'), 'my-twiligent');
+ assert.equal(githubRepoFromUrl('octocat'), null);
+});
diff --git a/frontend/tests/lib/passwords.test.ts b/frontend/tests/lib/passwords.test.ts
index 3efdaa3..509f3ab 100644
--- a/frontend/tests/lib/passwords.test.ts
+++ b/frontend/tests/lib/passwords.test.ts
@@ -1,14 +1,20 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { PASSWORD_MIN_LENGTH, newPasswordProblem } from '../../src/lib/passwords.ts';
+import { PASSWORD_MIN_LENGTH, newPasswordError, newPasswordProblem } from '../../src/lib/passwords.ts';
test('a new password needs the minimum length and a matching confirmation', () => {
assert.equal(PASSWORD_MIN_LENGTH, 6);
assert.equal(newPasswordProblem('12345', '12345'), 'Use at least 6 characters.');
- assert.equal(newPasswordProblem('123456', '123457'), 'The two passwords do not match.');
+ assert.equal(newPasswordProblem('123456', '123457'), 'The two passwords do not match. Type the same password in both fields.');
assert.equal(newPasswordProblem('123456', '123456'), null);
});
+test('each password problem names the field to fix', () => {
+ assert.equal(newPasswordError('abc', 'abc')?.field, 'password');
+ assert.equal(newPasswordError('123456', '')?.field, 'confirmation');
+ assert.equal(newPasswordError('123456', '123456'), null);
+});
+
test('length is checked before the confirmation, so a short password says what to fix first', () => {
assert.equal(newPasswordProblem('abc', 'xyz'), 'Use at least 6 characters.');
});
diff --git a/frontend/tests/lib/sessionDraft.test.ts b/frontend/tests/lib/sessionDraft.test.ts
new file mode 100644
index 0000000..a2bf0b1
--- /dev/null
+++ b/frontend/tests/lib/sessionDraft.test.ts
@@ -0,0 +1,31 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { clearDraft, readDraft, writeDraft } from '../../src/lib/sessionDraft.ts';
+import type { DraftStorage } from '../../src/lib/sessionDraft.ts';
+
+function memoryStorage(): DraftStorage & { data: Map<string, string> } {
+ const data = new Map<string, string>();
+ return {
+ data,
+ getItem: key => data.get(key) ?? null,
+ setItem: (key, value) => { data.set(key, value); },
+ removeItem: key => { data.delete(key); },
+ };
+}
+
+test('a written draft reads back the same and clears', () => {
+ const storage = memoryStorage();
+ writeDraft('rule:new', { name: 'Free guide' }, storage);
+ assert.deepEqual(readDraft('rule:new', storage), { name: 'Free guide' });
+ clearDraft('rule:new', storage);
+ assert.equal(readDraft('rule:new', storage), null);
+});
+
+test('a missing, broken or blocked storage gives no draft instead of an error', () => {
+ assert.equal(readDraft('rule:new', null), null);
+ const storage = memoryStorage();
+ storage.data.set('twiligent:draft:rule:new', '{not json');
+ assert.equal(readDraft('rule:new', storage), null);
+ const full: DraftStorage = { getItem: () => null, setItem: () => { throw new Error('QuotaExceededError'); }, removeItem: () => {} };
+ assert.doesNotThrow(() => writeDraft('rule:new', { name: 'x' }, full));
+});
diff --git a/site/content/docs/use/automations.mdx b/site/content/docs/use/automations.mdx
index ffe230b..447a46e 100644
--- a/site/content/docs/use/automations.mdx
+++ b/site/content/docs/use/automations.mdx
@@ -10,16 +10,18 @@ You need an Instagram Business or Creator account connected with Instagram sign-
## Create a rule
-1. Open **Automations** in the sidebar and choose **New rule**.
+1. Open **Automations** in the sidebar and choose **New rule**. The rule opens on its own page.
2. Choose the Instagram account, give the rule a name, and type its keywords, separated by commas.
3. Choose how comments match. **Anywhere in the comment, as a whole word** answers "send me the guide please" for GUIDE but not "guidelines". **The whole comment, nothing else** answers only a comment that is the keyword. **Any comment, no keyword needed** answers everyone who comments.
4. Choose **Every post and reel**, or **Only the posts I choose** and pick them.
5. Under **Send a private reply**, write the reply and, if you like, a link. Turn the switch off if the rule should answer only in public.
6. Under **Reply publicly under the comment**, turn the switch on to post a public reply as well, and write one to five wordings. Each comment gets one of them.
7. The preview shows the public reply under a comment and the private message as it will arrive, with how much of Instagram's 1,000 byte limit the message uses. Type a sample comment under **Test a comment** and choose **Test** to see whether it would match. Nothing is sent or posted.
-8. Leave **Turn the rule on when saved** on, and choose **Create rule**.
+8. Leave **Turn the rule on when saved** on, and choose **Create rule**. If something is missing, the field it concerns says what to fix.
-A comment is answered by one rule, the most specific one that answers it, with that rule's private reply, public reply or both: rules for chosen posts come before rules for every post, and keyword rules before any-comment rules. Among equals, the oldest rule answers. You can copy a rule (the copy starts off), change it, turn it off, or delete it.
+Your changes are kept in the browser tab while you edit, so a reload or a wrong click does not lose them, and Twiligent asks before you leave a rule with unsaved changes.
+
+A comment is answered by one rule, the most specific one that answers it, with that rule's private reply, public reply or both: rules for chosen posts come before rules for every post, and keyword rules before any-comment rules. Among equals, the oldest rule answers. You can copy a rule (the copy starts off), change it, turn it off, or delete it. A deleted rule can be brought back with **Undo** for a few seconds.
<Callout type="warning" title="Any comment means everyone">
diff --git a/site/content/docs/use/connect-accounts.mdx b/site/content/docs/use/connect-accounts.mdx
index 18acd28..a5b4013 100644
--- a/site/content/docs/use/connect-accounts.mdx
+++ b/site/content/docs/use/connect-accounts.mdx
@@ -43,7 +43,7 @@ Reddit blocks most requests from servers, so Twiligent uses your browser session
1. Sign in to reddit.com in your browser.
2. Open the browser's developer tools (F12), then **Application**, then **Cookies**, then `https://www.reddit.com`.
3. Find the cookie named `reddit_session` and copy its value.
-4. In Twiligent choose **Add account**, **Reddit account**, enter your username and paste the cookie.
+4. In Twiligent choose **Add account**, **Reddit account**, enter your username (`name`, `u/name` or the address of your profile all work) and paste the cookie.
<Callout type="warning" title="Treat the cookie like a password">
diff --git a/site/content/docs/use/publishing.mdx b/site/content/docs/use/publishing.mdx
index d04eebf..3f57182 100644
--- a/site/content/docs/use/publishing.mdx
+++ b/site/content/docs/use/publishing.mdx
@@ -10,7 +10,9 @@ Open **Publish**, pick **Photo**, **Reel** or **Story**, then choose the file. P
</Step>
<Step title="Write the caption and settings">
-Write the caption (up to 2,200 characters). In the panel on the right, pick the account and optionally add alt text, collaborators, tagged people, a location, and for Reels a cover image and audio name.
+Write the caption (up to 2,200 characters). In the panel on the right, pick the account and optionally add alt text. Collaborators, tagged people and a location are under **More options**; a location is the ID of the place's Facebook Page. For Reels you can add a cover image, an audio name and the time in seconds of the frame to show as the thumbnail.
+
+The caption and settings are kept in the browser tab, so a reload does not lose them; choose the file again after a reload. If something is missing when you choose **Publish now**, the field it concerns says what to fix. While Instagram processes a video, the page shows how long it has waited and offers **Stop waiting**.
</Step>
<Step title="Publish now or schedule">
@@ -26,7 +28,7 @@ The file uploads straight away. The server publishes the post within 15 minutes
| Status | Meaning |
| --- | --- |
-| **Pending** | Waiting for its time. You can edit the caption and time, or delete it. When it shows **Trying again on the next run**, the last attempt hit a passing problem and the Error column says which. |
+| **Pending** | Waiting for its time. You can edit the caption and time, or delete it; **Undo** brings a deleted post back for a few seconds. When it shows **Trying again on the next run**, the last attempt hit a passing problem and the Error column says which. |
| **Publishing** | The server is publishing it right now. It cannot be edited or deleted until it finishes. |
| **Published** | Live on Instagram. |
| **Failed** | Instagram rejected it, or three attempts in a row hit a problem. The Error column says why. Schedule the post again once the cause is fixed. |
@@ -39,7 +41,7 @@ A post still Pending 30 minutes after its time (or after its last attempt), or s
## Bulk upload
-Choose **Bulk upload** to add many files at once. Give each file its own caption or apply one caption to all, then either publish them one after another or **spread them out** from a start time at an interval such as once a day.
+Choose **Bulk upload** to add many files at once. Give each file its own caption or apply one caption to all, then either publish them one after another or **spread them out** from a start time at an interval such as once a day. Applying a caption and **Clear all** both offer **Undo**. Stay on the page until the files are done: leaving stops the files that have not started.
## Limits