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)!: track YouTube videos only

spacesdrive1d4ac5145704
diff --git a/frontend/src/components/ImageLightbox.tsx b/frontend/src/components/ImageLightbox.tsx
deleted file mode 100644
index b41ac33..0000000
--- a/frontend/src/components/ImageLightbox.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import React, { useState } from 'react';
-import { Dialog, DialogContent, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
-import { cn } from '@/lib/utils';
-
-export interface ImageLightboxProps {
- src?: string | null;
- alt?: string;
- className?: string;
- thumbClassName?: string;
-}
-
-export default function ImageLightbox({
- src,
- alt = '',
- className = '',
- thumbClassName = 'h-10 w-16',
-}: ImageLightboxProps) {
- const [open, setOpen] = useState(false);
-
- if (!src) return null;
-
- return (
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogTrigger
- render={
- <button
- type="button"
- title="View image"
- aria-label={alt ? `View image for ${alt}` : 'View image'}
- className={cn(
- 'group relative shrink-0 overflow-hidden rounded-sm border border-line bg-surface-sunken',
- 'cursor-zoom-in transition-opacity duration-(--duration-base) hover:opacity-85',
- 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
- thumbClassName,
- className
- )}
- />
- }
- >
- <img src={src} alt={alt} loading="lazy" className="h-full w-full object-cover" />
- </DialogTrigger>
-
- <DialogContent className="gap-2 p-2 sm:max-w-3xl">
- <DialogTitle className="sr-only">{alt || 'Image preview'}</DialogTitle>
- <img
- src={src}
- alt={alt}
- className="max-h-[75vh] w-full rounded-card object-contain"
- />
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/frontend/src/features/analytics/tracked/AddTrackedDialog.tsx b/frontend/src/features/analytics/tracked/AddTrackedDialog.tsx
index 38d45bc..7580884 100644
--- a/frontend/src/features/analytics/tracked/AddTrackedDialog.tsx
+++ b/frontend/src/features/analytics/tracked/AddTrackedDialog.tsx
@@ -3,16 +3,14 @@ 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';
-import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinner';
import { FieldRow } from '@/components/DetailPanel';
import { PlatformBadge } from '@/components/platform';
import CategoryPicker from './CategoryPicker';
-import type { AppAccount } from '../../../utils/formatters';
import type { AddTracked } from './useAddTracked';
interface LinkStatusProps {
- detectedType: 'reddit' | 'youtube' | null;
+ detectedType: 'youtube' | null;
}
// a found link is confirmed as soon as it is pasted; the region stays mounted so the confirmation is announced
@@ -22,7 +20,7 @@ function LinkStatus({ detectedType }: LinkStatusProps) {
{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'}
+ YouTube video found
</p>
)}
</div>
@@ -31,23 +29,18 @@ function LinkStatus({ detectedType }: LinkStatusProps) {
export interface AddTrackedDialogProps {
add: AddTracked;
- redditAccounts: AppAccount[];
categories: string[];
}
-export default function AddTrackedDialog({ add, redditAccounts, categories }: AddTrackedDialogProps) {
+export default function AddTrackedDialog({ add, categories }: AddTrackedDialogProps) {
const { draft, detectedType, adding } = add;
const { url } = draft;
- const accountItems = [
- { value: 'none', label: 'No account (public posts only)' },
- ...redditAccounts.map(account => ({ value: account.id, label: `u/${account.username}` })),
- ];
return (
<Dialog open={add.open} onOpenChange={add.handleOpenChange}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>Track content</DialogTitle>
- <DialogDescription>Paste a Reddit post or a YouTube video or Shorts link.</DialogDescription>
+ <DialogDescription>Paste a YouTube video or Shorts link.</DialogDescription>
</DialogHeader>
<form id="track-form" onSubmit={add.handleAdd} noValidate className="flex flex-col gap-5">
<FieldRow label="Link" htmlFor="track-url" error={add.urlError ?? undefined}>
@@ -65,20 +58,6 @@ export default function AddTrackedDialog({ add, redditAccounts, categories }: Ad
</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">
- <Select value={add.accountId} onValueChange={add.setAccountId as (value: string | null) => void} items={accountItems}>
- <SelectTrigger id="track-account" className="w-full"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- <SelectItem value="none">No account (public posts only)</SelectItem>
- {redditAccounts.map(account => <SelectItem key={account.id} value={account.id}>u/{account.username}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
- </FieldRow>
- )}
-
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
<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)} />
diff --git a/frontend/src/features/analytics/tracked/CategoryRedditSection.tsx b/frontend/src/features/analytics/tracked/CategoryRedditSection.tsx
deleted file mode 100644
index 7eb6eaa..0000000
--- a/frontend/src/features/analytics/tracked/CategoryRedditSection.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-import { useMemo } from 'react';
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
-import MetricBox from '@/components/MetricBox';
-import SurfaceBox from '@/components/SurfaceBox';
-import SectionHeader from '@/components/SectionHeader';
-import MetricAreaChart from '@/components/MetricAreaChart';
-import RelativeTime from '@/components/RelativeTime';
-import Num from '@/components/Num';
-import { METRIC_ICONS } from '@/lib/metricIcons';
-import ImageLightbox from '@/components/ImageLightbox';
-import ColumnHint from '@/components/ColumnHint';
-import { RankNumber } from '@/components/ListRow';
-import { PlatformIcon } from '@/components/platform';
-import { PLATFORM_META } from '@/lib/accounts';
-import { pointsOf, rankingSummary } from '@/lib/chart';
-import { fmtNum, fmtNumFull } from '../../../utils/formatters';
-import { hasTrackedViews, trackedViews } from '../../../utils/trackedContent';
-import NumberCell from './NumberCell';
-import OpenLink from './OpenLink';
-import { chartDataOf, redditViewsMetric, sortedByKarma, upvoteRatioLabel } from './trackedCategoryStats.ts';
-import type { RedditCategoryStats } from './trackedCategoryStats.ts';
-import type { TrackedContentItem } from '@shared/types/domain.ts';
-
-interface PostRowProps {
- item: TrackedContentItem;
- rank: number;
-}
-
-function PostRow({ item, rank }: PostRowProps) {
- return (
- <TableRow>
- <TableCell className="text-right"><RankNumber rank={rank} className="w-auto" /></TableCell>
- <TableCell className="whitespace-normal">
- <div className="flex items-start gap-3">
- {item.imageUrl && <ImageLightbox src={item.imageUrl} alt={item.title || 'Reddit post'} className="mt-0.5" />}
- <div className="min-w-0">
- <p className="line-clamp-2 text-sm font-medium leading-snug text-ink" title={item.title || item.url}>{item.title || item.url}</p>
- <div className="mt-1 flex flex-wrap items-center gap-1.5">
- {item.subredditPrefixed && <span className="text-caption text-ink-faint">{item.subredditPrefixed}</span>}
- {item.label && <span className="text-caption text-ink-faint italic">{item.label}</span>}
- </div>
- </div>
- </div>
- </TableCell>
- <NumberCell value={item.score} />
- <TableCell className="hidden text-right text-ink-muted sm:table-cell">{hasTrackedViews(item) ? <Num value={trackedViews(item)} /> : '-'}</TableCell>
- <TableCell className="hidden text-right text-ink-muted md:table-cell">{item.upvoteRatio != null && (item.score ?? 0) >= 10 ? `${Math.round(item.upvoteRatio * 100)}%` : '-'}</TableCell>
- <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={item.numComments ?? 0} /></TableCell>
- <TableCell className="hidden text-right text-small text-ink-faint md:table-cell">{item.lastFetchedAt ? <RelativeTime date={item.lastFetchedAt} /> : '-'}</TableCell>
- <TableCell><OpenLink href={item.permalink || item.url} label={`Open "${item.title || 'post'}" on Reddit`} /></TableCell>
- </TableRow>
- );
-}
-
-export interface CategoryRedditSectionProps {
- items: TrackedContentItem[];
- stats: RedditCategoryStats;
-}
-
-export default function CategoryRedditSection({ items, stats }: CategoryRedditSectionProps) {
- const sorted = useMemo(() => sortedByKarma(items), [items]);
- const chartData = chartDataOf(sorted, 'karma', item => item.score ?? 0);
- const views = redditViewsMetric(stats);
- return (
- <section className="flex flex-col gap-4">
- <SectionHeader
- className="mt-2"
- title={<span className="flex items-center gap-2"><PlatformIcon platform="reddit" className="text-ink-muted" />Reddit posts</span>}
- actions={<span className="text-small text-ink-faint">{items.length} post{items.length !== 1 ? 's' : ''}</span>}
- />
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <MetricBox small icon={<METRIC_ICONS.karma />} label="Post karma" value={<Num value={stats.karma} />} subtitle={`${fmtNum(stats.avgKarma)} per post on average`} />
- <MetricBox small icon={<METRIC_ICONS.views />} label="Post views" value={views.value} subtitle={views.subtitle} />
- <MetricBox small icon={<METRIC_ICONS.comments />} label="Post comments" value={<Num value={stats.comments} />} subtitle={`${fmtNum(stats.avgComments)} per post on average`} />
- <MetricBox small icon={<METRIC_ICONS.upvoteRate />} label="Average upvote ratio" value={upvoteRatioLabel(stats.avgRatio)} subtitle="Upvotes as a share of all votes" />
- </div>
- {chartData.length > 1 && (
- <SurfaceBox title="Post karma" headingLevel="h3" subheader={`Top ${chartData.length} posts in this category ranked by karma`}>
- <MetricAreaChart
- data={chartData}
- dataKey="karma"
- label="Karma"
- title="Post karma"
- description={rankingSummary(pointsOf(chartData, 'name', 'karma'), fmtNumFull, 'karma')}
- color={PLATFORM_META.reddit.series}
- height={260}
- />
- </SurfaceBox>
- )}
- <SurfaceBox title="All posts in this category" headingLevel="h3" content={false} className="overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead>Post</TableHead>
- <TableHead className="w-28 text-right">Karma</TableHead>
- <TableHead className="hidden w-24 text-right sm:table-cell">Views</TableHead>
- <TableHead className="hidden w-32 text-right md:table-cell"><ColumnHint label="Upvote rate" hint="Share of votes on a Reddit post that are upvotes. Shows a dash for YouTube videos and for posts under 10 karma, where the ratio is not meaningful." /></TableHead>
- <TableHead className="hidden w-24 text-right sm:table-cell">Comments</TableHead>
- <TableHead className="hidden w-28 text-right md:table-cell">Fetched</TableHead>
- <TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {sorted.map((item, i) => <PostRow key={item.id} item={item} rank={i + 1} />)}
- </TableBody>
- </Table>
- </SurfaceBox>
- </section>
- );
-}
diff --git a/frontend/src/features/analytics/tracked/CategoryYouTubeSection.tsx b/frontend/src/features/analytics/tracked/CategoryYouTubeSection.tsx
index d270a8c..41d3969 100644
--- a/frontend/src/features/analytics/tracked/CategoryYouTubeSection.tsx
+++ b/frontend/src/features/analytics/tracked/CategoryYouTubeSection.tsx
@@ -2,22 +2,17 @@ import { useMemo } from 'react';
import { CirclePlay } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
-import MetricBox from '@/components/MetricBox';
import SurfaceBox from '@/components/SurfaceBox';
-import SectionHeader from '@/components/SectionHeader';
import MetricAreaChart from '@/components/MetricAreaChart';
import RelativeTime from '@/components/RelativeTime';
import Num from '@/components/Num';
-import { METRIC_ICONS } from '@/lib/metricIcons';
import { RankNumber } from '@/components/ListRow';
-import { PlatformIcon } from '@/components/platform';
import { PLATFORM_META } from '@/lib/accounts';
import { pointsOf, rankingSummary } from '@/lib/chart';
-import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import { fmtNumFull } from '../../../utils/formatters';
import NumberCell from './NumberCell';
import OpenLink from './OpenLink';
import { chartDataOf, sortedByViews } from './trackedCategoryStats.ts';
-import type { YouTubeCategoryStats } from './trackedCategoryStats.ts';
import type { TrackedContentItem } from '@shared/types/domain.ts';
interface VideoRowProps {
@@ -57,27 +52,15 @@ function VideoRow({ item, rank }: VideoRowProps) {
export interface CategoryYouTubeSectionProps {
items: TrackedContentItem[];
- stats: YouTubeCategoryStats;
}
-export default function CategoryYouTubeSection({ items, stats }: CategoryYouTubeSectionProps) {
+export default function CategoryYouTubeSection({ items }: CategoryYouTubeSectionProps) {
const sorted = useMemo(() => sortedByViews(items), [items]);
const chartData = chartDataOf(sorted, 'views', item => item.viewCount ?? 0);
return (
<section className="flex flex-col gap-4">
- <SectionHeader
- className="mt-2"
- title={<span className="flex items-center gap-2"><PlatformIcon platform="youtube" className="text-ink-muted" />YouTube videos</span>}
- actions={<span className="text-small text-ink-faint">{items.length} video{items.length !== 1 ? 's' : ''}</span>}
- />
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <MetricBox small icon={<METRIC_ICONS.views />} label="Video views" value={<Num value={stats.views} />} subtitle={`${fmtNum(stats.avgViews)} per video on average`} />
- <MetricBox small icon={<METRIC_ICONS.likes />} label="Video likes" value={<Num value={stats.likes} />} subtitle={`${fmtNum(stats.avgLikes)} per video on average`} />
- <MetricBox small icon={<METRIC_ICONS.comments />} label="Video comments" value={<Num value={stats.comments} />} subtitle={`${fmtNum(stats.avgComments)} per video on average`} />
- <MetricBox small icon={<METRIC_ICONS.rate />} label="Likes per view" value={`${stats.likeRatio}%`} subtitle="Likes as a share of views" />
- </div>
{chartData.length > 1 && (
- <SurfaceBox title="Video views" headingLevel="h3" subheader={`Top ${chartData.length} videos in this category ranked by views`}>
+ <SurfaceBox title="Video views" subheader={`Top ${chartData.length} videos in this category ranked by views`}>
<MetricAreaChart
data={chartData}
dataKey="views"
@@ -89,7 +72,7 @@ export default function CategoryYouTubeSection({ items, stats }: CategoryYouTube
/>
</SurfaceBox>
)}
- <SurfaceBox title="All videos in this category" headingLevel="h3" content={false} className="overflow-hidden">
+ <SurfaceBox title="All videos in this category" content={false} className="overflow-hidden">
<Table>
<TableHeader>
<TableRow>
diff --git a/frontend/src/features/analytics/tracked/EditTrackedDialog.tsx b/frontend/src/features/analytics/tracked/EditTrackedDialog.tsx
index 28c494d..6d9dcd4 100644
--- a/frontend/src/features/analytics/tracked/EditTrackedDialog.tsx
+++ b/frontend/src/features/analytics/tracked/EditTrackedDialog.tsx
@@ -5,9 +5,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import { FieldRow } from '@/components/DetailPanel';
-import { isRedditItem } from '../../../utils/trackedContent';
import CategoryPicker from './CategoryPicker';
-import TrackedImageField from './TrackedImageField';
import type { TrackedEditor } from './useTrackedEditor';
export interface EditTrackedDialogProps {
@@ -17,12 +15,11 @@ export interface EditTrackedDialogProps {
export default function EditTrackedDialog({ editor, categories }: EditTrackedDialogProps) {
const { editItem, fields, setField, saving } = editor;
- const showRedditFields = editItem && isRedditItem(editItem);
return (
<Dialog open={Boolean(editItem)} onOpenChange={open => { if (!open && !saving) editor.setEditItem(null); }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
- <DialogTitle>Edit tracked item</DialogTitle>
+ <DialogTitle>Edit tracked video</DialogTitle>
<DialogDescription className="line-clamp-2">{editItem?.title || editItem?.url}</DialogDescription>
</DialogHeader>
<form id="edit-tracked-form" onSubmit={editor.handleSaveEdit} noValidate className="flex flex-col gap-5">
@@ -34,20 +31,6 @@ export default function EditTrackedDialog({ editor, categories }: EditTrackedDia
<CategoryPicker categories={categories} onPick={category => setField('category', category)} />
</FieldRow>
- {showRedditFields && (
- <FieldRow
- label="Views"
- 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="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 />
@@ -57,7 +40,7 @@ export default function EditTrackedDialog({ editor, categories }: EditTrackedDia
</form>
<DialogFooter>
<Button variant="outline" onClick={() => editor.setEditItem(null)} disabled={saving}>Cancel</Button>
- <Button type="submit" form="edit-tracked-form" disabled={saving || editor.uploading}>
+ <Button type="submit" form="edit-tracked-form" disabled={saving}>
{saving && <Spinner className="size-4" />}
{saving ? 'Saving' : 'Save changes'}
</Button>
diff --git a/frontend/src/features/analytics/tracked/TrackedCategory.tsx b/frontend/src/features/analytics/tracked/TrackedCategory.tsx
index a05581f..318898c 100644
--- a/frontend/src/features/analytics/tracked/TrackedCategory.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedCategory.tsx
@@ -9,17 +9,14 @@ import { EmptyState, ErrorState, PageSkeleton } from '@/components/StateViews';
import { METRIC_ICONS } from '@/lib/metricIcons';
import { useDocumentTitle } from '@/hooks/use-document-title';
import { api } from '../../../services/api';
-import { isRedditItem } from '../../../utils/trackedContent';
-import CategoryRedditSection from './CategoryRedditSection';
import CategoryYouTubeSection from './CategoryYouTubeSection';
-import {
- categoryDescription, commentsSubtitle, itemsSubtitle, karmaMetric, redditStatsOf, viewsMetric, youtubeStatsOf,
-} from './trackedCategoryStats.ts';
+import { fmtNum } from '../../../utils/formatters';
+import { categoryDescription, shortsSubtitle, youtubeStatsOf } from './trackedCategoryStats.ts';
import type { TrackedContentItem } from '@shared/types/domain.ts';
const BACK_LINK = { to: '/tracked-content', label: 'Tracked content' };
-const { tracked: Items, views: Views, karma: Karma, comments: Comments, category: Category } = METRIC_ICONS;
+const { tracked: Items, views: Views, likes: Likes, comments: Comments, category: Category } = METRIC_ICONS;
export default function TrackedCategory() {
const { name } = useParams();
@@ -45,10 +42,7 @@ export default function TrackedCategory() {
useEffect(() => { load(); }, [load]);
- const ytItems = useMemo(() => items.filter(item => item.contentType === 'youtube'), [items]);
- const rdItems = useMemo(() => items.filter(isRedditItem), [items]);
- const ytStats = useMemo(() => youtubeStatsOf(ytItems), [ytItems]);
- const rdStats = useMemo(() => redditStatsOf(rdItems), [rdItems]);
+ const stats = useMemo(() => youtubeStatsOf(items), [items]);
if (loading) return <PageSkeleton metrics={4} />;
@@ -69,7 +63,7 @@ export default function TrackedCategory() {
<EmptyState
icon={<Category />}
title={`Nothing tracked in ${categoryName}`}
- description="Assign this category to a Reddit post or YouTube video in Tracked content and its analytics appear here."
+ description="Assign this category to a YouTube video in Tracked content and its analytics appear here."
action={<Button size="sm" render={<Link to="/tracked-content" />}>Open tracked content</Button>}
/>
</SurfaceBox>
@@ -77,28 +71,24 @@ export default function TrackedCategory() {
);
}
- const views = viewsMetric(ytStats, rdStats);
- const karma = karmaMetric(rdStats);
-
return (
<div className="flex flex-col gap-6">
<PageHeader
back={BACK_LINK}
eyebrow="Category"
title={categoryName}
- description={categoryDescription(items.length, ytItems.length, rdItems.length)}
+ description={categoryDescription(stats)}
actions={<Button variant="outline" render={<Link to="/tracked-content" />}>Manage content</Button>}
/>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <MetricBox icon={<Items />} label="Items" value={items.length} subtitle={itemsSubtitle(ytStats, rdStats)} />
- <MetricBox icon={<Views />} label="Views" value={views.value} subtitle={views.subtitle} highlight />
- <MetricBox icon={<Karma />} label="Reddit karma" value={karma.value} subtitle={karma.subtitle} />
- <MetricBox icon={<Comments />} label="Comments" value={<Num value={ytStats.comments + rdStats.comments} />} subtitle={commentsSubtitle(ytStats, rdStats)} />
+ <MetricBox icon={<Items />} label="Videos" value={stats.count} subtitle={shortsSubtitle(stats)} />
+ <MetricBox icon={<Views />} label="Views" value={<Num value={stats.views} />} subtitle={`${fmtNum(stats.avgViews)} per video on average`} highlight />
+ <MetricBox icon={<Likes />} label="Likes" value={<Num value={stats.likes} />} subtitle={`${stats.likeRatio}% of views`} />
+ <MetricBox icon={<Comments />} label="Comments" value={<Num value={stats.comments} />} subtitle={`${fmtNum(stats.avgComments)} per video on average`} />
</div>
- {ytItems.length > 0 && <CategoryYouTubeSection items={ytItems} stats={ytStats} />}
- {rdItems.length > 0 && <CategoryRedditSection items={rdItems} stats={rdStats} />}
+ <CategoryYouTubeSection items={items} />
</div>
);
}
diff --git a/frontend/src/features/analytics/tracked/TrackedContent.tsx b/frontend/src/features/analytics/tracked/TrackedContent.tsx
index 75990e6..952637f 100644
--- a/frontend/src/features/analytics/tracked/TrackedContent.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedContent.tsx
@@ -8,7 +8,6 @@ import NoResults from '@/components/NoResults';
import { EmptyState, ErrorState } from '@/components/StateViews';
import { resultCountLabel } from '@/lib/library';
import { useAppContext } from '../../../context/AppContext';
-import { useCloudinaryConfig } from '../../../hooks/use-cloudinary-config';
import AddTrackedDialog from './AddTrackedDialog';
import BulkCategoryBar from './BulkCategoryBar';
import EditTrackedDialog from './EditTrackedDialog';
@@ -27,17 +26,15 @@ import { useTrackedSelection } from './useTrackedSelection';
const RESULTS_ID = 'tracked-results';
export default function TrackedContent() {
- const { accounts, showToast } = useAppContext();
- const redditAccounts = accounts.filter(account => account.platform === 'reddit');
+ const { showToast } = useAppContext();
const tracked = useTrackedItems(showToast);
const { setItems, replaceItem } = tracked;
- const cloudConfig = useCloudinaryConfig();
const filters = useTrackedFilters(tracked.items);
const selection = useTrackedSelection(filters.filtered);
const bulk = useBulkCategory({ selection, setItems, showToast });
const removal = useTrackedDelete({ setItems, dropSelection: selection.drop, showToast });
- const add = useAddTracked({ redditAccounts, setItems, showToast });
- const editor = useTrackedEditor({ cloudConfig, replaceItem, showToast });
+ const add = useAddTracked({ setItems, showToast });
+ const editor = useTrackedEditor({ replaceItem, showToast });
const isEmpty = !tracked.loading && !tracked.error && tracked.items.length === 0;
const typeLabel = typeChipsOf(filters.stats).find(chip => chip.value === filters.typeFilter && chip.value !== 'all')?.label;
@@ -51,7 +48,7 @@ export default function TrackedContent() {
const header = (
<PageHeader
title="Tracked content"
- description="Reddit posts and YouTube videos you follow, with karma, likes and comments."
+ description="YouTube videos you follow, with their views, likes and comments."
actions={!isEmpty && (
<Button onClick={() => add.setOpen(true)}>
<Plus data-icon="inline-start" aria-hidden="true" />
@@ -94,7 +91,7 @@ export default function TrackedContent() {
<EmptyState
icon={<Bookmark />}
title="Nothing tracked yet"
- description="Paste a Reddit post or YouTube video link to follow its karma, likes and comments."
+ description="Paste a YouTube video or Shorts link to follow its views, likes and comments."
action={<Button onClick={() => add.setOpen(true)}><Plus data-icon="inline-start" aria-hidden="true" />Track content</Button>}
/>
</SurfaceBox>
@@ -102,11 +99,11 @@ export default function TrackedContent() {
<>
<TrackedMetrics stats={filters.stats} />
<TrackedFilters filters={filters} />
- <ActiveFilters countLabel={resultCountLabel(filters.filtered.length, tracked.items.length, 'items')} filters={activeFilters} onClearAll={filters.clearFilters} />
+ <ActiveFilters countLabel={resultCountLabel(filters.filtered.length, tracked.items.length, 'videos')} filters={activeFilters} onClearAll={filters.clearFilters} />
{selection.someSelected && <BulkCategoryBar selectedCount={selection.selected.size} bulk={bulk} onClear={selection.clear} />}
<div id={RESULTS_ID} tabIndex={-1} className="outline-none">
{filters.filtered.length === 0 ? (
- <SurfaceBox><NoResults noun="items" query={filters.query} onClear={filters.clearFilters} /></SurfaceBox>
+ <SurfaceBox><NoResults noun="videos" query={filters.query} onClear={filters.clearFilters} /></SurfaceBox>
) : (
<TrackedTable
filtered={filters.filtered}
@@ -121,7 +118,7 @@ export default function TrackedContent() {
</>
)}
- <AddTrackedDialog add={add} redditAccounts={redditAccounts} categories={filters.categories} />
+ <AddTrackedDialog add={add} categories={filters.categories} />
<EditTrackedDialog editor={editor} categories={filters.categories} />
</div>
);
diff --git a/frontend/src/features/analytics/tracked/TrackedFilters.tsx b/frontend/src/features/analytics/tracked/TrackedFilters.tsx
index 03b1c2e..5afc3e4 100644
--- a/frontend/src/features/analytics/tracked/TrackedFilters.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedFilters.tsx
@@ -14,7 +14,7 @@ export default function TrackedFilters({ filters }: TrackedFiltersProps) {
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
- <SearchField value={filters.query} onChange={filters.setQuery} placeholder="Search titles, channels, subreddits and labels" className="min-w-56 flex-1" />
+ <SearchField value={filters.query} onChange={filters.setQuery} placeholder="Search titles, channels and labels" className="min-w-56 flex-1" />
{categories.length > 0 && (
<Select
value={filters.categoryFilter}
@@ -32,7 +32,7 @@ export default function TrackedFilters({ filters }: TrackedFiltersProps) {
)}
<SortSelect options={SORT_OPTIONS} value={filters.sort} onChange={filters.setSort} />
</div>
- <FilterChips label="Content type" options={typeChipsOf(filters.stats)} value={filters.typeFilter} onChange={filters.setTypeFilter} />
+ <FilterChips label="Video type" options={typeChipsOf(filters.stats)} value={filters.typeFilter} onChange={filters.setTypeFilter} />
</div>
);
}
diff --git a/frontend/src/features/analytics/tracked/TrackedImageField.tsx b/frontend/src/features/analytics/tracked/TrackedImageField.tsx
deleted file mode 100644
index 0f9518d..0000000
--- a/frontend/src/features/analytics/tracked/TrackedImageField.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { useEffect, useRef } from 'react';
-import { Upload, X } from 'lucide-react';
-import { Button } from '@/components/ui/button';
-import { Spinner } from '@/components/ui/spinner';
-import { FieldRow } from '@/components/DetailPanel';
-import ImageLightbox from '@/components/ImageLightbox';
-import type { TrackedEditor } from './useTrackedEditor';
-
-interface UploadImageButtonProps {
- uploading: boolean;
- disabled: boolean;
- onClick: () => void;
-}
-
-function UploadImageButton({ uploading, disabled, onClick }: UploadImageButtonProps) {
- if (uploading) {
- return (
- <Button type="button" variant="outline" className="justify-start" onClick={onClick} disabled>
- <Spinner className="size-4" />
- Uploading image
- </Button>
- );
- }
- return (
- <Button id="tracked-image-upload" type="button" variant="outline" className="justify-start" onClick={onClick} disabled={disabled}>
- <Upload data-icon="inline-start" />
- Upload image
- </Button>
- );
-}
-
-export interface TrackedImageFieldProps {
- editor: TrackedEditor;
-}
-
-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" 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-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>
- ) : (
- <UploadImageButton uploading={uploading} disabled={!cloudConfig} onClick={() => imageInputRef.current?.click()} />
- )}
- </FieldRow>
- );
-}
diff --git a/frontend/src/features/analytics/tracked/TrackedMetrics.tsx b/frontend/src/features/analytics/tracked/TrackedMetrics.tsx
index ba31127..55ba5cf 100644
--- a/frontend/src/features/analytics/tracked/TrackedMetrics.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedMetrics.tsx
@@ -3,7 +3,7 @@ import { METRIC_ICONS } from '@/lib/metricIcons';
import { countLabel, pluralize } from './trackedList.ts';
import type { TrackedStats } from './trackedList.ts';
-const { tracked: Tracked, category: Category, videos: Videos, redditPosts: Posts } = METRIC_ICONS;
+const { tracked: Tracked, category: Category, regularVideos: Videos, shorts: Shorts } = METRIC_ICONS;
function categoriesSubtitle(count: number): string {
if (count === 0) return 'None assigned yet';
@@ -22,10 +22,10 @@ export interface TrackedMetricsProps {
export default function TrackedMetrics({ stats }: TrackedMetricsProps) {
return (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
- <MetricBox icon={<Tracked />} label="Tracked items" value={stats.total} subtitle="Across all categories" highlight />
- <MetricBox icon={<Category />} label="Categories" value={stats.categories} subtitle={categoriesSubtitle(stats.categories)} />
- <MetricBox icon={<Videos />} label="YouTube" value={stats.youtube} subtitle={trackedSubtitle(stats.youtube, 'No videos tracked', 'Video')} />
- <MetricBox icon={<Posts />} label="Reddit" value={stats.reddit} subtitle={trackedSubtitle(stats.reddit, 'No posts tracked', 'Post')} />
+ <MetricBox icon={<Tracked />} label="Tracked videos" value={stats.total} subtitle="Across all categories" highlight />
+ <MetricBox icon={<Category />} label="Categories" value={stats.categories} subtitle={categoriesSubtitle(stats.categories)} />
+ <MetricBox icon={<Videos />} label="Videos" value={stats.videos} subtitle={trackedSubtitle(stats.videos, 'No videos tracked', 'Video')} />
+ <MetricBox icon={<Shorts />} label="Shorts" value={stats.shorts} subtitle={trackedSubtitle(stats.shorts, 'No Shorts tracked', 'Short')} />
</div>
);
}
diff --git a/frontend/src/features/analytics/tracked/TrackedRow.tsx b/frontend/src/features/analytics/tracked/TrackedRow.tsx
index a3389b2..2fb208e 100644
--- a/frontend/src/features/analytics/tracked/TrackedRow.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedRow.tsx
@@ -1,39 +1,15 @@
import { ExternalLink, Pencil, RefreshCw, Trash2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
-import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { TableCell, TableRow } from '@/components/ui/table';
-import { PlatformBadge } from '@/components/platform';
import Num from '@/components/Num';
import RelativeTime from '@/components/RelativeTime';
-import { METRIC_ICONS } from '@/lib/metricIcons';
import { cn } from '@/lib/utils';
import { hasTrackedViews, trackedViews } from '../../../utils/trackedContent';
import RowAction from '@/components/RowAction';
import TrackedThumbnail from './TrackedThumbnail';
import type { TrackedContentItem } from '@shared/types/domain.ts';
-const Views = METRIC_ICONS.views;
-
-interface ViewsCellProps {
- item: TrackedContentItem;
- title: string;
- isYT: boolean;
- onEdit: (item: TrackedContentItem) => void;
-}
-
-// the reason views are missing is part of the button's name, so it reaches touch and screen reader users too
-function ViewsCell({ item, title, isYT, onEdit }: ViewsCellProps) {
- if (hasTrackedViews(item)) return <span className="text-ink"><Num value={trackedViews(item)} /></span>;
- if (isYT) return <span className="text-ink-faint">-</span>;
- return (
- <Button variant="ghost" size="xs" onClick={() => onEdit(item)} title="Reddit does not report views. Enter them by hand.">
- <Views aria-hidden="true" />Add
- <span className="sr-only"> views for {title}. Reddit does not report views, so they are entered by hand.</span>
- </Button>
- );
-}
-
export interface TrackedRowProps {
item: TrackedContentItem;
isSelected: boolean;
@@ -45,10 +21,7 @@ export interface TrackedRowProps {
}
export default function TrackedRow({ item, isSelected, isRefreshing, onToggle, onRefresh, onEdit, onDelete }: TrackedRowProps) {
- const isYT = item.contentType === 'youtube';
const title = item.title || item.label || item.url;
- const engagement = isYT ? item.likeCount : item.score;
- const comments = isYT ? item.commentCount : item.numComments;
return (
<TableRow data-state={isSelected ? 'selected' : undefined}>
<TableCell>
@@ -56,14 +29,13 @@ export default function TrackedRow({ item, isSelected, isRefreshing, onToggle, o
</TableCell>
<TableCell className="sticky left-0 z-[1] bg-surface-raised whitespace-normal">
<div className="flex max-w-56 items-start gap-3 sm:max-w-sm">
- <TrackedThumbnail item={item} title={title} isYT={isYT} />
+ <TrackedThumbnail item={item} />
<div className="min-w-0">
<p className="line-clamp-2 text-sm font-medium leading-snug text-ink" title={title}>{title}</p>
<div className="mt-1 flex flex-wrap items-center gap-1.5">
- <PlatformBadge platform={item.contentType || 'reddit'} className="h-5" />
- <span className="text-caption text-ink-faint">{isYT ? item.channelTitle : item.subredditPrefixed}</span>
+ {item.channelTitle && <span className="text-caption text-ink-faint">{item.channelTitle}</span>}
{item.label && <span className="text-caption text-ink-faint italic">{item.label}</span>}
- {isYT && item.isShort && <Badge variant="outline">Short</Badge>}
+ {item.isShort && <Badge variant="outline">Short</Badge>}
{item.category && <Badge variant="secondary" className="lg:hidden">{item.category}</Badge>}
</div>
</div>
@@ -73,13 +45,10 @@ export default function TrackedRow({ item, isSelected, isRefreshing, onToggle, o
{item.category ? <Badge variant="secondary">{item.category}</Badge> : <span className="text-ink-faint">-</span>}
</TableCell>
<TableCell className="hidden text-right sm:table-cell">
- <ViewsCell item={item} title={title} isYT={isYT} onEdit={onEdit} />
- </TableCell>
- <TableCell className="text-right font-semibold text-ink">{engagement !== undefined ? <Num value={engagement} /> : '-'}</TableCell>
- <TableCell className="hidden text-right text-ink-muted md:table-cell">{comments !== undefined ? <Num value={comments} /> : '-'}</TableCell>
- <TableCell className="hidden text-right text-ink-muted lg:table-cell">
- {!isYT && item.upvoteRatio !== undefined && (item.score ?? 0) >= 10 ? `${Math.round(item.upvoteRatio * 100)}%` : '-'}
+ {hasTrackedViews(item) ? <span className="text-ink"><Num value={trackedViews(item)} /></span> : <span className="text-ink-faint">-</span>}
</TableCell>
+ <TableCell className="text-right font-semibold text-ink">{item.likeCount != null ? <Num value={item.likeCount} /> : '-'}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell">{item.commentCount != null ? <Num value={item.commentCount} /> : '-'}</TableCell>
<TableCell className="hidden text-right text-small text-ink-faint md:table-cell">
{item.lastFetchedAt ? <RelativeTime date={item.lastFetchedAt} /> : '-'}
</TableCell>
diff --git a/frontend/src/features/analytics/tracked/TrackedTable.tsx b/frontend/src/features/analytics/tracked/TrackedTable.tsx
index 3f76b7f..7835580 100644
--- a/frontend/src/features/analytics/tracked/TrackedTable.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedTable.tsx
@@ -1,7 +1,6 @@
import { Checkbox } from '@/components/ui/checkbox';
import { Table, TableBody, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import SurfaceBox from '@/components/SurfaceBox';
-import ColumnHint from '@/components/ColumnHint';
import TrackedRow from './TrackedRow';
import type { TrackedContentItem } from '@shared/types/domain.ts';
import type { TrackedSelection } from './useTrackedSelection';
@@ -17,19 +16,18 @@ export interface TrackedTableProps {
export default function TrackedTable({ filtered, selection, refreshingIds, onRefresh, onEdit, onDelete }: TrackedTableProps) {
return (
- <SurfaceBox title="Tracked items" content={false} className="overflow-hidden">
+ <SurfaceBox title="Tracked videos" content={false} className="overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-10">
- <Checkbox checked={selection.allSelected} onCheckedChange={selection.toggleAll} aria-label="Select all shown items" />
+ <Checkbox checked={selection.allSelected} onCheckedChange={selection.toggleAll} aria-label="Select all shown videos" />
</TableHead>
<TableHead className="sticky left-0 z-[1] bg-surface-raised">Content</TableHead>
<TableHead className="hidden w-32 lg:table-cell">Category</TableHead>
<TableHead className="hidden w-24 text-right sm:table-cell">Views</TableHead>
- <TableHead className="w-28 text-right">Likes or karma</TableHead>
+ <TableHead className="w-28 text-right">Likes</TableHead>
<TableHead className="hidden w-24 text-right md:table-cell">Comments</TableHead>
- <TableHead className="hidden w-32 text-right lg:table-cell"><ColumnHint label="Upvote rate" hint="Share of votes on a Reddit post that are upvotes. Shows a dash for YouTube videos and for posts under 10 karma, where the ratio is not meaningful." /></TableHead>
<TableHead className="hidden w-28 text-right md:table-cell">Fetched</TableHead>
<TableHead className="w-32"><span className="sr-only">Actions</span></TableHead>
</TableRow>
diff --git a/frontend/src/features/analytics/tracked/TrackedThumbnail.tsx b/frontend/src/features/analytics/tracked/TrackedThumbnail.tsx
index 14367a3..d721cb6 100644
--- a/frontend/src/features/analytics/tracked/TrackedThumbnail.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedThumbnail.tsx
@@ -1,18 +1,10 @@
-import ImageLightbox from '@/components/ImageLightbox';
import type { TrackedContentItem } from '@shared/types/domain.ts';
export interface TrackedThumbnailProps {
item: TrackedContentItem;
- title: string;
- isYT: boolean;
}
-export default function TrackedThumbnail({ item, title, isYT }: TrackedThumbnailProps) {
- if (isYT && item.thumbnail) {
- return <img src={item.thumbnail} alt="" loading="lazy" className="mt-0.5 h-10 w-16 shrink-0 rounded-sm object-cover" />;
- }
- if (!isYT && item.imageUrl) {
- return <ImageLightbox src={item.imageUrl} alt={title || 'Reddit post'} className="mt-0.5" />;
- }
- return null;
+export default function TrackedThumbnail({ item }: TrackedThumbnailProps) {
+ if (!item.thumbnail) return null;
+ return <img src={item.thumbnail} alt="" loading="lazy" className="mt-0.5 h-10 w-16 shrink-0 rounded-sm object-cover" />;
}
diff --git a/frontend/src/features/analytics/tracked/trackedCategoryStats.ts b/frontend/src/features/analytics/tracked/trackedCategoryStats.ts
index 413046c..d118fa7 100644
--- a/frontend/src/features/analytics/tracked/trackedCategoryStats.ts
+++ b/frontend/src/features/analytics/tracked/trackedCategoryStats.ts
@@ -1,10 +1,10 @@
-import { fmtNum } from '../../../utils/formatters.ts';
-import { hasTrackedViews, trackedViews } from '../../../utils/trackedContent.ts';
+import { trackedViews } from '../../../utils/trackedContent.ts';
import { countLabel } from './trackedList.ts';
import type { TrackedContentItem } from '../../../../../shared/types/domain.ts';
export interface YouTubeCategoryStats {
count: number;
+ shorts: number;
views: number;
likes: number;
comments: number;
@@ -14,27 +14,11 @@ export interface YouTubeCategoryStats {
likeRatio: string;
}
-export interface RedditCategoryStats {
- count: number;
- karma: number;
- comments: number;
- views: number;
- withViews: number;
- avgKarma: number;
- avgComments: number;
- avgRatio: number;
-}
-
export interface TrackedChartPoint {
name: string;
[dataKey: string]: string | number;
}
-export interface CategoryMetric {
- value: string;
- subtitle: string;
-}
-
const CHART_ITEMS = 12;
const CHART_LABEL_CHARS = 16;
@@ -53,6 +37,7 @@ export function youtubeStatsOf(ytItems: TrackedContentItem[]): YouTubeCategorySt
const comments = sumOf(ytItems, item => item.commentCount ?? 0);
return {
count, views, likes, comments,
+ shorts: ytItems.filter(item => item.isShort).length,
avgViews: averageOf(views, count),
avgLikes: averageOf(likes, count),
avgComments: averageOf(comments, count),
@@ -60,30 +45,10 @@ export function youtubeStatsOf(ytItems: TrackedContentItem[]): YouTubeCategorySt
};
}
-// Reddit post score is karma, so it is named and labelled as karma throughout
-export function redditStatsOf(rdItems: TrackedContentItem[]): RedditCategoryStats {
- const count = rdItems.length;
- const karma = sumOf(rdItems, item => item.score ?? 0);
- const comments = sumOf(rdItems, item => item.numComments ?? 0);
- const ratioSum = sumOf(rdItems, item => item.upvoteRatio ?? 0);
- const views = sumOf(rdItems, trackedViews);
- return {
- count, karma, comments, views,
- withViews: rdItems.filter(item => hasTrackedViews(item)).length,
- avgKarma: averageOf(karma, count),
- avgComments: averageOf(comments, count),
- avgRatio: count ? ratioSum / count : 0,
- };
-}
-
export function sortedByViews(ytItems: TrackedContentItem[]): TrackedContentItem[] {
return [...ytItems].sort((first, second) => (second.viewCount ?? 0) - (first.viewCount ?? 0));
}
-export function sortedByKarma(rdItems: TrackedContentItem[]): TrackedContentItem[] {
- return [...rdItems].sort((first, second) => (second.score ?? 0) - (first.score ?? 0));
-}
-
export function chartDataOf(sortedItems: TrackedContentItem[], dataKey: string, valueOf: (item: TrackedContentItem) => number): TrackedChartPoint[] {
return sortedItems.slice(0, CHART_ITEMS).map(item => ({
name: (item.title || item.url || '').slice(0, CHART_LABEL_CHARS),
@@ -91,47 +56,11 @@ export function chartDataOf(sortedItems: TrackedContentItem[], dataKey: string,
}));
}
-// each part is shown only when the category has items from that platform
-export function platformSplit(ytCount: number, rdCount: number, ytText: string, rdText: string): string {
- return [ytCount > 0 ? ytText : null, rdCount > 0 ? rdText : null].filter(Boolean).join(', ');
-}
-
-export function categoryDescription(total: number, ytCount: number, rdCount: number): string {
- return [
- countLabel(total, 'item'),
- ytCount > 0 ? `${ytCount} YouTube` : null,
- rdCount > 0 ? `${rdCount} Reddit` : null,
- ].filter(Boolean).join(', ');
-}
-
-export function itemsSubtitle(ytStats: YouTubeCategoryStats, rdStats: RedditCategoryStats): string {
- return platformSplit(ytStats.count, rdStats.count, countLabel(ytStats.count, 'YouTube video'), countLabel(rdStats.count, 'Reddit post'));
-}
-
-export function viewsMetric(ytStats: YouTubeCategoryStats, rdStats: RedditCategoryStats): CategoryMetric {
- const totalViews = ytStats.views + rdStats.views;
- if (totalViews > 0) {
- const subtitle = platformSplit(ytStats.count, rdStats.count, `${fmtNum(ytStats.views)} YouTube`, `${fmtNum(rdStats.views)} Reddit`);
- return { value: fmtNum(totalViews), subtitle };
- }
- return { value: '-', subtitle: 'No views recorded yet' };
-}
-
-export function karmaMetric(rdStats: RedditCategoryStats): CategoryMetric {
- if (rdStats.count > 0) return { value: fmtNum(rdStats.karma), subtitle: `${fmtNum(rdStats.avgKarma)} per post on average` };
- return { value: '-', subtitle: 'No Reddit posts in this category' };
-}
-
-export function commentsSubtitle(ytStats: YouTubeCategoryStats, rdStats: RedditCategoryStats): string {
- return platformSplit(ytStats.count, rdStats.count, `${fmtNum(ytStats.comments)} YouTube`, `${fmtNum(rdStats.comments)} Reddit`);
-}
-
-export function redditViewsMetric(rdStats: RedditCategoryStats): CategoryMetric {
- if (rdStats.withViews > 0) return { value: fmtNum(rdStats.views), subtitle: `Across ${countLabel(rdStats.count, 'post')}` };
- return { value: '-', subtitle: 'Reddit does not report views. Add them per post.' };
+export function categoryDescription(stats: YouTubeCategoryStats): string {
+ return countLabel(stats.count, 'video');
}
-export function upvoteRatioLabel(avgRatio: number): string {
- if (avgRatio > 0) return `${Math.round(avgRatio * 100)}%`;
- return '-';
+export function shortsSubtitle(stats: YouTubeCategoryStats): string {
+ if (stats.shorts === 0) return 'No Shorts';
+ return `${countLabel(stats.shorts, 'Short')} among them`;
}
diff --git a/frontend/src/features/analytics/tracked/trackedList.ts b/frontend/src/features/analytics/tracked/trackedList.ts
index 07b3156..ce41489 100644
--- a/frontend/src/features/analytics/tracked/trackedList.ts
+++ b/frontend/src/features/analytics/tracked/trackedList.ts
@@ -1,5 +1,5 @@
import { matchesText } from '../../../lib/library.ts';
-import { isRedditItem, trackedComments, trackedEngagement, trackedViews } from '../../../utils/trackedContent.ts';
+import { trackedComments, trackedLikes, trackedViews } from '../../../utils/trackedContent.ts';
import type { TrackedContentItem } from '../../../../../shared/types/domain.ts';
export interface TrackedSortOption {
@@ -17,8 +17,8 @@ export interface TrackedFilterOptions {
export interface TrackedStats {
total: number;
categories: number;
- youtube: number;
- reddit: number;
+ videos: number;
+ shorts: number;
}
export interface TrackedTypeChip {
@@ -32,16 +32,9 @@ export interface BulkCategoryResult {
severity: 'warning' | 'success';
}
-export interface ManualViewsResult {
- value?: number | null;
- error?: string;
-}
-
-export const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
-
export const SORT_OPTIONS: TrackedSortOption[] = [
{ value: 'date-desc', label: 'Newest first' },
- { value: 'engagement-desc', label: 'Most likes or karma' },
+ { value: 'engagement-desc', label: 'Most likes' },
{ value: 'comments-desc', label: 'Most comments' },
{ value: 'views-desc', label: 'Most views' },
];
@@ -52,7 +45,7 @@ export function trackedSortOf(value: string): string {
}
function compareTracked(sort: string, first: TrackedContentItem, second: TrackedContentItem): number {
- if (sort === 'engagement-desc') return trackedEngagement(second) - trackedEngagement(first);
+ if (sort === 'engagement-desc') return trackedLikes(second) - trackedLikes(first);
if (sort === 'comments-desc') return trackedComments(second) - trackedComments(first);
if (sort === 'views-desc') return trackedViews(second) - trackedViews(first);
return new Date(second.createdAt || 0).getTime() - new Date(first.createdAt || 0).getTime();
@@ -60,9 +53,9 @@ function compareTracked(sort: string, first: TrackedContentItem, second: Tracked
export function filterAndSortTracked(items: TrackedContentItem[], { typeFilter, categoryFilter, query, sort }: TrackedFilterOptions): TrackedContentItem[] {
let result = items;
- if (typeFilter !== 'all') result = result.filter(item => (item.contentType || 'reddit') === typeFilter);
+ if (typeFilter === 'video' || typeFilter === 'short') result = result.filter(item => Boolean(item.isShort) === (typeFilter === 'short'));
if (categoryFilter !== 'all') result = result.filter(item => item.category === categoryFilter);
- result = result.filter(item => matchesText([item.title, item.subreddit, item.channelTitle, item.label, item.category], query));
+ result = result.filter(item => matchesText([item.title, item.channelTitle, item.label, item.category], query));
return [...result].sort((first, second) => compareTracked(sort, first, second));
}
@@ -74,16 +67,16 @@ export function trackedStatsOf(items: TrackedContentItem[], categories: string[]
return {
total: items.length,
categories: categories.length,
- youtube: items.filter(item => item.contentType === 'youtube').length,
- reddit: items.filter(item => isRedditItem(item)).length,
+ videos: items.filter(item => !item.isShort).length,
+ shorts: items.filter(item => item.isShort).length,
};
}
export function typeChipsOf(stats: TrackedStats): TrackedTypeChip[] {
return [
{ value: 'all', label: 'All', count: stats.total },
- { value: 'reddit', label: 'Reddit posts', count: stats.reddit },
- { value: 'youtube', label: 'YouTube videos', count: stats.youtube },
+ { value: 'video', label: 'Videos', count: stats.videos },
+ { value: 'short', label: 'Shorts', count: stats.shorts },
];
}
@@ -101,27 +94,3 @@ export function bulkCategoryMessage(succeeded: number, failed: number): BulkCate
if (failed > 0) return { message: `${done}. ${failed} could not be updated; try those again.`, severity: 'warning' };
return { message: done, severity: 'success' };
}
-
-const VIEW_SUFFIXES: Record<string, number> = { k: 1e3, m: 1e6 };
-
-export const MANUAL_VIEWS_ERROR = 'Enter views as a whole number, such as 1200, 1,200 or 1.2K.';
-
-// an empty field clears the views; otherwise the number as Reddit's insights show it: separators and a K or M
-// suffix are accepted, so a copied "12.5K" works without retyping
-export function parseManualViews(raw: string): ManualViewsResult {
- const compact = raw.trim().replace(/[\s,_]/g, '');
- if (compact === '') return { value: null };
- const match = /^(\d+(?:\.\d+)?)([km])?$/i.exec(compact);
- if (!match) return { error: MANUAL_VIEWS_ERROR };
- const [, digits, suffix] = match;
- const number = Number(digits);
- if (!suffix) return Number.isInteger(number) ? { value: number } : { error: MANUAL_VIEWS_ERROR };
- return { value: Math.round(number * VIEW_SUFFIXES[suffix.toLowerCase()]) };
-}
-
-export function imageFileError(file: Pick<File, 'type' | 'size'>, hasCloudConfig: boolean): string {
- if (!hasCloudConfig) return 'Image uploads need Cloudinary set up on the server. Check Settings.';
- if (!file.type.startsWith('image/')) return 'That file is not an image. Choose a PNG, JPG or WebP file.';
- if (file.size > MAX_IMAGE_BYTES) return `That image is too large. Choose one under ${MAX_IMAGE_BYTES / 1024 / 1024}MB.`;
- return '';
-}
diff --git a/frontend/src/features/analytics/tracked/useAddTracked.ts b/frontend/src/features/analytics/tracked/useAddTracked.ts
index 05566a6..e7150f5 100644
--- a/frontend/src/features/analytics/tracked/useAddTracked.ts
+++ b/frontend/src/features/analytics/tracked/useAddTracked.ts
@@ -2,7 +2,6 @@ import { useState } from 'react';
import type { FormEvent } from 'react';
import { api } from '../../../services/api';
import { detectContentType } from '../../../utils/trackedContent';
-import type { AppAccount } from '../../../utils/formatters';
import type { SetTrackedItems, ShowToast } from './useTrackedItems';
export interface TrackedDraft {
@@ -12,7 +11,6 @@ export interface TrackedDraft {
}
export interface UseAddTrackedOptions {
- redditAccounts: AppAccount[];
setItems: SetTrackedItems;
showToast: ShowToast;
}
@@ -21,16 +19,14 @@ 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.';
+ if (!url.trim()) return 'Paste the link of a YouTube video or Short.';
+ if (!detectContentType(url.trim())) return 'Only YouTube videos can be tracked. Paste a youtube.com or youtu.be link.';
return null;
}
-// the default Reddit account is read once, when the page first renders
-export function useAddTracked({ redditAccounts, setItems, showToast }: UseAddTrackedOptions) {
+export function useAddTracked({ 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);
@@ -64,17 +60,15 @@ export function useAddTracked({ redditAccounts, setItems, showToast }: UseAddTra
document.getElementById('track-url')?.focus();
return;
}
- const type = detectContentType(url);
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());
+ const item = await api.addTrackedContent(url, draft.label.trim(), draft.category.trim());
setItems(prev => [item, ...prev]);
setOpen(false);
setDraft(EMPTY_DRAFT);
setChecked(false);
- showToast('Now tracking this content');
+ showToast('Now tracking this video');
} catch (err) {
setSubmitError(`Couldn't track that link. ${(err as Error).message}`);
} finally {
@@ -84,7 +78,7 @@ export function useAddTracked({ redditAccounts, setItems, showToast }: UseAddTra
return {
open, setOpen, handleOpenChange, draft, setDraftField, detectedType: detectContentType(draft.url),
- accountId, setAccountId, adding, handleAdd, urlError, checkUrl, submitError,
+ adding, handleAdd, urlError, checkUrl, submitError,
};
}
diff --git a/frontend/src/features/analytics/tracked/useTrackedEditor.ts b/frontend/src/features/analytics/tracked/useTrackedEditor.ts
index a7b7a78..cdf0336 100644
--- a/frontend/src/features/analytics/tracked/useTrackedEditor.ts
+++ b/frontend/src/features/analytics/tracked/useTrackedEditor.ts
@@ -1,99 +1,40 @@
-import { useRef, useState } from 'react';
-import type { ChangeEvent, FormEvent, RefObject } from 'react';
+import { useState } from 'react';
+import type { FormEvent } 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';
export interface TrackedEditFields {
label: string;
category: string;
- views: string;
}
-interface UseTrackedImageOptions {
- cloudConfig: CloudinaryConfigResponse | null;
- showToast: ShowToast;
-}
-
-export interface UseTrackedEditorOptions extends UseTrackedImageOptions {
+export interface UseTrackedEditorOptions {
replaceItem: (id: string, updated: TrackedContentItem) => void;
+ showToast: ShowToast;
}
-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) { 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) {
- setImageError(`Couldn't upload the image. ${(err as Error).message}`);
- } finally {
- setUploading(false);
- clearInput(imageInputRef);
- }
- };
-
- return { imageUrl, setImageUrl, uploading, imageInputRef, handleImageSelect, imageError, setImageError };
-}
-
-export function useTrackedEditor({ cloudConfig, replaceItem, showToast }: UseTrackedEditorOptions) {
- const image = useTrackedImage({ cloudConfig, showToast });
+export function useTrackedEditor({ replaceItem, showToast }: UseTrackedEditorOptions) {
const [editItem, setEditItem] = useState<TrackedContentItem | null>(null);
- const [fields, setFields] = useState<TrackedEditFields>({ label: '', category: '', views: '' });
+ const [fields, setFields] = useState<TrackedEditFields>({ label: '', category: '' });
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 }));
- 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);
+ setFields({ label: item.label || '', category: item.category || '' });
setSaveError(null);
- clearInput(image.imageInputRef);
};
const handleSaveEdit = async (e?: FormEvent<HTMLFormElement>) => {
e?.preventDefault();
if (!editItem || saving) return;
const updates: TrackedContentUpdateRequest = { label: fields.label, category: fields.category };
- if (isRedditItem(editItem)) {
- 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 {
@@ -107,12 +48,7 @@ export function useTrackedEditor({ cloudConfig, replaceItem, showToast }: UseTra
}
};
- // 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,
- };
+ return { editItem, setEditItem, fields, setField, saving, openEdit, handleSaveEdit, saveError };
}
export type TrackedEditor = ReturnType<typeof useTrackedEditor>;
diff --git a/frontend/src/features/analytics/tracked/viewsInput.ts b/frontend/src/features/analytics/tracked/viewsInput.ts
deleted file mode 100644
index 5520b23..0000000
--- a/frontend/src/features/analytics/tracked/viewsInput.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-// 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/lib/metricIcons.ts b/frontend/src/lib/metricIcons.ts
index 392779e..21be10b 100644
--- a/frontend/src/lib/metricIcons.ts
+++ b/frontend/src/lib/metricIcons.ts
@@ -1,6 +1,6 @@
import {
- Award, BarChart3, BookmarkCheck, Calendar, Camera, CirclePlay, Clapperboard, Clock, Film, Flame, Gauge, Hash, Heart, Image,
- MessageSquare, MessagesSquare, Percent, Scissors, Star, Tag, ThumbsUp, Timer, Trophy, UserPlus, Users, Video, Eye,
+ BarChart3, BookmarkCheck, Calendar, Camera, CirclePlay, Clapperboard, Clock, Film, Flame, Gauge, Hash, Heart, Image,
+ MessageSquare, Percent, Scissors, Tag, ThumbsUp, Timer, Trophy, UserPlus, Users, Video, Eye,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
@@ -11,9 +11,6 @@ export const METRIC_ICONS = {
likes: ThumbsUp,
instagramLikes: Heart,
comments: MessageSquare,
- karma: Award,
- awards: Star,
- upvoteRate: Percent,
rate: Percent,
audience: Users,
following: UserPlus,
@@ -23,7 +20,6 @@ export const METRIC_ICONS = {
instagram: Camera,
reels: Clapperboard,
posts: Image,
- redditPosts: MessagesSquare,
tracked: BookmarkCheck,
category: Tag,
tags: Hash,
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts
index 94be437..d81e0ba 100644
--- a/frontend/src/services/api.ts
+++ b/frontend/src/services/api.ts
@@ -109,20 +109,6 @@ function uploadToCloudinary(file: File, cloudConfig: CloudinaryUploadConfig, { o
});
}
-// screenshots need no progress events and show cloudinary's own error message
-async function uploadImage(file: File, cloudConfig: CloudinaryUploadConfig): Promise<string> {
- const formData = new FormData();
- formData.append('file', file);
- formData.append('upload_preset', cloudConfig.uploadPreset);
-
- const res = await fetch(`${CLOUDINARY_API}/${cloudConfig.cloudName}/image/upload`, { method: 'POST', body: formData });
- const json = await res.json() as CloudinaryUploadBody;
- if (!res.ok || !json.secure_url) {
- throw new Error(json.error?.message || 'Cloudinary did not return an image URL');
- }
- return json.secure_url;
-}
-
export const api = {
health: () => request<HealthResponse>('/health'),
@@ -154,7 +140,6 @@ export const api = {
getCloudinaryConfig: () => request<CloudinaryConfigResponse>('/cloudinary-config'),
uploadToCloudinary,
- uploadImage,
// Instagram Publishing
getIGPublishingLimit: (id: string) => request<InstagramPublishingLimitResponse>(`/accounts/${id}/ig-publishing-limit`),
@@ -166,9 +151,9 @@ export const api = {
// Overview dashboard (tracked content + per-account analytics cache)
getOverview: () => request<OverviewResponse>('/overview'),
- // Tracked Content (Reddit posts and YouTube videos)
+ // Tracked content (YouTube videos)
getTrackedContent: () => request<TrackedContentItem[]>('/tracked-content'),
- addTrackedContent: (url: string, accountId: string | null, label: string, category: string) => request<TrackedContentItem>('/tracked-content', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
+ addTrackedContent: (url: string, label: string, category: string) => request<TrackedContentItem>('/tracked-content', { method: 'POST', body: JSON.stringify({ url, label, category }) }),
updateTrackedContent: (id: string, updates: TrackedContentUpdateRequest) => request<TrackedContentItem>(`/tracked-content/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
deleteTrackedContent: (id: string) => request<SuccessResponse>(`/tracked-content/${id}`, { method: 'DELETE' }),
refreshTrackedContent: (id: string) => request<TrackedContentItem>(`/tracked-content/${id}/refresh`, { method: 'POST' }),
diff --git a/frontend/src/utils/trackedContent.ts b/frontend/src/utils/trackedContent.ts
index bf9464e..b89e20e 100644
--- a/frontend/src/utils/trackedContent.ts
+++ b/frontend/src/utils/trackedContent.ts
@@ -1,44 +1,30 @@
-// the tracked post fields these helpers read
+// the tracked video fields these helpers read
export interface TrackedMetrics {
contentType?: string;
viewCount?: number | null;
- manualViews?: number | null;
likeCount?: number | null;
commentCount?: number | null;
- score?: number;
- numComments?: number;
}
-// youtube reports views; reddit dropped view_count in 2018 so they are typed in
export function trackedViews(item: TrackedMetrics | null | undefined): number {
- if (!item) return 0;
- if (item.contentType === 'youtube') return item.viewCount ?? 0;
- return item.manualViews ?? 0;
+ return item?.viewCount ?? 0;
}
-// false for reddit posts with no views entered, so the ui can tell it from zero
+// false until YouTube has reported views, so the ui can tell it from zero
export function hasTrackedViews(item: TrackedMetrics | null | undefined): boolean {
- if (!item) return false;
- if (item.contentType === 'youtube') return item.viewCount !== undefined && item.viewCount !== null;
- return item.manualViews !== undefined && item.manualViews !== null;
+ return item?.viewCount !== undefined && item?.viewCount !== null;
}
-export function detectContentType(url: string | null | undefined): 'reddit' | 'youtube' | null {
+export function detectContentType(url: string | null | undefined): 'youtube' | null {
const lower = (url || '').toLowerCase();
- if (lower.includes('reddit.com') || lower.includes('redd.it')) return 'reddit';
if (lower.includes('youtube.com') || lower.includes('youtu.be')) return 'youtube';
return null;
}
-export function isRedditItem(item: TrackedMetrics | null | undefined): boolean {
- return (item?.contentType || 'reddit') === 'reddit';
-}
-
-// YouTube likes and Reddit karma play the same role, so lists sort and total them together
-export function trackedEngagement(item: TrackedMetrics): number {
- return item.contentType === 'youtube' ? (item.likeCount ?? 0) : (item.score ?? 0);
+export function trackedLikes(item: TrackedMetrics): number {
+ return item.likeCount ?? 0;
}
export function trackedComments(item: TrackedMetrics): number {
- return item.contentType === 'youtube' ? (item.commentCount ?? 0) : (item.numComments ?? 0);
+ return item.commentCount ?? 0;
}
diff --git a/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.ts b/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.ts
index 60c6c39..367179e 100644
--- a/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.ts
+++ b/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.ts
@@ -1,38 +1,27 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
- youtubeStatsOf, redditStatsOf, sortedByViews, sortedByKarma, chartDataOf, platformSplit, categoryDescription,
- itemsSubtitle, viewsMetric, karmaMetric, commentsSubtitle, redditViewsMetric, upvoteRatioLabel,
+ youtubeStatsOf, sortedByViews, chartDataOf, categoryDescription, shortsSubtitle,
} from '../../../../src/features/analytics/tracked/trackedCategoryStats.ts';
import type { TrackedContentItem } from '../../../../../shared/types/domain.ts';
const videos = [
{ id: 'y1', contentType: 'youtube', title: 'A very long video title here', viewCount: 2000, likeCount: 100, commentCount: 7 },
- { id: 'y2', contentType: 'youtube', url: 'https://youtu.be/x', viewCount: 1000, likeCount: 1 },
-] as TrackedContentItem[];
-const posts = [
- { id: 'r1', title: 'Post one', score: 40, numComments: 3, upvoteRatio: 0.9, manualViews: 500 },
- { id: 'r2', title: 'Post two', score: 60, numComments: 1, upvoteRatio: 0.7 },
+ { id: 'y2', contentType: 'youtube', url: 'https://youtu.be/x', viewCount: 1000, likeCount: 1, isShort: true },
] as TrackedContentItem[];
test('YouTube totals, averages and like ratio', () => {
assert.deepEqual(youtubeStatsOf(videos), {
- count: 2, views: 3000, likes: 101, comments: 7, avgViews: 1500, avgLikes: 51, avgComments: 4, likeRatio: '3.37',
+ count: 2, shorts: 1, views: 3000, likes: 101, comments: 7, avgViews: 1500, avgLikes: 51, avgComments: 4, likeRatio: '3.37',
});
assert.equal(youtubeStatsOf([]).likeRatio, '0');
assert.equal(youtubeStatsOf([]).avgViews, 0);
});
-test('Reddit totals use karma and only count entered views', () => {
- const stats = redditStatsOf(posts);
- assert.deepEqual(stats, { count: 2, karma: 100, comments: 4, views: 500, withViews: 1, avgKarma: 50, avgComments: 2, avgRatio: 0.8 });
- assert.equal(redditStatsOf([]).avgRatio, 0);
-});
-
-test('lists sort by views and karma without changing the input', () => {
- assert.deepEqual(sortedByViews([...videos].reverse()).map(item => item.id), ['y1', 'y2']);
- assert.deepEqual(sortedByKarma(posts).map(item => item.id), ['r2', 'r1']);
- assert.equal(posts[0].id, 'r1');
+test('videos sort by views without changing the input', () => {
+ const reversed = [...videos].reverse();
+ assert.deepEqual(sortedByViews(reversed).map(item => item.id), ['y1', 'y2']);
+ assert.equal(reversed[0].id, 'y2');
});
test('chart data trims names and keeps the data key', () => {
@@ -40,30 +29,11 @@ test('chart data trims names and keeps the data key', () => {
{ name: 'A very long vide', views: 2000 },
{ name: 'https://youtu.be', views: 1000 },
]);
- assert.equal(chartDataOf(Array.from({ length: 20 }, () => ({ score: 1 })) as TrackedContentItem[], 'karma', item => item.score!).length, 12);
-});
-
-test('platform parts show only for platforms with items', () => {
- assert.equal(platformSplit(1, 0, 'yt', 'rd'), 'yt');
- assert.equal(platformSplit(2, 3, 'yt', 'rd'), 'yt, rd');
- assert.equal(categoryDescription(1, 1, 0), '1 item, 1 YouTube');
- assert.equal(categoryDescription(3, 1, 2), '3 items, 1 YouTube, 2 Reddit');
-});
-
-test('overview metrics match the page wording', () => {
- const ytStats = youtubeStatsOf(videos);
- const rdStats = redditStatsOf(posts);
- assert.equal(itemsSubtitle(ytStats, rdStats), '2 YouTube videos, 2 Reddit posts');
- assert.deepEqual(viewsMetric(ytStats, rdStats), { value: '3.5K', subtitle: '3K YouTube, 500 Reddit' });
- assert.deepEqual(viewsMetric(youtubeStatsOf([]), redditStatsOf([])), { value: '-', subtitle: 'No views recorded yet' });
- assert.deepEqual(karmaMetric(rdStats), { value: '100', subtitle: '50 per post on average' });
- assert.deepEqual(karmaMetric(redditStatsOf([])), { value: '-', subtitle: 'No Reddit posts in this category' });
- assert.equal(commentsSubtitle(ytStats, redditStatsOf([])), '7 YouTube');
+ assert.equal(chartDataOf(Array.from({ length: 20 }, () => ({ viewCount: 1 })) as TrackedContentItem[], 'views', item => item.viewCount!).length, 12);
});
-test('Reddit view and ratio labels', () => {
- assert.deepEqual(redditViewsMetric(redditStatsOf(posts)), { value: '500', subtitle: 'Across 2 posts' });
- assert.deepEqual(redditViewsMetric(redditStatsOf([posts[1]])), { value: '-', subtitle: 'Reddit does not report views. Add them per post.' });
- assert.equal(upvoteRatioLabel(0.8), '80%');
- assert.equal(upvoteRatioLabel(0), '-');
+test('the category header counts videos and the first tile counts Shorts', () => {
+ assert.equal(categoryDescription(youtubeStatsOf(videos)), '2 videos');
+ assert.equal(shortsSubtitle(youtubeStatsOf(videos)), '1 Short among them');
+ assert.equal(shortsSubtitle(youtubeStatsOf([videos[0]])), 'No Shorts');
});
diff --git a/frontend/tests/features/analytics/tracked/trackedList.test.ts b/frontend/tests/features/analytics/tracked/trackedList.test.ts
index cad27fe..72050e6 100644
--- a/frontend/tests/features/analytics/tracked/trackedList.test.ts
+++ b/frontend/tests/features/analytics/tracked/trackedList.test.ts
@@ -2,15 +2,15 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
SORT_OPTIONS, filterAndSortTracked, categoriesOf, trackedStatsOf, typeChipsOf, pluralize, countLabel,
- bulkCategoryMessage, parseManualViews, imageFileError, MAX_IMAGE_BYTES, trackedSortOf,
+ bulkCategoryMessage, trackedSortOf,
} from '../../../../src/features/analytics/tracked/trackedList.ts';
import type { TrackedFilterOptions } from '../../../../src/features/analytics/tracked/trackedList.ts';
import type { TrackedContentItem } from '../../../../../shared/types/domain.ts';
const items = [
- { id: 'r1', title: 'Cat post', subreddit: 'cats', score: 50, numComments: 4, manualViews: 900, category: 'Pets', createdAt: '2030-01-02' },
+ { id: 's1', contentType: 'youtube', title: 'Cat short', channelTitle: 'Cats', likeCount: 50, commentCount: 4, viewCount: 900, isShort: true, category: 'Pets', createdAt: '2030-01-02' },
{ id: 'y1', contentType: 'youtube', title: 'Dog video', channelTitle: 'Dogs', likeCount: 10, commentCount: 9, viewCount: 100, category: 'Pets', createdAt: '2030-01-03' },
- { id: 'r2', contentType: 'reddit', title: 'Launch', score: 5, numComments: 1, category: 'Launch', createdAt: '2030-01-01' },
+ { id: 's2', contentType: 'youtube', title: 'Launch', likeCount: 5, commentCount: 1, isShort: true, category: 'Launch', createdAt: '2030-01-01' },
{ id: 'y2', contentType: 'youtube', title: 'Teaser', label: 'Campaign', likeCount: 99, commentCount: 0, viewCount: 5 },
] as unknown as TrackedContentItem[];
const allFilters: TrackedFilterOptions = { typeFilter: 'all', categoryFilter: 'all', query: '', sort: 'date-desc' };
@@ -22,27 +22,32 @@ test('sort options keep their order and labels', () => {
test('items sort by each option without changing the input', () => {
const before = ids(items);
- assert.deepEqual(ids(filterAndSortTracked(items, allFilters)), ['y1', 'r1', 'r2', 'y2']);
- assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, sort: 'engagement-desc' })), ['y2', 'r1', 'y1', 'r2']);
- assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, sort: 'comments-desc' })), ['y1', 'r1', 'r2', 'y2']);
- assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, sort: 'views-desc' })), ['r1', 'y1', 'y2', 'r2']);
+ assert.deepEqual(ids(filterAndSortTracked(items, allFilters)), ['y1', 's1', 's2', 'y2']);
+ assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, sort: 'engagement-desc' })), ['y2', 's1', 'y1', 's2']);
+ assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, sort: 'comments-desc' })), ['y1', 's1', 's2', 'y2']);
+ assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, sort: 'views-desc' })), ['s1', 'y1', 'y2', 's2']);
assert.deepEqual(ids(items), before);
});
test('type, category and text filters combine', () => {
- assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, typeFilter: 'reddit' })), ['r1', 'r2']);
- assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, categoryFilter: 'Pets' })), ['y1', 'r1']);
+ assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, typeFilter: 'short' })), ['s1', 's2']);
+ assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, typeFilter: 'video' })), ['y1', 'y2']);
+ assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, categoryFilter: 'Pets' })), ['y1', 's1']);
assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, query: 'campaign' })), ['y2']);
- assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, query: 'cats' })), ['r1']);
+ assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, query: 'cats' })), ['s1']);
+});
+
+test('a type from an old link that is no longer an option shows every video', () => {
+ assert.deepEqual(ids(filterAndSortTracked(items, { ...allFilters, typeFilter: 'youtube' })), ['y1', 's1', 's2', 'y2']);
});
test('categories are unique and sorted', () => {
assert.deepEqual(categoriesOf(items), ['Launch', 'Pets']);
});
-test('stats and chips count each platform', () => {
+test('stats and chips count videos and Shorts', () => {
const stats = trackedStatsOf(items, categoriesOf(items));
- assert.deepEqual(stats, { total: 4, categories: 2, youtube: 2, reddit: 2 });
+ assert.deepEqual(stats, { total: 4, categories: 2, videos: 2, shorts: 2 });
assert.deepEqual(typeChipsOf(stats).map(chip => chip.count), [4, 2, 2]);
});
@@ -60,31 +65,6 @@ test('the bulk category toast reports partial failures', () => {
});
});
-test('manual views accept whole numbers and clear on empty', () => {
- assert.deepEqual(parseManualViews(' '), { value: null });
- assert.deepEqual(parseManualViews(' 1200 '), { value: 1200 });
- assert.deepEqual(parseManualViews('0'), { value: 0 });
- assert.ok(parseManualViews('1.5').error);
- assert.ok(parseManualViews('-1').error);
- assert.equal(parseManualViews('abc').error, 'Enter views as a whole number, such as 1200, 1,200 or 1.2K.');
-});
-
-test('image checks run in the original order', () => {
- const image = { type: 'image/png', size: 100 };
- assert.equal(imageFileError(image, false), 'Image uploads need Cloudinary set up on the server. Check Settings.');
- assert.equal(imageFileError({ type: 'text/plain', size: 1 }, true), 'That file is not an image. Choose a PNG, JPG or WebP file.');
- assert.equal(imageFileError({ type: 'image/png', size: MAX_IMAGE_BYTES + 1 }, true), 'That image is too large. Choose one under 10MB.');
- assert.equal(imageFileError(image, true), '');
-});
-
-test('manual views accept separators and K or M suffixes as Reddit insights show them', () => {
- assert.deepEqual(parseManualViews('12,500'), { value: 12500 });
- assert.deepEqual(parseManualViews('1 234'), { value: 1234 });
- assert.deepEqual(parseManualViews('12.5k'), { value: 12500 });
- assert.deepEqual(parseManualViews('1.2M'), { value: 1200000 });
- assert.ok(parseManualViews('12.5x').error);
-});
-
test('a tracked sort from the address that is not an option falls back to newest first', () => {
assert.equal(trackedSortOf('views-desc'), 'views-desc');
assert.equal(trackedSortOf('title'), 'date-desc');
diff --git a/frontend/tests/features/analytics/tracked/viewsInput.test.ts b/frontend/tests/features/analytics/tracked/viewsInput.test.ts
deleted file mode 100644
index 30dfb07..0000000
--- a/frontend/tests/features/analytics/tracked/viewsInput.test.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-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');
-});