Skip to content

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

refactor(library): split video and Instagram explorers into modules

spacesdrive315b1899ede4
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index 89d91b4..3d6eebb 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -80,10 +80,16 @@ frontend/src/
│ │ ├── Settings.jsx <- Theme, server keys, scheduling, platform requirements, links
│ │ └── SchedulingSetupGuide.jsx <- Optional GitHub backup scheduler steps for administrators
│ ├── analytics/videos/
-│ │ ├── VideoExplorer.jsx <- YouTube video library with filtering
-│ │ └── useChannelVideos.js <- Loads every channel's videos; shared with Shorts
+│ │ ├── VideoExplorer.jsx <- Page: YouTube video library with filtering
+│ │ ├── VideoFilters.jsx, LayoutToggle.jsx, VideoListTable.jsx, VideoSortHeader.jsx, VideoGrid.jsx
+│ │ ├── useChannelVideos.js <- Loads every channel's videos; shared with Shorts
+│ │ └── videoLibrary.js <- Pure filter, sort and totals (videoLibrary.test.js)
│ ├── analytics/shorts/ShortsExplorer.jsx <- YouTube Shorts (60 seconds or less)
-│ └── analytics/reels/ReelsExplorer.jsx <- Instagram reels, posts and videos
+│ └── analytics/reels/
+│ ├── ReelsExplorer.jsx <- Page: Instagram reels, posts and videos
+│ ├── ReelsMetrics.jsx, ReelsFilters.jsx, ReelsGrid.jsx
+│ ├── useInstagramMedia.js <- Loads media from every Instagram account
+│ └── reelsLibrary.js <- Pure merge, filter, sort and totals (reelsLibrary.test.js)
```
## Metric Naming
diff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.md
index 16f6de4..9f8dd26 100644
--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md
+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md
@@ -99,9 +99,9 @@ frontend/src/
overview/ Overview.jsx - all-accounts dashboard (page; tabs, hooks and helpers beside it)
channel/ ChannelAnalytics.jsx - per-channel YouTube (page; tabs, hook and helpers beside it)
instagram/ InstagramAnalytics.jsx - per-account Instagram (page; sections and helpers beside it)
- videos/ VideoExplorer.jsx - all videos table
+ videos/ VideoExplorer.jsx - all videos table (page; filters, table, grid and helpers beside it)
shorts/ ShortsExplorer.jsx - shorts-filtered table
- reels/ ReelsExplorer.jsx - Instagram media grid
+ reels/ ReelsExplorer.jsx - Instagram media grid (page; hook, filters and helpers beside it)
reddit/ RedditAnalytics (page; sections and helpers beside it), RedditPosts, RedditPostsAll, shared post table
tracked/ TrackedContent.jsx, TrackedCategory.jsx (pages; components, hooks and helpers beside them)
publishing/
diff --git a/frontend/src/features/analytics/reels/ReelsExplorer.jsx b/frontend/src/features/analytics/reels/ReelsExplorer.jsx
index e938aec..c40556b 100644
--- a/frontend/src/features/analytics/reels/ReelsExplorer.jsx
+++ b/frontend/src/features/analytics/reels/ReelsExplorer.jsx
@@ -1,46 +1,25 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import { useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
-import { RefreshCw, Heart, MessageCircle, Eye, Clapperboard, Image, Film, Plus } from 'lucide-react';
+import { Plus, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
-import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import PageHeader from '@/components/PageHeader';
-import MetricBox from '@/components/MetricBox';
import SurfaceBox from '@/components/SurfaceBox';
-import SearchField from '@/components/SearchField';
-import FilterChips from '@/components/FilterChips';
import Pager from '@/components/Pager';
-import MediaCard, { MediaChip } from '@/components/MediaCard';
import { EmptyState } from '@/components/StateViews';
import { InstagramIcon } from '@/components/brand/platform-icons';
-import { LIKE_TIERS, filterByTier, matchesText, pageSlice } from '@/lib/library';
-import { useAppContext } from '../../../context/AppContext';
-import { api } from '../../../services/api';
-import { fmtNum, timeAgo } from '../../../utils/formatters';
-import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META, igContentTypeMeta, fmtIGViews } from '../../../utils/instagramContent';
+import { pageSlice } from '@/lib/library';
import { cn } from '@/lib/utils';
+import { useInstagramMedia } from './useInstagramMedia';
+import { filterAndSortMedia, reelsDescription, typeTotalsOf } from './reelsLibrary.js';
+import ReelsMetrics from './ReelsMetrics';
+import ReelsFilters from './ReelsFilters';
+import ReelsGrid from './ReelsGrid';
const ITEMS_PER_PAGE = 24;
-const CONTENT_TYPE_ICONS = { reel: Clapperboard, post: Image, video: Film };
-
-const SORT_OPTIONS = [
- { value: 'viewCount', label: 'Most viewed' },
- { value: 'likeCount', label: 'Most liked' },
- { value: 'commentsCount', label: 'Most comments' },
- { value: 'engagementRate', label: 'Best engagement' },
- { value: 'timestamp', label: 'Newest first' },
-];
-
-function sortValue(item, field) {
- if (field === 'timestamp') return new Date(item.timestamp).getTime() || 0;
- return item[field] ?? -1;
-}
export default function ReelsExplorer() {
- const { accounts, showToast } = useAppContext();
- const igAccounts = useMemo(() => accounts.filter(a => a.platform === 'instagram'), [accounts]);
- const [media, setMedia] = useState([]);
- const [loading, setLoading] = useState(true);
+ const { igAccounts, media, loading, loadAllMedia } = useInstagramMedia();
const [search, setSearch] = useState('');
const [accountFilter, setAccountFilter] = useState('all');
const [typeFilter, setTypeFilter] = useState('all');
@@ -48,73 +27,31 @@ export default function ReelsExplorer() {
const [sortField, setSortField] = useState('viewCount');
const [page, setPage] = useState(1);
- const loadAllMedia = useCallback(async () => {
- setLoading(true);
- try {
- const results = await Promise.allSettled(igAccounts.map(acct => api.getIGMedia(acct.id)));
- const all = [];
- results.forEach((result, i) => {
- if (result.status !== 'fulfilled') return;
- const acct = igAccounts[i];
- for (const m of result.value.media || []) {
- all.push({
- ...m,
- accountTitle: acct.title || acct.username || 'Unknown account',
- accountId: acct.id,
- engagementRate: m.viewCount > 0 ? ((m.likeCount || 0) + (m.commentsCount || 0)) / m.viewCount * 100 : null,
- });
- }
- });
- setMedia(all);
- } catch (err) {
- showToast(`Couldn't load Instagram content. ${err.message}`, 'error');
- } finally {
- setLoading(false);
- }
- }, [igAccounts, showToast]);
-
- useEffect(() => { loadAllMedia(); }, [loadAllMedia]);
-
const accountMedia = useMemo(
- () => accountFilter === 'all' ? media : media.filter(m => m.accountId === accountFilter),
+ () => accountFilter === 'all' ? media : media.filter(item => item.accountId === accountFilter),
[media, accountFilter],
);
-
- const typeTotals = useMemo(() => {
- const totals = Object.fromEntries(IG_CONTENT_TYPES.map(t => [t, { count: 0, views: 0, viewsReported: 0 }]));
- accountMedia.forEach(m => {
- const t = totals[m.contentType] ?? totals.post;
- t.count++;
- if (typeof m.viewCount === 'number') {
- t.views += m.viewCount;
- t.viewsReported++;
- }
- });
- return totals;
- }, [accountMedia]);
-
- const totalViews = IG_CONTENT_TYPES.reduce((s, t) => s + typeTotals[t].views, 0);
- const viewsReported = IG_CONTENT_TYPES.reduce((s, t) => s + typeTotals[t].viewsReported, 0);
-
- const filtered = useMemo(() => {
- let result = typeFilter === 'all' ? accountMedia : accountMedia.filter(m => m.contentType === typeFilter);
- result = result.filter(m => matchesText([m.caption], search));
- result = filterByTier(result, LIKE_TIERS, tier, 'likeCount');
- return [...result].sort((a, b) => sortValue(b, sortField) - sortValue(a, sortField));
- }, [accountMedia, typeFilter, search, tier, sortField]);
-
+ const typeTotals = useMemo(() => typeTotalsOf(accountMedia), [accountMedia]);
+ const filtered = useMemo(
+ () => filterAndSortMedia(accountMedia, { typeFilter, search, tier, sortField }),
+ [accountMedia, typeFilter, search, tier, sortField],
+ );
const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
- const resetPage = setter => value => { setter(value); setPage(1); };
- const typeChips = [
- { value: 'all', label: 'All types', count: accountMedia.length },
- ...IG_CONTENT_TYPES.map(t => ({ value: t, label: IG_CONTENT_TYPE_META[t].plural, icon: CONTENT_TYPE_ICONS[t], count: typeTotals[t].count })),
- ];
+ const resetPage = setter => value => { setter(value); setPage(1); };
+ const filters = { search, accountFilter, typeFilter, tier, sortField };
+ const handlers = {
+ onSearchChange: resetPage(setSearch),
+ onAccountChange: resetPage(setAccountFilter),
+ onTierChange: resetPage(setTier),
+ onSortChange: setSortField,
+ onTypeChange: resetPage(setTypeFilter),
+ };
const header = (
<PageHeader
title="Instagram content"
- description={loading ? 'Loading content from your accounts' : `${fmtNum(media.length)} item${media.length === 1 ? '' : 's'} across ${igAccounts.length} account${igAccounts.length === 1 ? '' : 's'}`}
+ description={reelsDescription(loading, media.length, igAccounts.length)}
actions={
<Button variant="outline" size="sm" onClick={loadAllMedia} disabled={loading}>
<RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />
@@ -159,89 +96,16 @@ export default function ReelsExplorer() {
<div className="flex flex-col gap-6">
{header}
- <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">
- <MetricBox small icon={<Eye />} label="Views" value={fmtNum(totalViews)} subtitle={`${viewsReported} of ${accountMedia.length} items report views`} highlight />
- {IG_CONTENT_TYPES.map(type => {
- const Icon = CONTENT_TYPE_ICONS[type];
- return (
- <MetricBox
- key={type}
- small
- icon={<Icon />}
- label={IG_CONTENT_TYPE_META[type].plural}
- value={fmtNum(typeTotals[type].count)}
- subtitle={typeTotals[type].viewsReported > 0 ? `${fmtNum(typeTotals[type].views)} views` : 'No views reported'}
- />
- );
- })}
- </div>
+ <ReelsMetrics typeTotals={typeTotals} itemCount={accountMedia.length} />
- <div className="flex flex-col gap-3">
- <div className="flex flex-wrap items-center gap-2">
- <SearchField value={search} onChange={resetPage(setSearch)} placeholder="Search captions" className="min-w-56 flex-1" />
- {igAccounts.length > 1 && (
- <Select
- value={accountFilter}
- onValueChange={resetPage(setAccountFilter)}
- items={[{ value: 'all', label: 'All accounts' }, ...igAccounts.map(a => ({ value: a.id, label: a.title || a.username }))]}
- >
- <SelectTrigger className="w-44" aria-label="Account"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- <SelectItem value="all">All accounts</SelectItem>
- {igAccounts.map(a => <SelectItem key={a.id} value={a.id}>{a.title || a.username}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
- )}
- <Select value={tier} onValueChange={resetPage(setTier)} items={LIKE_TIERS}>
- <SelectTrigger className="w-36" aria-label="Likes"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {LIKE_TIERS.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
- <Select value={sortField} onValueChange={setSortField} items={SORT_OPTIONS}>
- <SelectTrigger className="w-44" aria-label="Sort"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {SORT_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
- </div>
- <FilterChips label="Content type" options={typeChips} value={typeFilter} onChange={resetPage(setTypeFilter)} />
- </div>
+ <ReelsFilters igAccounts={igAccounts} itemCount={accountMedia.length} typeTotals={typeTotals} filters={filters} handlers={handlers} />
{filtered.length === 0 ? (
<SurfaceBox>
<EmptyState compact icon={<InstagramIcon />} title="No content matches" description="Clear the search or choose a different type or like range." />
</SurfaceBox>
) : (
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5">
- {paged.items.map((m, i) => {
- const meta = igContentTypeMeta(m.contentType);
- return (
- <MediaCard
- key={`${m.id}-${i}`}
- aspect="square"
- href={m.permalink}
- image={m.contentType === 'post' ? (m.thumbnailUrl || m.mediaUrl) : m.thumbnailUrl}
- title={m.caption}
- topLeft={<MediaChip>{meta.label}</MediaChip>}
- meta={
- <>
- <span className="flex items-center gap-1"><Eye />{fmtIGViews(m.viewCount)}</span>
- <span className="flex items-center gap-1"><Heart />{fmtNum(m.likeCount)}</span>
- <span className="flex items-center gap-1"><MessageCircle />{fmtNum(m.commentsCount)}</span>
- <span className="ml-auto">{timeAgo(m.timestamp)}</span>
- </>
- }
- />
- );
- })}
- </div>
+ <ReelsGrid items={paged.items} />
)}
<Pager page={paged.page} pageCount={paged.pageCount} onPageChange={setPage} total={filtered.length} shown={paged.items.length} noun="items" />
diff --git a/frontend/src/features/analytics/reels/ReelsFilters.jsx b/frontend/src/features/analytics/reels/ReelsFilters.jsx
new file mode 100644
index 0000000..b266169
--- /dev/null
+++ b/frontend/src/features/analytics/reels/ReelsFilters.jsx
@@ -0,0 +1,64 @@
+import { Clapperboard, Film, Image } from 'lucide-react';
+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+import SearchField from '@/components/SearchField';
+import FilterChips from '@/components/FilterChips';
+import { LIKE_TIERS } from '@/lib/library';
+import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';
+
+const CONTENT_TYPE_ICONS = { reel: Clapperboard, post: Image, video: Film };
+
+const SORT_OPTIONS = [
+ { value: 'viewCount', label: 'Most viewed' },
+ { value: 'likeCount', label: 'Most liked' },
+ { value: 'commentsCount', label: 'Most comments' },
+ { value: 'engagementRate', label: 'Best engagement' },
+ { value: 'timestamp', label: 'Newest first' },
+];
+
+function typeChipsOf(itemCount, typeTotals) {
+ return [
+ { value: 'all', label: 'All types', count: itemCount },
+ ...IG_CONTENT_TYPES.map(type => ({ value: type, label: IG_CONTENT_TYPE_META[type].plural, icon: CONTENT_TYPE_ICONS[type], count: typeTotals[type].count })),
+ ];
+}
+
+function OptionSelect({ value, onChange, options, className, label }) {
+ return (
+ <Select value={value} onValueChange={onChange} items={options}>
+ <SelectTrigger className={className} aria-label={label}><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {options.map(option => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ );
+}
+
+export default function ReelsFilters({ igAccounts, itemCount, typeTotals, filters, handlers }) {
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <SearchField value={filters.search} onChange={handlers.onSearchChange} placeholder="Search captions" className="min-w-56 flex-1" />
+ {igAccounts.length > 1 && (
+ <Select
+ value={filters.accountFilter}
+ onValueChange={handlers.onAccountChange}
+ items={[{ value: 'all', label: 'All accounts' }, ...igAccounts.map(account => ({ value: account.id, label: account.title || account.username }))]}
+ >
+ <SelectTrigger className="w-44" aria-label="Account"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ <SelectItem value="all">All accounts</SelectItem>
+ {igAccounts.map(account => <SelectItem key={account.id} value={account.id}>{account.title || account.username}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ )}
+ <OptionSelect value={filters.tier} onChange={handlers.onTierChange} options={LIKE_TIERS} className="w-36" label="Likes" />
+ <OptionSelect value={filters.sortField} onChange={handlers.onSortChange} options={SORT_OPTIONS} className="w-44" label="Sort" />
+ </div>
+ <FilterChips label="Content type" options={typeChipsOf(itemCount, typeTotals)} value={filters.typeFilter} onChange={handlers.onTypeChange} />
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/reels/ReelsGrid.jsx b/frontend/src/features/analytics/reels/ReelsGrid.jsx
new file mode 100644
index 0000000..fd75b4d
--- /dev/null
+++ b/frontend/src/features/analytics/reels/ReelsGrid.jsx
@@ -0,0 +1,29 @@
+import { Eye, Heart, MessageCircle } from 'lucide-react';
+import MediaCard, { MediaChip } from '@/components/MediaCard';
+import { fmtNum, timeAgo } from '../../../utils/formatters';
+import { fmtIGViews, igContentTypeMeta, igThumbnail } from '../../../utils/instagramContent';
+
+export default function ReelsGrid({ items }) {
+ return (
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5">
+ {items.map((item, i) => (
+ <MediaCard
+ key={`${item.id}-${i}`}
+ aspect="square"
+ href={item.permalink}
+ image={igThumbnail(item)}
+ title={item.caption}
+ topLeft={<MediaChip>{igContentTypeMeta(item.contentType).label}</MediaChip>}
+ meta={
+ <>
+ <span className="flex items-center gap-1"><Eye />{fmtIGViews(item.viewCount)}</span>
+ <span className="flex items-center gap-1"><Heart />{fmtNum(item.likeCount)}</span>
+ <span className="flex items-center gap-1"><MessageCircle />{fmtNum(item.commentsCount)}</span>
+ <span className="ml-auto">{timeAgo(item.timestamp)}</span>
+ </>
+ }
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/reels/ReelsMetrics.jsx b/frontend/src/features/analytics/reels/ReelsMetrics.jsx
new file mode 100644
index 0000000..bc691fc
--- /dev/null
+++ b/frontend/src/features/analytics/reels/ReelsMetrics.jsx
@@ -0,0 +1,30 @@
+import { Clapperboard, Eye, Film, Image } from 'lucide-react';
+import MetricBox from '@/components/MetricBox';
+import { fmtNum } from '../../../utils/formatters';
+import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';
+import { typeViewsSubtitle, viewTotalsOf } from './reelsLibrary.js';
+
+const CONTENT_TYPE_ICONS = { reel: Clapperboard, post: Image, video: Film };
+
+function TypeMetric({ type, typeTotal }) {
+ const Icon = CONTENT_TYPE_ICONS[type];
+ return (
+ <MetricBox
+ small
+ icon={<Icon />}
+ label={IG_CONTENT_TYPE_META[type].plural}
+ value={fmtNum(typeTotal.count)}
+ subtitle={typeViewsSubtitle(typeTotal)}
+ />
+ );
+}
+
+export default function ReelsMetrics({ typeTotals, itemCount }) {
+ const { totalViews, viewsReported } = viewTotalsOf(typeTotals);
+ return (
+ <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">
+ <MetricBox small icon={<Eye />} label="Views" value={fmtNum(totalViews)} subtitle={`${viewsReported} of ${itemCount} items report views`} highlight />
+ {IG_CONTENT_TYPES.map(type => <TypeMetric key={type} type={type} typeTotal={typeTotals[type]} />)}
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/reels/reelsLibrary.js b/frontend/src/features/analytics/reels/reelsLibrary.js
new file mode 100644
index 0000000..3d6f03f
--- /dev/null
+++ b/frontend/src/features/analytics/reels/reelsLibrary.js
@@ -0,0 +1,70 @@
+// Instagram library merging and filters; no JSX or path aliases so node --test can import it
+
+import { LIKE_TIERS, filterByTier, matchesText } from '../../../lib/library.js';
+import { fmtNum } from '../../../utils/formatters.js';
+import { IG_CONTENT_TYPES } from '../../../utils/instagramContent.js';
+
+function engagementRateOf(item) {
+ if (item.viewCount > 0) return ((item.likeCount || 0) + (item.commentsCount || 0)) / item.viewCount * 100;
+ return null;
+}
+
+// results come from Promise.allSettled, one per account; failed accounts are skipped
+export function mergeAccountMedia(igAccounts, results) {
+ const all = [];
+ results.forEach((result, i) => {
+ if (result.status !== 'fulfilled') return;
+ const account = igAccounts[i];
+ for (const item of result.value.media || []) {
+ all.push({
+ ...item,
+ accountTitle: account.title || account.username || 'Unknown account',
+ accountId: account.id,
+ engagementRate: engagementRateOf(item),
+ });
+ }
+ });
+ return all;
+}
+
+export function typeTotalsOf(media) {
+ const totals = Object.fromEntries(IG_CONTENT_TYPES.map(type => [type, { count: 0, views: 0, viewsReported: 0 }]));
+ media.forEach(item => {
+ const typeTotal = totals[item.contentType] ?? totals.post;
+ typeTotal.count++;
+ if (typeof item.viewCount === 'number') {
+ typeTotal.views += item.viewCount;
+ typeTotal.viewsReported++;
+ }
+ });
+ return totals;
+}
+
+export function viewTotalsOf(typeTotals) {
+ return {
+ totalViews: IG_CONTENT_TYPES.reduce((sum, type) => sum + typeTotals[type].views, 0),
+ viewsReported: IG_CONTENT_TYPES.reduce((sum, type) => sum + typeTotals[type].viewsReported, 0),
+ };
+}
+
+function sortValue(item, field) {
+ if (field === 'timestamp') return new Date(item.timestamp).getTime() || 0;
+ return item[field] ?? -1;
+}
+
+export function filterAndSortMedia(media, { typeFilter, search, tier, sortField }) {
+ let result = typeFilter === 'all' ? media : media.filter(item => item.contentType === typeFilter);
+ result = result.filter(item => matchesText([item.caption], search));
+ result = filterByTier(result, LIKE_TIERS, tier, 'likeCount');
+ return [...result].sort((a, b) => sortValue(b, sortField) - sortValue(a, sortField));
+}
+
+export function typeViewsSubtitle(typeTotal) {
+ if (typeTotal.viewsReported > 0) return `${fmtNum(typeTotal.views)} views`;
+ return 'No views reported';
+}
+
+export function reelsDescription(loading, itemCount, accountCount) {
+ if (loading) return 'Loading content from your accounts';
+ return `${fmtNum(itemCount)} item${itemCount === 1 ? '' : 's'} across ${accountCount} account${accountCount === 1 ? '' : 's'}`;
+}
diff --git a/frontend/src/features/analytics/reels/reelsLibrary.test.js b/frontend/src/features/analytics/reels/reelsLibrary.test.js
new file mode 100644
index 0000000..ccc012c
--- /dev/null
+++ b/frontend/src/features/analytics/reels/reelsLibrary.test.js
@@ -0,0 +1,58 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ mergeAccountMedia, typeTotalsOf, viewTotalsOf, filterAndSortMedia, typeViewsSubtitle, reelsDescription,
+} from './reelsLibrary.js';
+
+const accounts = [{ id: 'i1', title: 'Paper Fold' }, { id: 'i2', username: 'second' }, { id: 'i3' }];
+
+test('media from every fulfilled account is merged with its account', () => {
+ const results = [
+ { status: 'fulfilled', value: { media: [{ id: 'm1', viewCount: 200, likeCount: 10, commentsCount: 10 }] } },
+ { status: 'rejected', reason: new Error('token expired') },
+ { status: 'fulfilled', value: { media: [{ id: 'm2', viewCount: 0 }] } },
+ ];
+ const media = mergeAccountMedia(accounts, results);
+ assert.deepEqual(media.map(item => [item.id, item.accountId, item.accountTitle]), [
+ ['m1', 'i1', 'Paper Fold'],
+ ['m2', 'i3', 'Unknown account'],
+ ]);
+ assert.equal(media[0].engagementRate, 10);
+ assert.equal(media[1].engagementRate, null);
+ assert.deepEqual(mergeAccountMedia(accounts, [{ status: 'fulfilled', value: {} }]), []);
+});
+
+const media = [
+ { id: 'r1', contentType: 'reel', viewCount: 1000, likeCount: 50, caption: 'Folding a crane', timestamp: '2026-03-01T00:00:00Z' },
+ { id: 'p1', contentType: 'post', likeCount: 5000, caption: 'Paper stack', timestamp: '2026-05-01T00:00:00Z' },
+ { id: 'x1', contentType: 'carousel', viewCount: 10, likeCount: 2, timestamp: 'not a date' },
+];
+
+test('type totals count unknown types as posts and only reported views', () => {
+ const totals = typeTotalsOf(media);
+ assert.deepEqual(totals.reel, { count: 1, views: 1000, viewsReported: 1 });
+ assert.deepEqual(totals.post, { count: 2, views: 10, viewsReported: 1 });
+ assert.deepEqual(totals.video, { count: 0, views: 0, viewsReported: 0 });
+ assert.deepEqual(viewTotalsOf(totals), { totalViews: 1010, viewsReported: 2 });
+});
+
+test('media filters by type, caption and like range', () => {
+ const base = { typeFilter: 'all', search: '', tier: 'all', sortField: 'viewCount' };
+ assert.deepEqual(filterAndSortMedia(media, { ...base, typeFilter: 'reel' }).map(item => item.id), ['r1']);
+ assert.deepEqual(filterAndSortMedia(media, { ...base, search: 'paper' }).map(item => item.id), ['p1']);
+ assert.deepEqual(filterAndSortMedia(media, { ...base, tier: 'medium' }).map(item => item.id), ['p1']);
+});
+
+test('media sorts with missing values last', () => {
+ const base = { typeFilter: 'all', search: '', tier: 'all' };
+ assert.deepEqual(filterAndSortMedia(media, { ...base, sortField: 'viewCount' }).map(item => item.id), ['r1', 'x1', 'p1']);
+ assert.deepEqual(filterAndSortMedia(media, { ...base, sortField: 'timestamp' }).map(item => item.id), ['p1', 'r1', 'x1']);
+});
+
+test('labels', () => {
+ assert.equal(typeViewsSubtitle({ views: 1500, viewsReported: 2 }), '1.5K views');
+ assert.equal(typeViewsSubtitle({ views: 0, viewsReported: 0 }), 'No views reported');
+ assert.equal(reelsDescription(true, 5, 1), 'Loading content from your accounts');
+ assert.equal(reelsDescription(false, 1, 1), '1 item across 1 account');
+ assert.equal(reelsDescription(false, 2, 3), '2 items across 3 accounts');
+});
diff --git a/frontend/src/features/analytics/reels/useInstagramMedia.js b/frontend/src/features/analytics/reels/useInstagramMedia.js
new file mode 100644
index 0000000..ef997d7
--- /dev/null
+++ b/frontend/src/features/analytics/reels/useInstagramMedia.js
@@ -0,0 +1,28 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useAppContext } from '../../../context/AppContext';
+import { api } from '../../../services/api';
+import { mergeAccountMedia } from './reelsLibrary.js';
+
+// loads media from every Instagram account; one failed account does not hide the rest
+export function useInstagramMedia() {
+ const { accounts, showToast } = useAppContext();
+ const igAccounts = useMemo(() => accounts.filter(account => account.platform === 'instagram'), [accounts]);
+ const [media, setMedia] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ const loadAllMedia = useCallback(async () => {
+ setLoading(true);
+ try {
+ const results = await Promise.allSettled(igAccounts.map(account => api.getIGMedia(account.id)));
+ setMedia(mergeAccountMedia(igAccounts, results));
+ } catch (err) {
+ showToast(`Couldn't load Instagram content. ${err.message}`, 'error');
+ } finally {
+ setLoading(false);
+ }
+ }, [igAccounts, showToast]);
+
+ useEffect(() => { loadAllMedia(); }, [loadAllMedia]);
+
+ return { igAccounts, media, loading, loadAllMedia };
+}
diff --git a/frontend/src/features/analytics/videos/LayoutToggle.jsx b/frontend/src/features/analytics/videos/LayoutToggle.jsx
new file mode 100644
index 0000000..de7cc5e
--- /dev/null
+++ b/frontend/src/features/analytics/videos/LayoutToggle.jsx
@@ -0,0 +1,30 @@
+import { LayoutGrid, List } from 'lucide-react';
+import { cn } from '@/lib/utils';
+
+const LAYOUTS = [{ value: 'table', label: 'List', Icon: List }, { value: 'grid', label: 'Grid', Icon: LayoutGrid }];
+
+export default function LayoutToggle({ value, onChange }) {
+ return (
+ <div role="radiogroup" aria-label="Layout" className="flex h-(--control-h-lg) items-center gap-0.5 rounded-field border border-line-control p-1">
+ {LAYOUTS.map(layout => {
+ const { Icon } = layout;
+ return (
+ <button
+ key={layout.value}
+ type="button"
+ role="radio"
+ aria-checked={value === layout.value}
+ aria-label={`${layout.label} layout`}
+ onClick={() => onChange(layout.value)}
+ className={cn(
+ 'flex size-8 items-center justify-center rounded-[8px] transition-colors',
+ value === layout.value ? 'bg-surface-selected text-ink' : 'text-ink-muted hover:text-ink',
+ )}
+ >
+ <Icon className="size-4 stroke-[1.75]" />
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/videos/VideoExplorer.jsx b/frontend/src/features/analytics/videos/VideoExplorer.jsx
index cca88e3..d39b5eb 100644
--- a/frontend/src/features/analytics/videos/VideoExplorer.jsx
+++ b/frontend/src/features/analytics/videos/VideoExplorer.jsx
@@ -1,49 +1,40 @@
-import React, { useMemo, useState } from 'react';
+import { useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
-import {
- RefreshCw, List, LayoutGrid, ThumbsUp, MessageSquare, Play, Eye, PlaySquare, ArrowUp, ArrowDown, Plus,
-} from 'lucide-react';
+import { Eye, MessageSquare, Play, PlaySquare, Plus, RefreshCw, ThumbsUp } from 'lucide-react';
import { Button } from '@/components/ui/button';
-import { Badge } from '@/components/ui/badge';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
-import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import PageHeader from '@/components/PageHeader';
import MetricBox from '@/components/MetricBox';
import SurfaceBox from '@/components/SurfaceBox';
-import SearchField from '@/components/SearchField';
-import FilterChips from '@/components/FilterChips';
import Pager from '@/components/Pager';
-import MediaCard, { MediaChip } from '@/components/MediaCard';
import { EmptyState } from '@/components/StateViews';
-import { VIEW_TIERS, filterByTier, matchesText, pageSlice } from '@/lib/library';
-import { useChannelVideos } from './useChannelVideos';
-import { fmtNum, fmtDate, fmtDuration, fmtPercent, timeAgo, fmtCount } from '../../../utils/formatters';
+import { pageSlice } from '@/lib/library';
import { cn } from '@/lib/utils';
+import { fmtNum } from '../../../utils/formatters';
+import { useChannelVideos } from './useChannelVideos';
+import { filterAndSortVideos, nextSort, videoStatsOf, videosDescription } from './videoLibrary.js';
+import VideoFilters from './VideoFilters';
+import VideoListTable from './VideoListTable';
+import VideoGrid from './VideoGrid';
const ITEMS_PER_PAGE = 25;
-const watchUrl = id => `https://www.youtube.com/watch?v=${id}`;
-const LAYOUTS = [{ value: 'table', label: 'List', Icon: List }, { value: 'grid', label: 'Grid', Icon: LayoutGrid }];
-function SortHeader({ field, label, sort, onSort, align = 'left' }) {
- const active = sort.field === field;
- const Arrow = sort.order === 'asc' ? ArrowUp : ArrowDown;
- return (
- <button
- type="button"
- onClick={() => onSort(field)}
- aria-sort={active ? (sort.order === 'asc' ? 'ascending' : 'descending') : undefined}
- className={cn(
- 'inline-flex items-center gap-1 rounded-sm transition-colors hover:text-ink',
- align === 'right' && 'flex-row-reverse',
- active ? 'text-ink' : 'text-ink-muted',
- )}
- >
- {label}
- <Arrow className={cn('size-3', !active && 'invisible')} />
- </button>
- );
+function VideoResults({ filtered, paged, viewMode, sort, onSort, showChannel, onClearFilters }) {
+ if (filtered.length === 0) {
+ return (
+ <SurfaceBox>
+ <EmptyState
+ compact
+ icon={<PlaySquare />}
+ title="No videos match"
+ description="Clear the search or choose a different view range."
+ action={<Button variant="outline" size="sm" onClick={onClearFilters}>Clear filters</Button>}
+ />
+ </SurfaceBox>
+ );
+ }
+ if (viewMode === 'table') return <VideoListTable paged={paged} sort={sort} onSort={onSort} showChannel={showChannel} />;
+ return <VideoGrid items={paged.items} showChannel={showChannel} />;
}
export default function VideoExplorer() {
@@ -55,42 +46,21 @@ export default function VideoExplorer() {
const [viewMode, setViewMode] = useState('table');
const [page, setPage] = useState(1);
- const filtered = useMemo(() => {
- let result = channelFilter === 'all' ? videos : videos.filter(v => v.channelId === channelFilter);
- result = result.filter(v => matchesText([v.title, ...(v.tags || [])], search));
- result = filterByTier(result, VIEW_TIERS, tier, 'viewCount');
- const dir = sort.order === 'asc' ? 1 : -1;
- return [...result].sort((a, b) => {
- const av = a[sort.field] ?? 0;
- const bv = b[sort.field] ?? 0;
- if (typeof av === 'string' && typeof bv === 'string') return av.localeCompare(bv) * dir;
- return (Number(av) - Number(bv)) * dir;
- });
- }, [videos, channelFilter, search, tier, sort]);
-
+ const filtered = useMemo(
+ () => filterAndSortVideos(videos, { channelFilter, search, tier, sort }),
+ [videos, channelFilter, search, tier, sort],
+ );
const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
-
- const stats = useMemo(() => {
- const sum = key => filtered.reduce((s, v) => s + (v[key] || 0), 0);
- const views = sum('viewCount');
- return {
- total: filtered.length,
- views,
- likes: sum('likeCount'),
- comments: sum('commentCount'),
- avgViews: filtered.length ? Math.round(views / filtered.length) : 0,
- };
- }, [filtered]);
+ const stats = useMemo(() => videoStatsOf(filtered), [filtered]);
const resetPage = setter => value => { setter(value); setPage(1); };
- const handleSort = field => {
- setSort(prev => prev.field === field ? { field, order: prev.order === 'asc' ? 'desc' : 'asc' } : { field, order: 'desc' });
- };
+ const handleSort = field => setSort(prev => nextSort(prev, field));
+ const clearFilters = () => { setSearch(''); setTier('all'); setChannelFilter('all'); setPage(1); };
const header = (
<PageHeader
title="Videos"
- description={loading ? 'Loading videos from your channels' : `${fmtNum(videos.length)} videos across ${channels.length} channel${channels.length === 1 ? '' : 's'}`}
+ description={videosDescription(loading, videos.length, channels.length)}
actions={
<Button variant="outline" size="sm" onClick={reload} disabled={loading}>
<RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />
@@ -141,138 +111,27 @@ export default function VideoExplorer() {
<MetricBox small icon={<Eye />} label="Average views" value={fmtNum(stats.avgViews)} />
</div>
- <div className="flex flex-col gap-3">
- <div className="flex flex-wrap items-center gap-2">
- <SearchField
- value={search}
- onChange={resetPage(setSearch)}
- placeholder="Search titles and tags"
- className="min-w-56 flex-1"
- />
- {channels.length > 1 && (
- <Select
- value={channelFilter}
- onValueChange={resetPage(setChannelFilter)}
- items={[{ value: 'all', label: 'All channels' }, ...channels.map(c => ({ value: c.id, label: c.title }))]}
- >
- <SelectTrigger className="w-48" aria-label="Channel"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- <SelectItem value="all">All channels</SelectItem>
- {channels.map(c => <SelectItem key={c.id} value={c.id}>{c.title}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
- )}
- <div role="radiogroup" aria-label="Layout" className="flex h-(--control-h-lg) items-center gap-0.5 rounded-field border border-line-control p-1">
- {LAYOUTS.map(layout => {
- const { value, label, Icon } = layout;
- return (
- <button
- key={value}
- type="button"
- role="radio"
- aria-checked={viewMode === value}
- aria-label={`${label} layout`}
- onClick={() => setViewMode(value)}
- className={cn(
- 'flex size-8 items-center justify-center rounded-[8px] transition-colors',
- viewMode === value ? 'bg-surface-selected text-ink' : 'text-ink-muted hover:text-ink',
- )}
- >
- <Icon className="size-4 stroke-[1.75]" />
- </button>
- );
- })}
- </div>
- </div>
- <FilterChips label="Views" options={VIEW_TIERS} value={tier} onChange={resetPage(setTier)} />
- </div>
+ <VideoFilters
+ channels={channels}
+ search={search}
+ onSearchChange={resetPage(setSearch)}
+ channelFilter={channelFilter}
+ onChannelChange={resetPage(setChannelFilter)}
+ viewMode={viewMode}
+ onViewModeChange={setViewMode}
+ tier={tier}
+ onTierChange={resetPage(setTier)}
+ />
- {filtered.length === 0 ? (
- <SurfaceBox>
- <EmptyState
- compact
- icon={<PlaySquare />}
- title="No videos match"
- description="Clear the search or choose a different view range."
- action={<Button variant="outline" size="sm" onClick={() => { setSearch(''); setTier('all'); setChannelFilter('all'); setPage(1); }}>Clear filters</Button>}
- />
- </SurfaceBox>
- ) : viewMode === 'table' ? (
- <SurfaceBox content={false} className="overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead><SortHeader field="title" label="Video" sort={sort} onSort={handleSort} /></TableHead>
- {channels.length > 1 && <TableHead>Channel</TableHead>}
- <TableHead className="text-right"><SortHeader field="viewCount" label="Views" sort={sort} onSort={handleSort} align="right" /></TableHead>
- <TableHead className="text-right"><SortHeader field="likeCount" label="Likes" sort={sort} onSort={handleSort} align="right" /></TableHead>
- <TableHead className="text-right"><SortHeader field="commentCount" label="Comments" sort={sort} onSort={handleSort} align="right" /></TableHead>
- <TableHead className="text-right"><SortHeader field="engagementRate" label="Engagement" sort={sort} onSort={handleSort} align="right" /></TableHead>
- <TableHead className="text-right"><SortHeader field="durationSeconds" label="Length" sort={sort} onSort={handleSort} align="right" /></TableHead>
- <TableHead className="text-right"><SortHeader field="publishedAt" label="Published" sort={sort} onSort={handleSort} align="right" /></TableHead>
- <TableHead className="w-10"><span className="sr-only">Watch</span></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {paged.items.map((v, i) => (
- <TableRow key={`${v.videoId}-${i}`}>
- <TableCell className="text-right font-mono text-caption text-ink-faint">{paged.offset + i + 1}</TableCell>
- <TableCell>
- <div className="flex items-center gap-3">
- {v.thumbnail
- ? <img src={v.thumbnail} alt="" loading="lazy" className="h-9 w-16 shrink-0 rounded-sm object-cover" />
- : <span className="h-9 w-16 shrink-0 rounded-sm bg-surface-sunken" />}
- <a href={watchUrl(v.videoId)} target="_blank" rel="noopener noreferrer" className="max-w-[18rem] truncate text-sm font-medium text-ink hover:underline">
- {v.title}
- </a>
- </div>
- </TableCell>
- {channels.length > 1 && <TableCell className="max-w-36 truncate text-small text-ink-muted">{v.channelTitle}</TableCell>}
- <TableCell className="text-right font-semibold text-ink">{fmtNum(v.viewCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtCount(v.likeCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtCount(v.commentCount)}</TableCell>
- <TableCell className="text-right">
- <Badge variant={parseFloat(v.engagementRate) > 5 ? 'success' : 'secondary'}>{fmtPercent(v.engagementRate)}</Badge>
- </TableCell>
- <TableCell className="text-right text-ink-muted">{fmtDuration(v.durationSeconds)}</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{fmtDate(v.publishedAt)}</TableCell>
- <TableCell>
- <Tooltip>
- <TooltipTrigger render={<Button variant="ghost" size="icon-xs" render={<a href={watchUrl(v.videoId)} target="_blank" rel="noopener noreferrer" aria-label={`Watch ${v.title} on YouTube`} />} />}>
- <Play />
- </TooltipTrigger>
- <TooltipContent>Watch on YouTube</TooltipContent>
- </Tooltip>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </SurfaceBox>
- ) : (
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4">
- {paged.items.map((v, i) => (
- <MediaCard
- key={`${v.videoId}-${i}`}
- href={watchUrl(v.videoId)}
- image={v.thumbnail}
- title={v.title}
- topRight={<MediaChip><Eye />{fmtNum(v.viewCount)}</MediaChip>}
- bottomRight={v.durationSeconds > 0 && <MediaChip>{fmtDuration(v.durationSeconds)}</MediaChip>}
- meta={
- <>
- <span className="flex items-center gap-1"><ThumbsUp />{fmtCount(v.likeCount)}</span>
- <span className="flex items-center gap-1"><MessageSquare />{fmtCount(v.commentCount)}</span>
- <span className="ml-auto">{channels.length > 1 ? v.channelTitle : timeAgo(v.publishedAt)}</span>
- </>
- }
- />
- ))}
- </div>
- )}
+ <VideoResults
+ filtered={filtered}
+ paged={paged}
+ viewMode={viewMode}
+ sort={sort}
+ onSort={handleSort}
+ showChannel={channels.length > 1}
+ onClearFilters={clearFilters}
+ />
<Pager page={paged.page} pageCount={paged.pageCount} onPageChange={setPage} total={filtered.length} shown={paged.items.length} noun="videos" />
</div>
diff --git a/frontend/src/features/analytics/videos/VideoFilters.jsx b/frontend/src/features/analytics/videos/VideoFilters.jsx
new file mode 100644
index 0000000..234efa7
--- /dev/null
+++ b/frontend/src/features/analytics/videos/VideoFilters.jsx
@@ -0,0 +1,43 @@
+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+import SearchField from '@/components/SearchField';
+import FilterChips from '@/components/FilterChips';
+import { VIEW_TIERS } from '@/lib/library';
+import LayoutToggle from './LayoutToggle';
+
+function ChannelSelect({ channels, value, onChange }) {
+ return (
+ <Select
+ value={value}
+ onValueChange={onChange}
+ items={[{ value: 'all', label: 'All channels' }, ...channels.map(channel => ({ value: channel.id, label: channel.title }))]}
+ >
+ <SelectTrigger className="w-48" aria-label="Channel"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ <SelectItem value="all">All channels</SelectItem>
+ {channels.map(channel => <SelectItem key={channel.id} value={channel.id}>{channel.title}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ );
+}
+
+export default function VideoFilters({
+ channels, search, onSearchChange, channelFilter, onChannelChange, viewMode, onViewModeChange, tier, onTierChange,
+}) {
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <SearchField
+ value={search}
+ onChange={onSearchChange}
+ placeholder="Search titles and tags"
+ className="min-w-56 flex-1"
+ />
+ {channels.length > 1 && <ChannelSelect channels={channels} value={channelFilter} onChange={onChannelChange} />}
+ <LayoutToggle value={viewMode} onChange={onViewModeChange} />
+ </div>
+ <FilterChips label="Views" options={VIEW_TIERS} value={tier} onChange={onTierChange} />
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/videos/VideoGrid.jsx b/frontend/src/features/analytics/videos/VideoGrid.jsx
new file mode 100644
index 0000000..94e82e9
--- /dev/null
+++ b/frontend/src/features/analytics/videos/VideoGrid.jsx
@@ -0,0 +1,28 @@
+import { Eye, MessageSquare, ThumbsUp } from 'lucide-react';
+import MediaCard, { MediaChip } from '@/components/MediaCard';
+import { fmtCount, fmtDuration, fmtNum, timeAgo } from '../../../utils/formatters';
+import { watchUrl } from './videoLibrary.js';
+
+export default function VideoGrid({ items, showChannel }) {
+ return (
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4">
+ {items.map((video, i) => (
+ <MediaCard
+ key={`${video.videoId}-${i}`}
+ href={watchUrl(video.videoId)}
+ image={video.thumbnail}
+ title={video.title}
+ topRight={<MediaChip><Eye />{fmtNum(video.viewCount)}</MediaChip>}
+ bottomRight={video.durationSeconds > 0 && <MediaChip>{fmtDuration(video.durationSeconds)}</MediaChip>}
+ meta={
+ <>
+ <span className="flex items-center gap-1"><ThumbsUp />{fmtCount(video.likeCount)}</span>
+ <span className="flex items-center gap-1"><MessageSquare />{fmtCount(video.commentCount)}</span>
+ <span className="ml-auto">{showChannel ? video.channelTitle : timeAgo(video.publishedAt)}</span>
+ </>
+ }
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/videos/VideoListTable.jsx b/frontend/src/features/analytics/videos/VideoListTable.jsx
new file mode 100644
index 0000000..c3c4883
--- /dev/null
+++ b/frontend/src/features/analytics/videos/VideoListTable.jsx
@@ -0,0 +1,72 @@
+import { Play } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Badge } from '@/components/ui/badge';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import SurfaceBox from '@/components/SurfaceBox';
+import { fmtCount, fmtDate, fmtDuration, fmtNum, fmtPercent } from '../../../utils/formatters';
+import { watchUrl } from './videoLibrary.js';
+import VideoSortHeader from './VideoSortHeader';
+
+function VideoRow({ video, rank, showChannel }) {
+ return (
+ <TableRow>
+ <TableCell className="text-right font-mono text-caption text-ink-faint">{rank}</TableCell>
+ <TableCell>
+ <div className="flex items-center gap-3">
+ {video.thumbnail
+ ? <img src={video.thumbnail} alt="" loading="lazy" className="h-9 w-16 shrink-0 rounded-sm object-cover" />
+ : <span className="h-9 w-16 shrink-0 rounded-sm bg-surface-sunken" />}
+ <a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" className="max-w-[18rem] truncate text-sm font-medium text-ink hover:underline">
+ {video.title}
+ </a>
+ </div>
+ </TableCell>
+ {showChannel && <TableCell className="max-w-36 truncate text-small text-ink-muted">{video.channelTitle}</TableCell>}
+ <TableCell className="text-right font-semibold text-ink">{fmtNum(video.viewCount)}</TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtCount(video.likeCount)}</TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtCount(video.commentCount)}</TableCell>
+ <TableCell className="text-right">
+ <Badge variant={parseFloat(video.engagementRate) > 5 ? 'success' : 'secondary'}>{fmtPercent(video.engagementRate)}</Badge>
+ </TableCell>
+ <TableCell className="text-right text-ink-muted">{fmtDuration(video.durationSeconds)}</TableCell>
+ <TableCell className="text-right text-small text-ink-faint">{fmtDate(video.publishedAt)}</TableCell>
+ <TableCell>
+ <Tooltip>
+ <TooltipTrigger render={<Button variant="ghost" size="icon-xs" render={<a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" aria-label={`Watch ${video.title} on YouTube`} />} />}>
+ <Play />
+ </TooltipTrigger>
+ <TooltipContent>Watch on YouTube</TooltipContent>
+ </Tooltip>
+ </TableCell>
+ </TableRow>
+ );
+}
+
+export default function VideoListTable({ paged, sort, onSort, showChannel }) {
+ return (
+ <SurfaceBox content={false} className="overflow-hidden">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-10 text-right">#</TableHead>
+ <TableHead><VideoSortHeader field="title" label="Video" sort={sort} onSort={onSort} /></TableHead>
+ {showChannel && <TableHead>Channel</TableHead>}
+ <TableHead className="text-right"><VideoSortHeader field="viewCount" label="Views" sort={sort} onSort={onSort} align="right" /></TableHead>
+ <TableHead className="text-right"><VideoSortHeader field="likeCount" label="Likes" sort={sort} onSort={onSort} align="right" /></TableHead>
+ <TableHead className="text-right"><VideoSortHeader field="commentCount" label="Comments" sort={sort} onSort={onSort} align="right" /></TableHead>
+ <TableHead className="text-right"><VideoSortHeader field="engagementRate" label="Engagement" sort={sort} onSort={onSort} align="right" /></TableHead>
+ <TableHead className="text-right"><VideoSortHeader field="durationSeconds" label="Length" sort={sort} onSort={onSort} align="right" /></TableHead>
+ <TableHead className="text-right"><VideoSortHeader field="publishedAt" label="Published" sort={sort} onSort={onSort} align="right" /></TableHead>
+ <TableHead className="w-10"><span className="sr-only">Watch</span></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {paged.items.map((video, i) => (
+ <VideoRow key={`${video.videoId}-${i}`} video={video} rank={paged.offset + i + 1} showChannel={showChannel} />
+ ))}
+ </TableBody>
+ </Table>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/analytics/videos/VideoSortHeader.jsx b/frontend/src/features/analytics/videos/VideoSortHeader.jsx
new file mode 100644
index 0000000..39fe10f
--- /dev/null
+++ b/frontend/src/features/analytics/videos/VideoSortHeader.jsx
@@ -0,0 +1,23 @@
+import { ArrowDown, ArrowUp } from 'lucide-react';
+import { cn } from '@/lib/utils';
+import { ariaSortOf } from './videoLibrary.js';
+
+export default function VideoSortHeader({ field, label, sort, onSort, align = 'left' }) {
+ const active = sort.field === field;
+ const Arrow = sort.order === 'asc' ? ArrowUp : ArrowDown;
+ return (
+ <button
+ type="button"
+ onClick={() => onSort(field)}
+ aria-sort={ariaSortOf(sort, field)}
+ className={cn(
+ 'inline-flex items-center gap-1 rounded-sm transition-colors hover:text-ink',
+ align === 'right' && 'flex-row-reverse',
+ active ? 'text-ink' : 'text-ink-muted',
+ )}
+ >
+ {label}
+ <Arrow className={cn('size-3', !active && 'invisible')} />
+ </button>
+ );
+}
diff --git a/frontend/src/features/analytics/videos/videoLibrary.js b/frontend/src/features/analytics/videos/videoLibrary.js
new file mode 100644
index 0000000..4ce0bdd
--- /dev/null
+++ b/frontend/src/features/analytics/videos/videoLibrary.js
@@ -0,0 +1,53 @@
+// video library filters and totals; no JSX or path aliases so node --test can import it
+
+import { VIEW_TIERS, filterByTier, matchesText } from '../../../lib/library.js';
+import { fmtNum } from '../../../utils/formatters.js';
+
+export function watchUrl(videoId) {
+ return `https://www.youtube.com/watch?v=${videoId}`;
+}
+
+// engagement rates are strings, so they compare as text rather than as numbers
+function compareField(a, b, field) {
+ const aValue = a[field] ?? 0;
+ const bValue = b[field] ?? 0;
+ if (typeof aValue === 'string' && typeof bValue === 'string') return aValue.localeCompare(bValue);
+ return Number(aValue) - Number(bValue);
+}
+
+export function filterAndSortVideos(videos, { channelFilter, search, tier, sort }) {
+ let result = channelFilter === 'all' ? videos : videos.filter(video => video.channelId === channelFilter);
+ result = result.filter(video => matchesText([video.title, ...(video.tags || [])], search));
+ result = filterByTier(result, VIEW_TIERS, tier, 'viewCount');
+ const direction = sort.order === 'asc' ? 1 : -1;
+ return [...result].sort((a, b) => compareField(a, b, sort.field) * direction);
+}
+
+export function videoStatsOf(videos) {
+ const sum = key => videos.reduce((total, video) => total + (video[key] || 0), 0);
+ const views = sum('viewCount');
+ return {
+ total: videos.length,
+ views,
+ likes: sum('likeCount'),
+ comments: sum('commentCount'),
+ avgViews: videos.length ? Math.round(views / videos.length) : 0,
+ };
+}
+
+// a new column starts descending; the same column flips direction
+export function nextSort(previous, field) {
+ if (previous.field !== field) return { field, order: 'desc' };
+ return { field, order: previous.order === 'asc' ? 'desc' : 'asc' };
+}
+
+export function ariaSortOf(sort, field) {
+ if (sort.field !== field) return undefined;
+ if (sort.order === 'asc') return 'ascending';
+ return 'descending';
+}
+
+export function videosDescription(loading, videoCount, channelCount) {
+ if (loading) return 'Loading videos from your channels';
+ return `${fmtNum(videoCount)} videos across ${channelCount} channel${channelCount === 1 ? '' : 's'}`;
+}
diff --git a/frontend/src/features/analytics/videos/videoLibrary.test.js b/frontend/src/features/analytics/videos/videoLibrary.test.js
new file mode 100644
index 0000000..92b52a2
--- /dev/null
+++ b/frontend/src/features/analytics/videos/videoLibrary.test.js
@@ -0,0 +1,52 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { watchUrl, filterAndSortVideos, videoStatsOf, nextSort, ariaSortOf, videosDescription } from './videoLibrary.js';
+
+const videos = [
+ { videoId: 'a', title: 'Banana bread', channelId: 'c1', viewCount: 500, likeCount: 10, commentCount: 1, tags: ['baking'] },
+ { videoId: 'b', title: 'Apple pie', channelId: 'c2', viewCount: 50000, likeCount: 900, commentCount: 40 },
+ { videoId: 'c', title: 'Cherry tart', channelId: 'c1', viewCount: 2000000 },
+];
+const allFilters = { channelFilter: 'all', search: '', tier: 'all', sort: { field: 'viewCount', order: 'desc' } };
+const ids = list => list.map(video => video.videoId);
+
+test('videos sort by number in either direction', () => {
+ assert.deepEqual(ids(filterAndSortVideos(videos, allFilters)), ['c', 'b', 'a']);
+ assert.deepEqual(ids(filterAndSortVideos(videos, { ...allFilters, sort: { field: 'viewCount', order: 'asc' } })), ['a', 'b', 'c']);
+ assert.deepEqual(ids(filterAndSortVideos(videos, { ...allFilters, sort: { field: 'likeCount', order: 'desc' } })), ['b', 'a', 'c']);
+});
+
+test('titles sort alphabetically', () => {
+ assert.deepEqual(ids(filterAndSortVideos(videos, { ...allFilters, sort: { field: 'title', order: 'asc' } })), ['b', 'a', 'c']);
+});
+
+test('channel, search and view range narrow the list', () => {
+ assert.deepEqual(ids(filterAndSortVideos(videos, { ...allFilters, channelFilter: 'c1' })), ['c', 'a']);
+ assert.deepEqual(ids(filterAndSortVideos(videos, { ...allFilters, search: 'BAKING' })), ['a']);
+ assert.deepEqual(ids(filterAndSortVideos(videos, { ...allFilters, tier: 'viral' })), ['c']);
+ assert.equal(videos[0].videoId, 'a');
+});
+
+test('stats total the filtered videos', () => {
+ assert.deepEqual(videoStatsOf(videos), { total: 3, views: 2050500, likes: 910, comments: 41, avgViews: 683500 });
+ assert.deepEqual(videoStatsOf([]), { total: 0, views: 0, likes: 0, comments: 0, avgViews: 0 });
+});
+
+test('sorting a new column starts descending and the same column flips', () => {
+ assert.deepEqual(nextSort({ field: 'viewCount', order: 'desc' }, 'title'), { field: 'title', order: 'desc' });
+ assert.deepEqual(nextSort({ field: 'title', order: 'desc' }, 'title'), { field: 'title', order: 'asc' });
+ assert.deepEqual(nextSort({ field: 'title', order: 'asc' }, 'title'), { field: 'title', order: 'desc' });
+});
+
+test('aria sort is set only on the active column', () => {
+ assert.equal(ariaSortOf({ field: 'title', order: 'asc' }, 'title'), 'ascending');
+ assert.equal(ariaSortOf({ field: 'title', order: 'desc' }, 'title'), 'descending');
+ assert.equal(ariaSortOf({ field: 'title', order: 'desc' }, 'viewCount'), undefined);
+});
+
+test('description and watch links', () => {
+ assert.equal(videosDescription(true, 10, 2), 'Loading videos from your channels');
+ assert.equal(videosDescription(false, 1500, 1), '1.5K videos across 1 channel');
+ assert.equal(videosDescription(false, 3, 2), '3 videos across 2 channels');
+ assert.equal(watchUrl('xyz'), 'https://www.youtube.com/watch?v=xyz');
+});