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)!: remove the Reddit analytics pages

spacesdrive468d66d06e11
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 1466e4b..43c5f5c 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,5 +1,5 @@
import React, { lazy, Suspense } from 'react';
-import { createBrowserRouter, RouterProvider, Navigate } from 'react-router-dom';
+import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { ThemeProvider } from 'next-themes';
import { Toaster } from '@/components/ui/sonner';
import { TooltipProvider } from '@/components/ui/tooltip';
@@ -23,9 +23,6 @@ const Automations = lazy(() => import('./features/automations/Automations
const RuleEditorPage = lazy(() => import('./features/automations/RuleEditorPage'));
const AccountManager = lazy(() => import('./features/accounts/AccountManager'));
const Settings = lazy(() => import('./features/settings/Settings'));
-const RedditAnalytics = lazy(() => import('./features/analytics/reddit/RedditAnalytics'));
-const RedditPosts = lazy(() => import('./features/analytics/reddit/RedditPosts'));
-const RedditPostsAll = lazy(() => import('./features/analytics/reddit/RedditPostsAll'));
const TrackedContent = lazy(() => import('./features/analytics/tracked/TrackedContent'));
const TrackedCategory = lazy(() => import('./features/analytics/tracked/TrackedCategory'));
const NotFound = lazy(() => import('./pages/NotFound'));
@@ -63,12 +60,8 @@ const router = createBrowserRouter([
{ path: 'automations/rules/:id', element: <RuleEditorPage /> },
{ path: 'accounts', element: <AccountManager /> },
{ path: 'settings', element: <Settings /> },
- { path: 'reddit/:id', element: <RedditAnalytics /> },
- { path: 'reddit-posts', element: <RedditPostsAll /> },
- { path: 'reddit-posts/:id', element: <RedditPosts /> },
{ path: 'tracked-content', element: <TrackedContent /> },
{ path: 'tracked-content/category/:name', element: <TrackedCategory /> },
- { path: 'reddit-tracked', element: <Navigate to="/tracked-content" replace /> },
{ path: '*', element: <NotFound /> },
],
},
diff --git a/frontend/src/features/analytics/reddit/RedditAnalytics.tsx b/frontend/src/features/analytics/reddit/RedditAnalytics.tsx
deleted file mode 100644
index ee2aba3..0000000
--- a/frontend/src/features/analytics/reddit/RedditAnalytics.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-import { useParams } from 'react-router-dom';
-import { UserX } from 'lucide-react';
-import { Alert, AlertAction, AlertDescription } from '@/components/ui/alert';
-import { Button } from '@/components/ui/button';
-import PageHeader from '@/components/PageHeader';
-import MetricBox from '@/components/MetricBox';
-import Num from '@/components/Num';
-import SurfaceBox from '@/components/SurfaceBox';
-import { EmptyState, ErrorState, PageSkeleton } from '@/components/StateViews';
-import { METRIC_ICONS } from '@/lib/metricIcons';
-import { useAppContext } from '../../../context/AppContext';
-import { useAccountAnalytics } from '../../../hooks/use-account-analytics';
-import { useDocumentTitle } from '@/hooks/use-document-title';
-import { api } from '../../../services/api';
-import { fmtNum } from '../../../utils/formatters';
-import { MEDIA_TYPE_LABELS } from './redditPostUtils';
-import { mediaTypeDataOf } from './redditAnalyticsData.ts';
-import type { RedditAnalytics as RedditAnalyticsData } from '@shared/types/reddit.ts';
-import RedditHeader from './RedditHeader';
-import RedditKarmaSummary from './RedditKarmaSummary';
-import RedditKarmaCharts from './RedditKarmaCharts';
-import RedditStatPanels from './RedditStatPanels';
-import RedditTimingCharts from './RedditTimingCharts';
-import RedditSubredditTable from './RedditSubredditTable';
-import RedditTopPostsTable from './RedditTopPostsTable';
-
-const BACK = { to: '/', label: 'Overview' };
-
-const { redditPosts: Posts, karma: Karma, comments: Comments, awards: Awards } = METRIC_ICONS;
-
-export default function RedditAnalytics() {
- const { id } = useParams();
- const { accounts } = useAppContext();
- const account = accounts.find(item => item.id === id);
- const { initialLoading, error, profile, analytics, fetchedAt, refreshing, handleRefresh, retry } = useAccountAnalytics(
- account, api.getRedditAnalytics, 'Reddit',
- );
- useDocumentTitle(account ? `u/${account.username}` : null);
-
- if (!account) {
- return (
- <div className="flex flex-col gap-6">
- <PageHeader title="Reddit account" back={BACK} />
- <SurfaceBox>
- <EmptyState icon={<UserX />} title="Account not found" description="It may have been removed. Choose another account from the sidebar." />
- </SurfaceBox>
- </div>
- );
- }
-
- if (initialLoading) return <PageSkeleton metrics={4} />;
-
- const profileData = profile || account;
-
- if (!analytics) {
- return (
- <div className="flex flex-col gap-6">
- <RedditHeader account={account} profile={profileData} back={BACK} refreshing={refreshing} onRefresh={handleRefresh} fetchedAt={null} />
- <SurfaceBox>
- <ErrorState title="Reddit analytics could not load" description={error ?? undefined} onRetry={retry} />
- </SurfaceBox>
- </div>
- );
- }
-
- const analyticsData: Partial<RedditAnalyticsData> = analytics;
- const postsPeriod = `Last ${analyticsData.fetchedPosts ?? 0} posts`;
-
- return (
- <div className="flex flex-col gap-6">
- <RedditHeader account={account} profile={profileData} back={BACK} refreshing={refreshing} onRefresh={handleRefresh} fetchedAt={fetchedAt} />
-
- {error && (
- <Alert variant="destructive" role="alert">
- <AlertDescription>{error} The numbers below are from the last successful load.</AlertDescription>
- <AlertAction><Button size="xs" variant="outline" onClick={retry}>Try again</Button></AlertAction>
- </Alert>
- )}
-
- <div className="flex flex-col gap-6" aria-busy={refreshing}>
- <RedditKarmaSummary profile={profileData} />
-
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
- <MetricBox icon={<Karma />} label="Karma from posts" value={<Num value={analyticsData.totalScore} />} period={postsPeriod} subtitle={`${fmtNum(analyticsData.avgScore)} per post on average`} highlight />
- <MetricBox icon={<Posts />} label="Posts loaded" value={<Num value={analyticsData.fetchedPosts} />} period="Newest first" subtitle={`${analyticsData.postsLast30Days ?? 0} in the last 30 days`} />
- <MetricBox icon={<Comments />} label="Comments" value={<Num value={analyticsData.totalComments} />} period={postsPeriod} subtitle={`${fmtNum(analyticsData.avgComments)} per post on average`} />
- <MetricBox icon={<Awards />} label="Awards received" value={<Num value={analyticsData.totalAwards ?? 0} />} period={postsPeriod} subtitle={`${analyticsData.avgAwards ?? 0} per post on average`} />
- </div>
-
- {(analyticsData.monthlyBreakdown?.length as number) > 0 && (
- <RedditKarmaCharts
- monthlyBreakdown={analyticsData.monthlyBreakdown!}
- mediaTypeData={mediaTypeDataOf(analyticsData.mediaTypeDistribution, MEDIA_TYPE_LABELS)}
- />
- )}
-
- <RedditStatPanels analytics={analyticsData} />
-
- {(analyticsData.postsByDayOfWeek?.length as number) > 0 && <RedditTimingCharts analytics={analyticsData} />}
-
- {(analyticsData.subredditBreakdown?.length as number) > 0 && <RedditSubredditTable subreddits={analyticsData.subredditBreakdown!} />}
-
- {(analyticsData.topPosts?.length as number) > 0 && <RedditTopPostsTable posts={analyticsData.topPosts!} />}
- </div>
- </div>
- );
-}
diff --git a/frontend/src/features/analytics/reddit/RedditHeader.tsx b/frontend/src/features/analytics/reddit/RedditHeader.tsx
deleted file mode 100644
index 8b3c0fe..0000000
--- a/frontend/src/features/analytics/reddit/RedditHeader.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { Link } from 'react-router-dom';
-import { FileText } from 'lucide-react';
-import { Button } from '@/components/ui/button';
-import { Badge } from '@/components/ui/badge';
-import PageHeader from '@/components/PageHeader';
-import RefreshButton from '@/components/RefreshButton';
-import DataFreshness from '@/components/DataFreshness';
-import { AccountAvatar } from '@/components/platform';
-import { fmtDate } from '../../../utils/formatters';
-import type { AppAccount } from '../../../utils/formatters';
-import type { PageHeaderBack } from '@/components/PageHeader';
-import type { RedditProfileFields } from './redditAnalyticsData.ts';
-
-export interface RedditHeaderProps {
- account: AppAccount;
- profile: RedditProfileFields;
- back: PageHeaderBack;
- refreshing: boolean;
- onRefresh: () => void;
- // when the posts were fetched; Reddit numbers are cached for up to 6 hours
- fetchedAt: string | null;
-}
-
-export default function RedditHeader({ account, profile, back, refreshing, onRefresh, fetchedAt }: RedditHeaderProps) {
- return (
- <PageHeader
- back={back}
- media={<AccountAvatar account={{ ...account, iconUrl: profile.iconUrl || account.iconUrl }} size="xl" showPlatform decorative />}
- title={`u/${profile.username || account.username}`}
- description={
- <span className="flex flex-col gap-1.5">
- <span className="flex flex-wrap items-center gap-1.5">
- {profile.isGold && <Badge variant="warning">Gold</Badge>}
- {profile.verified && <Badge variant="info">Verified</Badge>}
- {profile.isMod && <Badge variant="outline">Moderator</Badge>}
- {profile.createdAt && <span>Joined {fmtDate(profile.createdAt)}</span>}
- </span>
- <DataFreshness fetchedAt={fetchedAt} />
- </span>
- }
- actions={
- <>
- <Button variant="outline" render={<Link to={`/reddit-posts/${account.id}`} />}>
- <FileText data-icon="inline-start" aria-hidden="true" />
- View posts
- </Button>
- <RefreshButton refreshing={refreshing} onRefresh={onRefresh} />
- </>
- }
- />
- );
-}
diff --git a/frontend/src/features/analytics/reddit/RedditKarmaCharts.tsx b/frontend/src/features/analytics/reddit/RedditKarmaCharts.tsx
deleted file mode 100644
index 76f915b..0000000
--- a/frontend/src/features/analytics/reddit/RedditKarmaCharts.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { AreaChart } from '@/components/ui/area-chart';
-import ChartPanel from '@/components/ChartPanel';
-import DonutChart from '@/components/DonutChart';
-import ExactTooltip from '@/components/ExactTooltip';
-import { PLATFORM_META } from '@/lib/accounts';
-import { pointsOf, rankingSummary, trendSummary } from '@/lib/chart';
-import { fmtNum, fmtNumFull } from '../../../utils/formatters';
-import type { RedditMonthStats } from '@shared/types/reddit.ts';
-import type { RedditMediaSlice } from './redditAnalyticsData.ts';
-
-// karma keeps Reddit's series colour here and on the Overview, so one colour means one thing
-const KARMA = PLATFORM_META.reddit.series;
-
-const BY_MONTH = { score: { label: 'Karma', color: KARMA } };
-
-export interface RedditKarmaChartsProps {
- monthlyBreakdown: RedditMonthStats[];
- mediaTypeData: RedditMediaSlice[];
-}
-
-export default function RedditKarmaCharts({ monthlyBreakdown, mediaTypeData }: RedditKarmaChartsProps) {
- return (
- <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
- <ChartPanel
- title="Karma over time"
- height={240}
- className="xl:col-span-2"
- description={trendSummary(pointsOf(monthlyBreakdown, 'month', 'score'), fmtNumFull, 'karma')}
- >
- <AreaChart
- data={monthlyBreakdown.map(month => ({ ...month }))}
- dataKey="month"
- config={BY_MONTH}
- containerHeight={240}
- legend={false}
- tooltip={<ExactTooltip />}
- valueFormatter={fmtNum}
- areaProps={{ type: 'monotone', dot: { fill: KARMA, r: 3, strokeWidth: 0 } }}
- />
- </ChartPanel>
-
- {mediaTypeData.length > 0 && (
- <ChartPanel title="Post types" height={240} description={rankingSummary(mediaTypeData, fmtNumFull, 'posts')}>
- <DonutChart data={mediaTypeData} height={240} cy="44%" innerRadius={48} outerRadius={80} />
- </ChartPanel>
- )}
- </div>
- );
-}
diff --git a/frontend/src/features/analytics/reddit/RedditKarmaSummary.tsx b/frontend/src/features/analytics/reddit/RedditKarmaSummary.tsx
deleted file mode 100644
index 7d747a8..0000000
--- a/frontend/src/features/analytics/reddit/RedditKarmaSummary.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import SurfaceBox from '@/components/SurfaceBox';
-import Num from '@/components/Num';
-import { cn } from '@/lib/utils';
-import { karmaSummaryOf } from './redditAnalyticsData.ts';
-import type { RedditProfileFields } from './redditAnalyticsData.ts';
-
-export interface RedditKarmaSummaryProps {
- profile: RedditProfileFields;
-}
-
-export default function RedditKarmaSummary({ profile }: RedditKarmaSummaryProps) {
- return (
- <SurfaceBox title="Karma" subheader="Earned across posts and comments, all time">
- <dl className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-4">
- {karmaSummaryOf(profile).map(item => (
- <div key={item.label} className="flex flex-col gap-1">
- <dt className="text-small font-medium text-ink-muted">{item.label}</dt>
- <dd className={cn('font-heading text-page-title font-semibold tabular-nums', item.lead ? 'text-brand-text' : 'text-ink')}>
- <Num value={item.value} />
- </dd>
- <dd className="text-caption text-ink-faint">{item.sub}</dd>
- </div>
- ))}
- </dl>
- </SurfaceBox>
- );
-}
diff --git a/frontend/src/features/analytics/reddit/RedditPostFilters.tsx b/frontend/src/features/analytics/reddit/RedditPostFilters.tsx
deleted file mode 100644
index 6bee3f4..0000000
--- a/frontend/src/features/analytics/reddit/RedditPostFilters.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
-import SearchField from '@/components/SearchField';
-import SortSelect from '@/components/SortSelect';
-import { REDDIT_SORT_OPTIONS } from './redditPostUtils';
-import type { RedditFilterOption } from './redditPostUtils';
-import type { AppAccount } from '../../../utils/formatters';
-
-interface FilterSelectProps {
- value: string;
- onChange: (value: string) => void;
- items: RedditFilterOption[];
- label: string;
-}
-
-function FilterSelect({ value, onChange, items, label }: FilterSelectProps) {
- return (
- <Select value={value} onValueChange={next => { if (next) onChange(next as string); }} items={items}>
- <SelectTrigger className="h-(--control-h-lg) w-full sm:w-48" aria-label={label}><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {items.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
- );
-}
-
-export interface RedditPostFiltersProps {
- query: string;
- onQuery: (value: string) => void;
- sort: string;
- onSort: (value: string) => void;
- subreddit: string;
- onSubreddit: (value: string) => void;
- subreddits: string[];
- accountId?: string;
- onAccount?: (value: string) => void;
- accounts?: AppAccount[];
-}
-
-export default function RedditPostFilters({ query, onQuery, sort, onSort, subreddit, onSubreddit, subreddits, accountId, onAccount, accounts }: RedditPostFiltersProps) {
- return (
- <div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap">
- <SearchField value={query} onChange={onQuery} placeholder="Search titles, subreddits and flair" className="min-w-56 flex-1" />
- {accounts && accounts.length > 1 && onAccount && (
- <FilterSelect
- label="Account"
- value={accountId ?? 'all'}
- onChange={onAccount}
- items={[{ value: 'all', label: 'All accounts' }, ...accounts.map(account => ({ value: account.id, label: `u/${account.username}` }))]}
- />
- )}
- <FilterSelect
- label="Subreddit"
- value={subreddit}
- onChange={onSubreddit}
- items={[{ value: 'all', label: 'All subreddits' }, ...subreddits.map(subredditName => ({ value: subredditName, label: `r/${subredditName}` }))]}
- />
- <SortSelect options={REDDIT_SORT_OPTIONS} value={sort} onChange={onSort} />
- </div>
- );
-}
diff --git a/frontend/src/features/analytics/reddit/RedditPostTable.tsx b/frontend/src/features/analytics/reddit/RedditPostTable.tsx
deleted file mode 100644
index 06ea5fb..0000000
--- a/frontend/src/features/analytics/reddit/RedditPostTable.tsx
+++ /dev/null
@@ -1,96 +0,0 @@
-import { Link } from 'react-router-dom';
-import { ExternalLink, FileText, Image, Video, Link2 } from 'lucide-react';
-import type { LucideIcon } from 'lucide-react';
-import { Badge } from '@/components/ui/badge';
-import { Button } from '@/components/ui/button';
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
-import SurfaceBox from '@/components/SurfaceBox';
-import ColumnHint from '@/components/ColumnHint';
-import Num from '@/components/Num';
-import { AccountAvatar } from '@/components/platform';
-import { MEDIA_TYPE_LABELS } from './redditPostUtils';
-import { fmtDate } from '../../../utils/formatters';
-import type { RedditMediaType } from '@shared/types/reddit.ts';
-import type { AppAccount } from '../../../utils/formatters';
-import type { RedditPostRow } from './redditPostUtils';
-
-const MEDIA_TYPE_ICONS: Record<RedditMediaType, LucideIcon> = { image: Image, video: Video, link: Link2, text: FileText };
-
-function MediaTypeIcon({ type }: { type: RedditMediaType }) {
- const Icon = MEDIA_TYPE_ICONS[type] || FileText;
- return <Icon className="size-3.5" aria-hidden="true" />;
-}
-
-export interface RedditPostTableProps {
- posts: RedditPostRow[];
- // rank of the first post on this page
- offset?: number;
- showAccount?: boolean;
- accountsById?: Record<string, AppAccount>;
-}
-
-export default function RedditPostTable({ posts, offset = 0, showAccount = false, accountsById = {} }: RedditPostTableProps) {
- return (
- <SurfaceBox title="Posts" content={false} className="overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="hidden w-10 text-right sm:table-cell">#</TableHead>
- <TableHead className="sticky left-0 z-[1] bg-surface-raised">Post</TableHead>
- {showAccount && <TableHead className="hidden w-40 lg:table-cell">Account</TableHead>}
- <TableHead className="hidden w-24 md:table-cell">Type</TableHead>
- <TableHead className="w-24 text-right">Karma</TableHead>
- <TableHead className="hidden w-24 text-right sm:table-cell">Comments</TableHead>
- <TableHead className="hidden w-32 text-right md:table-cell"><ColumnHint label="Upvote rate" hint="Share of votes on the post that are upvotes. 96% means 96 of every 100 votes were up." /></TableHead>
- <TableHead className="hidden w-28 text-right md:table-cell">Posted</TableHead>
- <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {posts.map((post, i) => (
- <TableRow key={`${post.accountId || ''}-${post.id}`}>
- <TableCell className="hidden text-right font-mono text-caption text-ink-faint sm:table-cell">{offset + i + 1}</TableCell>
- <TableCell className="sticky left-0 z-[1] bg-surface-raised whitespace-normal">
- <div className="max-w-56 sm:max-w-md">
- <p className="line-clamp-2 text-sm font-medium leading-snug text-ink" title={post.title}>{post.title}</p>
- <div className="mt-1 flex flex-wrap items-center gap-1.5">
- <span className="text-caption text-ink-faint">{post.subredditPrefixed}</span>
- {post.flair && <Badge variant="outline">{post.flair}</Badge>}
- {post.isNsfw && <Badge variant="destructive">NSFW</Badge>}
- </div>
- </div>
- </TableCell>
- {showAccount && (
- <TableCell className="hidden lg:table-cell">
- <Link to={`/reddit/${post.accountId}`} className="flex items-center gap-2 text-small text-ink-muted underline-offset-4 hover:text-ink hover:underline">
- <AccountAvatar account={accountsById[post.accountId!] || { platform: 'reddit', username: post.accountUsername, iconUrl: post.accountIconUrl }} size="xs" decorative />
- u/{post.accountUsername}
- </Link>
- </TableCell>
- )}
- <TableCell className="hidden md:table-cell">
- <span className="flex items-center gap-1.5 text-small text-ink-muted">
- <MediaTypeIcon type={post.mediaType} />
- {MEDIA_TYPE_LABELS[post.mediaType] || post.mediaType}
- </span>
- </TableCell>
- <TableCell className="text-right font-semibold text-ink"><Num value={post.score} /></TableCell>
- <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={post.numComments} /></TableCell>
- <TableCell className="hidden text-right text-ink-muted md:table-cell">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>
- <TableCell className="hidden text-right text-small text-ink-faint md:table-cell">{fmtDate(post.createdAt)}</TableCell>
- <TableCell>
- <Button
- variant="ghost"
- size="icon-xs"
- render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label={`Open "${post.title}" on Reddit (opens in a new tab)`} />}
- >
- <ExternalLink aria-hidden="true" />
- </Button>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </SurfaceBox>
- );
-}
diff --git a/frontend/src/features/analytics/reddit/RedditPosts.tsx b/frontend/src/features/analytics/reddit/RedditPosts.tsx
deleted file mode 100644
index cf95a10..0000000
--- a/frontend/src/features/analytics/reddit/RedditPosts.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import { useMemo } from 'react';
-import { useParams } from 'react-router-dom';
-import { UserX } from 'lucide-react';
-import { Skeleton } from '@/components/ui/skeleton';
-import PageHeader from '@/components/PageHeader';
-import SurfaceBox from '@/components/SurfaceBox';
-import Pager from '@/components/Pager';
-import RefreshButton from '@/components/RefreshButton';
-import DataFreshness from '@/components/DataFreshness';
-import ActiveFilters from '@/components/ActiveFilters';
-import NoResults from '@/components/NoResults';
-import { EmptyState, ErrorState } from '@/components/StateViews';
-import { AccountAvatar } from '@/components/platform';
-import { accountName } from '@/lib/accounts';
-import { useDocumentTitle } from '@/hooks/use-document-title';
-import { pageSlice, resultCountLabel } from '@/lib/library';
-import { useAppContext } from '../../../context/AppContext';
-import { api } from '../../../services/api';
-import type { AppAccount } from '../../../utils/formatters';
-import { useLibrarySources } from '../useLibrarySources';
-import { useLibraryParams } from '../useLibraryParams';
-import RedditPostFilters from './RedditPostFilters';
-import RedditPostTable from './RedditPostTable';
-import { filterAndSortRedditPosts, mergeAccountPosts, redditSortOf, subredditsOf } from './redditPostUtils';
-
-const ITEMS_PER_PAGE = 25;
-const RESULTS_ID = 'account-reddit-results';
-
-const DEFAULTS = { q: '', subreddit: 'all', sort: 'score-desc' };
-
-function fetchAccountPosts(id: string, fresh: boolean) {
- return api.getRedditAnalytics(id, fresh);
-}
-
-function nameOf(account: AppAccount): string {
- return accountName(account);
-}
-
-export default function RedditPosts() {
- const { id } = useParams();
- const { accounts } = useAppContext();
- const account = accounts.find(item => item.id === id);
- const sources = useMemo(() => (account ? [account] : []), [account]);
- const library = useLibrarySources(sources, fetchAccountPosts, nameOf, 'Reddit posts');
- const posts = useMemo(() => mergeAccountPosts(library.sources, library.results), [library.sources, library.results]);
- const { values, page, update, clear, setPage } = useLibraryParams(DEFAULTS);
- const sort = redditSortOf(values.sort);
- useDocumentTitle(account ? `Posts by u/${account.username}` : null);
-
- const subreddits = useMemo(() => subredditsOf(posts), [posts]);
- const filtered = useMemo(
- () => filterAndSortRedditPosts(posts, { query: values.q, sort, subreddit: values.subreddit }),
- [posts, values.q, sort, values.subreddit],
- );
- const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
- const clearFilters = () => clear(['q', 'subreddit']);
- const activeFilters = [
- values.q && { key: 'q', label: `"${values.q}"`, onRemove: () => update({ q: '' }) },
- values.subreddit !== 'all' && { key: 'subreddit', label: `r/${values.subreddit}`, onRemove: () => update({ subreddit: 'all' }) },
- ].filter(Boolean) as { key: string; label: string; onRemove: () => void }[];
-
- if (!account) {
- return (
- <div className="flex flex-col gap-6">
- <PageHeader title="Reddit posts" back={{ to: '/reddit-posts', label: 'All Reddit posts' }} />
- <SurfaceBox>
- <EmptyState icon={<UserX />} title="Account not found" description="It may have been removed. Choose another account from the sidebar." />
- </SurfaceBox>
- </div>
- );
- }
-
- const loading = library.initialLoading;
- const failure = library.failures[0];
-
- return (
- <div className="flex flex-col gap-6">
- <PageHeader
- back={{ to: `/reddit/${account.id}`, label: `u/${account.username} analytics` }}
- media={<AccountAvatar account={account} size="lg" decorative />}
- title={`Posts by u/${account.username}`}
- description={
- <span className="flex flex-col gap-1">
- <span>{loading ? 'Loading posts' : `${posts.length} posts loaded`}</span>
- {!loading && <DataFreshness fetchedAt={library.fetchedAt} />}
- </span>
- }
- actions={<RefreshButton refreshing={library.refreshing} onRefresh={library.refresh} disabled={loading} />}
- />
-
- {loading ? (
- <div className="flex flex-col gap-4">
- <Skeleton className="h-10 rounded-field" />
- <Skeleton className="h-96 rounded-card" />
- </div>
- ) : failure && posts.length === 0 ? (
- <SurfaceBox>
- <ErrorState title="These posts could not load" description={failure.message} onRetry={library.refresh} />
- </SurfaceBox>
- ) : (
- <>
- <RedditPostFilters
- query={values.q} onQuery={value => update({ q: value }, { replace: true })}
- sort={sort} onSort={value => update({ sort: value })}
- subreddit={values.subreddit} onSubreddit={value => update({ subreddit: value })} subreddits={subreddits}
- />
- <ActiveFilters countLabel={resultCountLabel(filtered.length, posts.length, 'posts')} filters={activeFilters} onClearAll={clearFilters} />
- <div id={RESULTS_ID} tabIndex={-1} className="outline-none" aria-busy={library.refreshing}>
- {posts.length === 0 ? (
- <SurfaceBox><EmptyState compact icon={<UserX />} title="No posts yet" description={`u/${account.username} has not submitted any posts Reddit lets Twiligent read.`} /></SurfaceBox>
- ) : filtered.length === 0 ? (
- <SurfaceBox><NoResults noun="posts" query={values.q} onClear={clearFilters} /></SurfaceBox>
- ) : (
- <RedditPostTable posts={paged.items} offset={paged.offset} />
- )}
- </div>
- <Pager
- page={paged.page}
- pageCount={paged.pageCount}
- onPageChange={setPage}
- total={filtered.length}
- shown={paged.items.length}
- pageSize={ITEMS_PER_PAGE}
- noun="posts"
- resultsId={RESULTS_ID}
- />
- </>
- )}
- </div>
- );
-}
diff --git a/frontend/src/features/analytics/reddit/RedditPostsAll.tsx b/frontend/src/features/analytics/reddit/RedditPostsAll.tsx
deleted file mode 100644
index 0f2fdbe..0000000
--- a/frontend/src/features/analytics/reddit/RedditPostsAll.tsx
+++ /dev/null
@@ -1,156 +0,0 @@
-import { useMemo } from 'react';
-import { Link } from 'react-router-dom';
-import { Plus } from 'lucide-react';
-import { Button } from '@/components/ui/button';
-import { Skeleton } from '@/components/ui/skeleton';
-import PageHeader from '@/components/PageHeader';
-import MetricBox from '@/components/MetricBox';
-import Num from '@/components/Num';
-import SurfaceBox from '@/components/SurfaceBox';
-import Pager from '@/components/Pager';
-import RefreshButton from '@/components/RefreshButton';
-import DataFreshness from '@/components/DataFreshness';
-import ActiveFilters from '@/components/ActiveFilters';
-import NoResults from '@/components/NoResults';
-import FailedSourcesAlert from '@/components/FailedSourcesAlert';
-import { EmptyState } from '@/components/StateViews';
-import { accountName } from '@/lib/accounts';
-import { pageSlice, resultCountLabel } from '@/lib/library';
-import { METRIC_ICONS } from '@/lib/metricIcons';
-import { useAppContext } from '../../../context/AppContext';
-import { api } from '../../../services/api';
-import { fmtNum } from '../../../utils/formatters';
-import type { AppAccount } from '../../../utils/formatters';
-import { useLibrarySources } from '../useLibrarySources';
-import { useLibraryParams } from '../useLibraryParams';
-import RedditPostFilters from './RedditPostFilters';
-import RedditPostTable from './RedditPostTable';
-import { filterAndSortRedditPosts, mergeAccountPosts, redditSortOf, subredditsOf } from './redditPostUtils';
-
-const ITEMS_PER_PAGE = 25;
-const RESULTS_ID = 'reddit-results';
-
-const DEFAULTS = { q: '', account: 'all', subreddit: 'all', sort: 'score-desc' };
-
-const { redditPosts: Posts, karma: Karma, comments: Comments } = METRIC_ICONS;
-
-// the analytics read carries the posts and the time they were fetched, so the page can say how old they are
-function fetchAccountPosts(id: string, fresh: boolean) {
- return api.getRedditAnalytics(id, fresh);
-}
-
-function nameOf(account: AppAccount): string {
- return accountName(account);
-}
-
-export default function RedditPostsAll() {
- const { accounts } = useAppContext();
- const redditAccounts = useMemo(() => accounts.filter(account => account.platform === 'reddit'), [accounts]);
- const accountsById = useMemo(() => Object.fromEntries(redditAccounts.map(account => [account.id, account])), [redditAccounts]);
- const library = useLibrarySources(redditAccounts, fetchAccountPosts, nameOf, 'Reddit posts');
- const posts = useMemo(() => mergeAccountPosts(library.sources, library.results), [library.sources, library.results]);
- const { values, page, update, clear, setPage } = useLibraryParams(DEFAULTS);
- const sort = redditSortOf(values.sort);
-
- const subreddits = useMemo(() => subredditsOf(posts), [posts]);
- const filtered = useMemo(
- () => filterAndSortRedditPosts(posts, { query: values.q, sort, subreddit: values.subreddit, accountId: values.account }),
- [posts, values.q, sort, values.subreddit, values.account],
- );
- const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
- const totals = useMemo(() => ({
- score: filtered.reduce((sum, post) => sum + post.score, 0),
- comments: filtered.reduce((sum, post) => sum + post.numComments, 0),
- }), [filtered]);
- const average = (total: number) => (filtered.length > 0 ? `${fmtNum(Math.round(total / filtered.length))} per post on average` : '');
-
- const clearFilters = () => clear(['q', 'account', 'subreddit']);
- const activeAccount = accountsById[values.account];
- const activeFilters = [
- values.q && { key: 'q', label: `"${values.q}"`, onRemove: () => update({ q: '' }) },
- activeAccount && { key: 'account', label: `u/${activeAccount.username}`, onRemove: () => update({ account: 'all' }) },
- values.subreddit !== 'all' && { key: 'subreddit', label: `r/${values.subreddit}`, onRemove: () => update({ subreddit: 'all' }) },
- ].filter(Boolean) as { key: string; label: string; onRemove: () => void }[];
-
- if (redditAccounts.length === 0) {
- return (
- <div className="flex flex-col gap-6">
- <PageHeader title="Reddit posts" description="Posts from every connected Reddit account" />
- <SurfaceBox>
- <EmptyState
- icon={<Posts />}
- title="No Reddit accounts yet"
- description="Connect a Reddit account to see its posts, karma and comments here."
- action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" aria-hidden="true" />Add account</Button>}
- />
- </SurfaceBox>
- </div>
- );
- }
-
- const loading = library.initialLoading;
- const accountWord = `account${redditAccounts.length === 1 ? '' : 's'}`;
-
- return (
- <div className="flex flex-col gap-6">
- <PageHeader
- title="Reddit posts"
- description={
- <span className="flex flex-col gap-1">
- <span>{loading ? `Loading posts from ${redditAccounts.length} ${accountWord}` : `${posts.length} posts across ${redditAccounts.length} ${accountWord}`}</span>
- {!loading && <DataFreshness fetchedAt={library.fetchedAt} qualifier={redditAccounts.length > 1 ? 'oldest account' : undefined} />}
- </span>
- }
- actions={<RefreshButton refreshing={library.refreshing} onRefresh={library.refresh} disabled={loading} />}
- />
-
- {loading ? (
- <div className="flex flex-col gap-4">
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
- {[0, 1, 2].map(i => <Skeleton key={i} className="h-28 rounded-card" />)}
- </div>
- <Skeleton className="h-10 rounded-field" />
- <Skeleton className="h-96 rounded-card" />
- </div>
- ) : (
- <>
- <FailedSourcesAlert failures={library.failures} total={redditAccounts.length} noun="accounts" onRetry={library.refresh} retrying={library.refreshing} />
-
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-3" aria-busy={library.refreshing}>
- <MetricBox icon={<Posts />} label="Posts" value={<Num value={filtered.length} />} period="Matching posts" subtitle={`${posts.length} loaded in total`} />
- <MetricBox icon={<Karma />} label="Karma" value={<Num value={totals.score} />} period="Matching posts" subtitle={average(totals.score)} highlight />
- <MetricBox icon={<Comments />} label="Comments" value={<Num value={totals.comments} />} period="Matching posts" subtitle={average(totals.comments)} />
- </div>
-
- <RedditPostFilters
- query={values.q} onQuery={value => update({ q: value }, { replace: true })}
- sort={sort} onSort={value => update({ sort: value })}
- subreddit={values.subreddit} onSubreddit={value => update({ subreddit: value })} subreddits={subreddits}
- accountId={values.account} onAccount={value => update({ account: value })} accounts={redditAccounts}
- />
-
- <ActiveFilters countLabel={resultCountLabel(filtered.length, posts.length, 'posts')} filters={activeFilters} onClearAll={clearFilters} />
-
- <div id={RESULTS_ID} tabIndex={-1} className="outline-none" aria-busy={library.refreshing}>
- {filtered.length === 0 ? (
- <SurfaceBox><NoResults noun="posts" query={values.q} onClear={clearFilters} /></SurfaceBox>
- ) : (
- <RedditPostTable posts={paged.items} offset={paged.offset} showAccount={redditAccounts.length > 1} accountsById={accountsById} />
- )}
- </div>
-
- <Pager
- page={paged.page}
- pageCount={paged.pageCount}
- onPageChange={setPage}
- total={filtered.length}
- shown={paged.items.length}
- pageSize={ITEMS_PER_PAGE}
- noun="posts"
- resultsId={RESULTS_ID}
- />
- </>
- )}
- </div>
- );
-}
diff --git a/frontend/src/features/analytics/reddit/RedditStatPanels.tsx b/frontend/src/features/analytics/reddit/RedditStatPanels.tsx
deleted file mode 100644
index dd66cfe..0000000
--- a/frontend/src/features/analytics/reddit/RedditStatPanels.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { Progress } from '@/components/ui/progress';
-import SurfaceBox from '@/components/SurfaceBox';
-import { karmaBreakdownRows, performanceIndicators, postingFrequencyRows } from './redditAnalyticsData.ts';
-import type { RedditStatRow } from './redditAnalyticsData.ts';
-import type { RedditAnalytics } from '@shared/types/reddit.ts';
-
-interface StatListProps {
- rows: RedditStatRow[];
-}
-
-function StatList({ rows }: StatListProps) {
- return (
- <dl className="flex flex-col divide-y divide-divider">
- {rows.map(row => (
- <div key={row.label} className="flex items-center justify-between gap-4 py-2.5 first:pt-0 last:pb-0">
- <dt className="text-sm text-ink-muted">{row.label}</dt>
- <dd className="text-sm font-semibold text-ink tabular-nums">{row.value}</dd>
- </div>
- ))}
- </dl>
- );
-}
-
-export interface RedditStatPanelsProps {
- analytics: Partial<RedditAnalytics>;
-}
-
-export default function RedditStatPanels({ analytics }: RedditStatPanelsProps) {
- return (
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
- <SurfaceBox title="Posting frequency">
- <StatList rows={postingFrequencyRows(analytics)} />
- </SurfaceBox>
-
- <SurfaceBox title="Karma breakdown">
- <StatList rows={karmaBreakdownRows(analytics)} />
- </SurfaceBox>
-
- <SurfaceBox title="Performance indicators">
- <div className="flex flex-col gap-5">
- {performanceIndicators(analytics).map(item => (
- <div key={item.label} className="flex flex-col gap-2">
- <div className="flex items-center justify-between text-sm">
- <span className="font-medium text-ink">{item.label}</span>
- <span className="text-ink-muted tabular-nums">{item.value}</span>
- </div>
- <Progress value={(item.value / item.max) * 100} aria-label={item.label} />
- <p className="text-caption text-ink-faint">{item.desc}</p>
- </div>
- ))}
- </div>
- </SurfaceBox>
- </div>
- );
-}
diff --git a/frontend/src/features/analytics/reddit/RedditSubredditTable.tsx b/frontend/src/features/analytics/reddit/RedditSubredditTable.tsx
deleted file mode 100644
index 1ff23a4..0000000
--- a/frontend/src/features/analytics/reddit/RedditSubredditTable.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { ExternalLink } from 'lucide-react';
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
-import SurfaceBox from '@/components/SurfaceBox';
-import Num from '@/components/Num';
-import type { RedditSubredditStats } from '@shared/types/reddit.ts';
-
-export interface RedditSubredditTableProps {
- subreddits: RedditSubredditStats[];
-}
-
-export default function RedditSubredditTable({ subreddits }: RedditSubredditTableProps) {
- return (
- <SurfaceBox title="Top subreddits" content={false} className="overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead>Subreddit</TableHead>
- <TableHead className="text-right">Posts</TableHead>
- <TableHead className="text-right">Total karma</TableHead>
- <TableHead className="hidden text-right sm:table-cell">Average karma</TableHead>
- <TableHead className="hidden text-right md:table-cell">Average comments</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {subreddits.map((sub, i) => (
- <TableRow key={sub.subreddit}>
- <TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>
- <TableCell>
- <a href={`https://reddit.com/r/${sub.subreddit}`} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-sm font-medium text-ink underline-offset-4 hover:underline">
- r/{sub.subreddit}
- <ExternalLink className="size-3 text-ink-faint" aria-hidden="true" />
- <span className="sr-only"> (opens in a new tab)</span>
- </a>
- </TableCell>
- <TableCell className="text-right text-ink-muted">{sub.posts}</TableCell>
- <TableCell className="text-right font-semibold text-ink"><Num value={sub.totalScore} /></TableCell>
- <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={sub.avgScore} /></TableCell>
- <TableCell className="hidden text-right text-ink-muted md:table-cell"><Num value={sub.avgComments} /></TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </SurfaceBox>
- );
-}
diff --git a/frontend/src/features/analytics/reddit/RedditTimingCharts.tsx b/frontend/src/features/analytics/reddit/RedditTimingCharts.tsx
deleted file mode 100644
index 4a66f84..0000000
--- a/frontend/src/features/analytics/reddit/RedditTimingCharts.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { BarChart } from '@/components/ui/bar-chart';
-import ChartPanel from '@/components/ChartPanel';
-import ExactTooltip from '@/components/ExactTooltip';
-import { PLATFORM_META } from '@/lib/accounts';
-import { SERIES, pointsOf, rankingSummary } from '@/lib/chart';
-import { fmtNum, fmtNumFull } from '../../../utils/formatters';
-import type { RedditAnalytics } from '@shared/types/reddit.ts';
-
-const KARMA = PLATFORM_META.reddit.series;
-
-const BY_DAY = {
- posts: { label: 'Posts', color: SERIES.neutral },
- avgScore: { label: 'Average karma', color: KARMA },
-};
-
-const BY_HOUR = { avgScore: { label: 'Average karma', color: KARMA } };
-
-function formatHour(hour: number) {
- return `${hour}h`;
-}
-
-function bestLabel(prefix: string, value: string | undefined) {
- return value ? `${prefix}: ${value}` : undefined;
-}
-
-export interface RedditTimingChartsProps {
- analytics: Partial<RedditAnalytics>;
-}
-
-export default function RedditTimingCharts({ analytics }: RedditTimingChartsProps) {
- const byDay = (analytics.postsByDayOfWeek || []).map(day => ({ ...day }));
- // the tooltip heads each bar with its category, which has to be text
- const byHour = (analytics.postsByHour || []).map(hour => ({ ...hour, hourName: formatHour(hour.hour) }));
- return (
- <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
- <ChartPanel
- title="Posts by day of week"
- subheader={bestLabel('Best day', analytics.bestPostingDay)}
- height={220}
- description={rankingSummary(pointsOf(byDay, 'day', 'avgScore'), fmtNumFull, 'karma per post')}
- >
- <BarChart
- data={byDay}
- dataKey="shortDay"
- config={BY_DAY}
- containerHeight={220}
- tooltip={<ExactTooltip />}
- valueFormatter={fmtNum}
- yAxisProps={{ width: 36 }}
- />
- </ChartPanel>
-
- <ChartPanel
- title="Average karma by hour"
- subheader={bestLabel('Best hour', analytics.bestPostingHour)}
- height={220}
- description={rankingSummary(pointsOf(byHour, 'hourName', 'avgScore'), fmtNumFull, 'karma per post')}
- >
- <BarChart
- data={byHour}
- dataKey="hourName"
- config={BY_HOUR}
- containerHeight={220}
- legend={false}
- tooltip={<ExactTooltip />}
- valueFormatter={fmtNum}
- xAxisProps={{ interval: 3 }}
- yAxisProps={{ width: 36 }}
- />
- </ChartPanel>
- </div>
- );
-}
diff --git a/frontend/src/features/analytics/reddit/RedditTopPostsTable.tsx b/frontend/src/features/analytics/reddit/RedditTopPostsTable.tsx
deleted file mode 100644
index 45a40e6..0000000
--- a/frontend/src/features/analytics/reddit/RedditTopPostsTable.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { ExternalLink } from 'lucide-react';
-import { Button } from '@/components/ui/button';
-import { Badge } from '@/components/ui/badge';
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
-import SurfaceBox from '@/components/SurfaceBox';
-import ColumnHint from '@/components/ColumnHint';
-import Num from '@/components/Num';
-import { RankNumber } from '@/components/ListRow';
-import { fmtDate } from '../../../utils/formatters';
-import type { RedditPost } from '@shared/types/reddit.ts';
-
-export interface RedditTopPostsTableProps {
- posts: RedditPost[];
-}
-
-export default function RedditTopPostsTable({ posts }: RedditTopPostsTableProps) {
- return (
- <SurfaceBox title="Top posts by karma" content={false} className="overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead>Post</TableHead>
- <TableHead className="text-right">Karma</TableHead>
- <TableHead className="hidden text-right sm:table-cell">Comments</TableHead>
- <TableHead className="hidden text-right md:table-cell"><ColumnHint label="Upvote rate" hint="Share of votes on the post that are upvotes. 96% means 96 of every 100 votes were up." /></TableHead>
- <TableHead className="hidden text-right md:table-cell">Posted</TableHead>
- <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {posts.map((post, i) => (
- <TableRow key={post.id}>
- <TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>
- <TableCell className="whitespace-normal">
- <div className="max-w-sm">
- <p className="line-clamp-2 text-sm font-medium leading-snug text-ink" title={post.title}>{post.title}</p>
- <div className="mt-1 flex items-center gap-1.5">
- <span className="text-caption text-ink-faint">{post.subredditPrefixed}</span>
- {post.flair && <Badge variant="outline">{post.flair}</Badge>}
- </div>
- </div>
- </TableCell>
- <TableCell className="text-right font-semibold text-ink"><Num value={post.score} /></TableCell>
- <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={post.numComments} /></TableCell>
- <TableCell className="hidden text-right text-ink-muted md:table-cell">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>
- <TableCell className="hidden text-right text-small text-ink-faint md:table-cell">{fmtDate(post.createdAt)}</TableCell>
- <TableCell>
- <Button variant="ghost" size="icon-xs" render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label={`Open "${post.title}" on Reddit (opens in a new tab)`} />}>
- <ExternalLink aria-hidden="true" />
- </Button>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </SurfaceBox>
- );
-}
diff --git a/frontend/src/features/analytics/reddit/redditAnalyticsData.ts b/frontend/src/features/analytics/reddit/redditAnalyticsData.ts
deleted file mode 100644
index e74ec9e..0000000
--- a/frontend/src/features/analytics/reddit/redditAnalyticsData.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { seriesAt } from '../../../lib/chart.ts';
-import { fmtNum } from '../../../utils/formatters.ts';
-import type { RedditAnalytics, RedditMediaType, RedditProfile } from '../../../../../shared/types/reddit.ts';
-
-// the page falls back to the stored account until the live profile loads, and accounts can store createdAt as a number
-export type RedditProfileFields = Partial<Omit<RedditProfile, 'createdAt'>> & { createdAt?: string | number };
-
-export interface RedditMediaSlice {
- name: string;
- value: number;
- color: string;
-}
-
-export interface RedditKarmaItem {
- label: string;
- value: number;
- sub: string;
- lead?: boolean;
-}
-
-export interface RedditStatRow {
- label: string;
- value: string | number;
-}
-
-export interface RedditIndicator {
- label: string;
- value: number;
- max: number;
- desc: string;
-}
-
-const MEDIA_TYPE_ORDER: string[] = ['text', 'image', 'video', 'link'];
-
-// labels are passed in because redditPostUtils.js imports through a path alias
-export function mediaTypeDataOf(distribution: Partial<Record<RedditMediaType, number>> | undefined, labels: Partial<Record<string, string>>): RedditMediaSlice[] {
- if (!distribution) return [];
- return (Object.entries(distribution) as [string, number][]).map(([key, value]) => ({
- name: labels[key] || key,
- value,
- color: seriesAt(Math.max(0, MEDIA_TYPE_ORDER.indexOf(key))),
- }));
-}
-
-export function karmaSummaryOf(profile: RedditProfileFields): RedditKarmaItem[] {
- return [
- { label: 'Total karma', value: profile.totalKarma ?? 0, sub: 'All time', lead: true },
- { label: 'Post karma', value: profile.postKarma ?? 0, sub: 'From submitted posts' },
- { label: 'Comment karma', value: profile.commentKarma ?? 0, sub: 'From comments' },
- { label: 'Awardee karma', value: profile.awardeeKarma ?? 0, sub: 'From awards received' },
- ];
-}
-
-export function postingFrequencyRows(analytics: Partial<RedditAnalytics>): RedditStatRow[] {
- return [
- { label: 'Last 7 days', value: `${analytics.postsLast7Days ?? 0} posts` },
- { label: 'Last 30 days', value: `${analytics.postsLast30Days ?? 0} posts` },
- { label: 'Last 90 days', value: `${analytics.postsLast90Days ?? 0} posts` },
- { label: 'Per week', value: analytics.postFrequency?.perWeek ?? 0 },
- { label: 'Per month', value: analytics.postFrequency?.perMonth ?? 0 },
- ];
-}
-
-export function karmaBreakdownRows(analytics: Partial<RedditAnalytics>): RedditStatRow[] {
- return [
- { label: 'Average karma', value: fmtNum(analytics.avgScore) },
- { label: 'Median karma', value: fmtNum(analytics.medianScore) },
- { label: 'Best single post', value: fmtNum(analytics.topPosts?.[0]?.score) },
- { label: 'Average upvote ratio', value: `${analytics.avgUpvoteRatio ?? 0}%` },
- { label: 'Total comments', value: fmtNum(analytics.totalComments) },
- { label: 'Average comments', value: fmtNum(analytics.avgComments) },
- ];
-}
-
-export function performanceIndicators(analytics: Partial<RedditAnalytics>): RedditIndicator[] {
- const virality = analytics.viralityScore ?? 0;
- return [
- { label: 'Virality score', value: virality, max: Math.max(10, virality), desc: 'Best post karma against the average. Higher means bigger outlier hits.' },
- { label: 'Consistency', value: analytics.consistencyScore ?? 0, max: 100, desc: 'How evenly karma spreads across posts. 100 means every post performs alike.' },
- ];
-}
diff --git a/frontend/src/features/analytics/reddit/redditPostUtils.ts b/frontend/src/features/analytics/reddit/redditPostUtils.ts
deleted file mode 100644
index 3ce404d..0000000
--- a/frontend/src/features/analytics/reddit/redditPostUtils.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { matchesText } from '../../../lib/library.ts';
-import type { RedditMediaType, RedditPost } from '../../../../../shared/types/reddit.ts';
-
-// Filtering and sorting shared by the per-account and all-accounts Reddit posts pages.
-
-// posts on the all-accounts page carry the account they were fetched for
-export interface RedditPostRow extends RedditPost {
- accountId?: string;
- accountUsername?: string;
- accountIconUrl?: string;
-}
-
-export interface RedditFilterOption {
- value: string;
- label: string;
-}
-
-export interface RedditPostFilterOptions {
- query: string;
- sort: string;
- subreddit?: string;
- accountId?: string;
-}
-
-export const MEDIA_TYPE_LABELS: Record<RedditMediaType, string> = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };
-
-export const REDDIT_SORT_OPTIONS: RedditFilterOption[] = [
- { value: 'score-desc', label: 'Most karma' },
- { value: 'score-asc', label: 'Least karma' },
- { value: 'comments-desc', label: 'Most comments' },
- { value: 'date-desc', label: 'Newest first' },
- { value: 'date-asc', label: 'Oldest first' },
-];
-
-export function filterAndSortRedditPosts<T extends RedditPostRow>(posts: T[], { query, sort, subreddit = 'all', accountId = 'all' }: RedditPostFilterOptions): T[] {
- let result = posts;
- if (accountId !== 'all') result = result.filter(p => p.accountId === accountId);
- if (subreddit !== 'all') result = result.filter(p => p.subreddit === subreddit);
- result = result.filter(p => matchesText([p.title, p.subreddit, p.flair, p.accountUsername], query));
- return [...result].sort((a, b) => {
- if (sort === 'score-desc') return b.score - a.score;
- if (sort === 'score-asc') return a.score - b.score;
- if (sort === 'comments-desc') return b.numComments - a.numComments;
- if (sort === 'date-desc') return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
- if (sort === 'date-asc') return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
- return 0;
- });
-}
-
-export function subredditsOf(posts: Pick<RedditPost, 'subreddit'>[]): string[] {
- return [...new Set(posts.map(p => p.subreddit))].sort();
-}
-
-// a sort read from the address falls back to most karma when it is not one of the options
-export function redditSortOf(value: string): string {
- return REDDIT_SORT_OPTIONS.some(option => option.value === value) ? value : 'score-desc';
-}
-
-// tags each post with the account it was fetched for, skipping accounts whose request failed
-export function mergeAccountPosts<A extends { id: string; username?: string; iconUrl?: string }>(
- accounts: readonly A[],
- results: readonly PromiseSettledResult<{ posts?: RedditPost[] }>[],
-): RedditPostRow[] {
- const combined: RedditPostRow[] = [];
- results.forEach((result, index) => {
- if (result.status !== 'fulfilled') return;
- const account = accounts[index];
- for (const post of result.value.posts || []) {
- combined.push({ ...post, accountId: account.id, accountUsername: account.username, accountIconUrl: account.iconUrl });
- }
- });
- return combined;
-}
diff --git a/frontend/src/layout/navigation.ts b/frontend/src/layout/navigation.ts
index 8e1b95d..bc99aeb 100644
--- a/frontend/src/layout/navigation.ts
+++ b/frontend/src/layout/navigation.ts
@@ -1,5 +1,5 @@
import {
- LayoutDashboard, PlaySquare, Scissors, Clapperboard, MessagesSquare, Bookmark, Send, MessageSquareReply, Users, Settings,
+ LayoutDashboard, PlaySquare, Scissors, Clapperboard, Bookmark, Send, MessageSquareReply, Users, Settings,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { activeNavPath, routeTitle as titleForRoute } from './routes';
@@ -27,7 +27,6 @@ export const NAV_GROUPS: NavGroup[] = [
{ path: '/videos', label: 'Videos', icon: PlaySquare },
{ path: '/shorts', label: 'Shorts', icon: Scissors },
{ path: '/instagram', label: 'Instagram content', icon: Clapperboard },
- { path: '/reddit-posts', label: 'Reddit posts', icon: MessagesSquare },
{ path: '/tracked-content', label: 'Tracked content', icon: Bookmark },
],
},
diff --git a/frontend/src/layout/routes.ts b/frontend/src/layout/routes.ts
index 6d078a4..93f3de4 100644
--- a/frontend/src/layout/routes.ts
+++ b/frontend/src/layout/routes.ts
@@ -25,8 +25,6 @@ export interface DetailRoute {
export const DETAIL_ROUTES: DetailRoute[] = [
{ prefix: '/channel/', label: 'YouTube channel', parent: { path: '/', label: 'Overview' } },
{ prefix: '/instagram/', label: 'Instagram account', parent: { path: '/', label: 'Overview' } },
- { prefix: '/reddit/', label: 'Reddit account', parent: { path: '/', label: 'Overview' } },
- { prefix: '/reddit-posts/', label: 'Reddit posts', parent: { path: '/reddit-posts', label: 'Reddit posts' } },
{ prefix: '/tracked-content/category/', label: 'Category', parent: { path: '/tracked-content', label: 'Tracked content' } },
{ prefix: '/automations/rules/new', label: 'New rule', parent: { path: '/automations', label: 'Automations' } },
{ prefix: '/automations/rules/', label: 'Edit rule', parent: { path: '/automations', label: 'Automations' } },
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts
index 30a182a..d0012ba 100644
--- a/frontend/src/services/api.ts
+++ b/frontend/src/services/api.ts
@@ -12,7 +12,6 @@ import type {
InstagramMediaPublishResponse, InstagramMediaResponse, InstagramPublishingLimitResponse, InstagramPublishRequest,
InstagramPublishResponse, InstagramTokenRefreshResponse,
} from '@shared/types/instagram.ts';
-import type { RedditCacheData } from '@shared/types/reddit.ts';
import type {
AutomationAccountResponse, AutomationActivityItemResponse, AutomationActivityResponse, AutomationOverviewResponse,
AutomationRuleRequest, AutomationRuleResponse, AutomationRuleUpdateRequest, AutomationStatsResponse, AutomationTestRequest,
@@ -164,8 +163,6 @@ export const api = {
publishIGContainer: (id: string, containerId: string) => request<InstagramMediaPublishResponse>(`/accounts/${id}/ig-media-publish`, { method: 'POST', body: JSON.stringify({ containerId }) }),
addRedditAccount: (username: string, cookie: string) => request<AccountResponse>('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, cookie }) }),
- // fresh skips the server's cache, for a person's explicit Refresh
- getRedditAnalytics: (id: string, fresh = false) => request<RedditCacheData>(`/accounts/${id}/reddit-analytics${fresh ? '?fresh=1' : ''}`),
// Overview dashboard (tracked content + per-account analytics cache)
getOverview: () => request<OverviewResponse>('/overview'),
diff --git a/frontend/tests/features/analytics/reddit/redditAnalyticsData.test.ts b/frontend/tests/features/analytics/reddit/redditAnalyticsData.test.ts
deleted file mode 100644
index 9f7121c..0000000
--- a/frontend/tests/features/analytics/reddit/redditAnalyticsData.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import {
- mediaTypeDataOf, karmaSummaryOf, postingFrequencyRows, karmaBreakdownRows, performanceIndicators,
-} from '../../../../src/features/analytics/reddit/redditAnalyticsData.ts';
-import type { RedditMediaType, RedditPost } from '../../../../../shared/types/reddit.ts';
-
-const labels = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };
-
-test('media types use their label and a fixed colour per type', () => {
- assert.deepEqual(mediaTypeDataOf({ image: 4, gallery: 1 } as Partial<Record<RedditMediaType, number>>, labels), [
- { name: 'Image', value: 4, color: 'var(--chart-2)' },
- { name: 'gallery', value: 1, color: 'var(--chart-1)' },
- ]);
- assert.deepEqual(mediaTypeDataOf(undefined, labels), []);
-});
-
-test('karma summary leads with total karma', () => {
- const items = karmaSummaryOf({ totalKarma: 1500, postKarma: 1000, commentKarma: 500 });
- assert.deepEqual(items.map(item => item.value), [1500, 1000, 500, 0]);
- assert.equal(items[0].sub, 'All time');
- assert.equal(items[0].lead, true);
-});
-
-test('stat lists fall back to zero', () => {
- assert.deepEqual(postingFrequencyRows({}).map(row => row.value), ['0 posts', '0 posts', '0 posts', 0, 0]);
- const breakdown = karmaBreakdownRows({ avgScore: 12, topPosts: [{ score: 2400 }] as RedditPost[], avgUpvoteRatio: 93 });
- assert.equal(breakdown[0].value, '12');
- assert.equal(breakdown[2].value, '2.4K');
- assert.equal(breakdown[3].value, '93%');
-});
-
-test('virality scale grows past ten', () => {
- assert.equal(performanceIndicators({}).at(0)!.max, 10);
- assert.equal(performanceIndicators({ viralityScore: 25 }).at(0)!.max, 25);
- assert.equal(performanceIndicators({ consistencyScore: 80 }).at(1)!.value, 80);
-});
diff --git a/frontend/tests/features/analytics/reddit/redditPostUtils.test.ts b/frontend/tests/features/analytics/reddit/redditPostUtils.test.ts
deleted file mode 100644
index f22a368..0000000
--- a/frontend/tests/features/analytics/reddit/redditPostUtils.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { filterAndSortRedditPosts, mergeAccountPosts, redditSortOf } from '../../../../src/features/analytics/reddit/redditPostUtils.ts';
-import type { RedditPost } from '../../../../../shared/types/reddit.ts';
-
-const post = (id: string, score: number, subreddit = 'origami') => ({ id, score, subreddit, title: id, numComments: 0, createdAt: '2026-01-01T00:00:00Z' }) as RedditPost;
-
-test('posts are tagged with their account and failed accounts are skipped', () => {
- const accounts = [{ id: 'r1', username: 'ribbon' }, { id: 'r2', username: 'fold' }];
- const results: PromiseSettledResult<{ posts?: RedditPost[] }>[] = [
- { status: 'fulfilled', value: { posts: [post('a', 5)] } },
- { status: 'rejected', reason: new Error('cookie expired') },
- ];
- const merged = mergeAccountPosts(accounts, results);
- assert.deepEqual(merged.map(row => [row.id, row.accountId, row.accountUsername]), [['a', 'r1', 'ribbon']]);
-});
-
-test('posts filter by subreddit and sort by karma', () => {
- const rows = [post('a', 5), post('b', 50), post('c', 20, 'paper')];
- assert.deepEqual(filterAndSortRedditPosts(rows, { query: '', sort: 'score-desc', subreddit: 'origami' }).map(row => row.id), ['b', 'a']);
-});
-
-test('a sort from the address that is not an option falls back to most karma', () => {
- assert.equal(redditSortOf('date-asc'), 'date-asc');
- assert.equal(redditSortOf('upvotes'), 'score-desc');
-});
diff --git a/frontend/tests/layout/routes.test.ts b/frontend/tests/layout/routes.test.ts
index 743ea12..c467520 100644
--- a/frontend/tests/layout/routes.test.ts
+++ b/frontend/tests/layout/routes.test.ts
@@ -13,8 +13,8 @@ test('the overview link matches only the overview itself', () => {
});
test('a section link matches its own pages but not a path that only starts with the same letters', () => {
- assert.equal(matchesPath('/reddit', '/reddit/abc'), true);
- assert.equal(matchesPath('/reddit', '/reddit-posts'), false);
+ assert.equal(matchesPath('/automations', '/automations/rules'), true);
+ assert.equal(matchesPath('/automations', '/automations-old'), false);
});
test('only the most specific matching link is active', () => {
diff --git a/frontend/tests/lib/commandSearch.test.ts b/frontend/tests/lib/commandSearch.test.ts
index c1c9f7a..6a81be1 100644
--- a/frontend/tests/lib/commandSearch.test.ts
+++ b/frontend/tests/lib/commandSearch.test.ts
@@ -5,7 +5,7 @@ import { scoreCommand, filterCommands, groupCommands } from '../../src/lib/comma
const commands = [
{ id: 'overview', group: 'Pages', label: 'Overview', keywords: ['Analytics'] },
{ id: 'videos', group: 'Pages', label: 'Videos', keywords: ['Analytics'] },
- { id: 'reddit-posts', group: 'Pages', label: 'Reddit posts', keywords: ['Analytics'] },
+ { id: 'instagram', group: 'Pages', label: 'Instagram content', keywords: ['Analytics'] },
{ id: 'acct', group: 'Accounts', label: 'Daily Café Vlogs', keywords: ['YouTube', 'cafevlogs'] },
{ id: 'theme-dark', group: 'Theme', label: 'Use dark theme', keywords: ['appearance', 'dusk'] },
];
@@ -26,8 +26,8 @@ test('keywords and groups are searchable', () => {
});
test('every word in the query must match', () => {
- assert.deepEqual(filterCommands(commands, 'reddit posts').map(c => c.id), ['reddit-posts']);
- assert.deepEqual(filterCommands(commands, 'reddit videos'), []);
+ assert.deepEqual(filterCommands(commands, 'instagram content').map(c => c.id), ['instagram']);
+ assert.deepEqual(filterCommands(commands, 'instagram videos'), []);
});
test('matching ignores case and accents', () => {