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(ts): type the Overview, channel and video library pages

spacesdrive37be6d219af7
diff --git a/frontend/src/features/analytics/channel/ChannelContentTab.tsx b/frontend/src/features/analytics/channel/ChannelContentTab.tsx
index d4153bf..ab843db 100644
--- a/frontend/src/features/analytics/channel/ChannelContentTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelContentTab.tsx
@@ -5,8 +5,13 @@ import ChartPanel from '@/components/ChartPanel';
import { SERIES, axisProps, axisTick, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
import { fmtPercent } from '../../../utils/formatters';
import { categoryDataOf, durationDataOf, viewRangeDataOf } from './channelChartData.ts';
+import type { VideoAnalytics } from '@shared/types/youtube.ts';
-export default function ChannelContentTab({ analytics }) {
+export interface ChannelContentTabProps {
+ analytics: VideoAnalytics;
+}
+
+export default function ChannelContentTab({ analytics }: ChannelContentTabProps) {
const durationData = durationDataOf(analytics.durationDistribution);
const categoryData = categoryDataOf(analytics.categoryDistribution);
return (
diff --git a/frontend/src/features/analytics/channel/ChannelEngagementTab.tsx b/frontend/src/features/analytics/channel/ChannelEngagementTab.tsx
index 896c829..a455841 100644
--- a/frontend/src/features/analytics/channel/ChannelEngagementTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelEngagementTab.tsx
@@ -7,8 +7,13 @@ import { fmtNum, fmtPercent } from '../../../utils/formatters';
import { likesPerComment, rateOf } from './channelChartData.ts';
import ChannelVideoTable from './ChannelVideoTable';
import TrendArea from './TrendArea';
+import type { VideoAnalytics } from '@shared/types/youtube.ts';
-export default function ChannelEngagementTab({ analytics }) {
+export interface ChannelEngagementTabProps {
+ analytics: VideoAnalytics;
+}
+
+export default function ChannelEngagementTab({ analytics }: ChannelEngagementTabProps) {
return (
<>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
diff --git a/frontend/src/features/analytics/channel/ChannelGrowthTab.tsx b/frontend/src/features/analytics/channel/ChannelGrowthTab.tsx
index d45fa21..a9daf1a 100644
--- a/frontend/src/features/analytics/channel/ChannelGrowthTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelGrowthTab.tsx
@@ -7,8 +7,15 @@ import { fmtNum } from '../../../utils/formatters';
import { uploadsByMonthOf } from './channelChartData.ts';
import MetricGrid from './MetricGrid';
import TrendArea from './TrendArea';
+import type { VideoAnalytics } from '@shared/types/youtube.ts';
+import type { ChannelDetails } from './channelChartData.ts';
-export default function ChannelGrowthTab({ channel, analytics }) {
+export interface ChannelGrowthTabProps {
+ channel: ChannelDetails;
+ analytics: VideoAnalytics;
+}
+
+export default function ChannelGrowthTab({ channel, analytics }: ChannelGrowthTabProps) {
return (
<>
<MetricGrid>
diff --git a/frontend/src/features/analytics/channel/ChannelHeader.tsx b/frontend/src/features/analytics/channel/ChannelHeader.tsx
index 32a8a2f..6f8b99a 100644
--- a/frontend/src/features/analytics/channel/ChannelHeader.tsx
+++ b/frontend/src/features/analytics/channel/ChannelHeader.tsx
@@ -3,9 +3,19 @@ import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import PageHeader from '@/components/PageHeader';
import { AccountAvatar } from '@/components/platform';
+import type { PageHeaderBack } from '@/components/PageHeader';
+import type { AppAccount } from '../../../utils/formatters';
import { channelMeta } from './channelChartData.ts';
+import type { ChannelDetails } from './channelChartData.ts';
-export default function ChannelHeader({ account, channel, back, onRefresh }) {
+export interface ChannelHeaderProps {
+ account: AppAccount | undefined;
+ channel: ChannelDetails;
+ back: PageHeaderBack;
+ onRefresh: () => void;
+}
+
+export default function ChannelHeader({ account, channel, back, onRefresh }: ChannelHeaderProps) {
return (
<PageHeader
back={back}
diff --git a/frontend/src/features/analytics/channel/ChannelNoVideos.tsx b/frontend/src/features/analytics/channel/ChannelNoVideos.tsx
index bcf7105..24c5260 100644
--- a/frontend/src/features/analytics/channel/ChannelNoVideos.tsx
+++ b/frontend/src/features/analytics/channel/ChannelNoVideos.tsx
@@ -3,8 +3,13 @@ import MetricBox from '@/components/MetricBox';
import SurfaceBox from '@/components/SurfaceBox';
import { EmptyState } from '@/components/StateViews';
import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import type { ChannelDetails } from './channelChartData.ts';
-export default function ChannelNoVideos({ channel }) {
+export interface ChannelNoVideosProps {
+ channel: ChannelDetails;
+}
+
+export default function ChannelNoVideos({ channel }: ChannelNoVideosProps) {
return (
<>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
diff --git a/frontend/src/features/analytics/channel/ChannelOverviewTab.tsx b/frontend/src/features/analytics/channel/ChannelOverviewTab.tsx
index b6d9d80..85fc89b 100644
--- a/frontend/src/features/analytics/channel/ChannelOverviewTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelOverviewTab.tsx
@@ -7,8 +7,10 @@ import MediaCard, { MediaChip } from '@/components/MediaCard';
import { fmtNum, fmtNumFull, fmtPercent } from '../../../utils/formatters';
import { bestVideosOf, likesLabel, watchUrl } from './channelChartData.ts';
import MetricGrid from './MetricGrid';
+import type { VideoAnalytics } from '@shared/types/youtube.ts';
+import type { ChannelDetails } from './channelChartData.ts';
-function BestVideos({ analytics }) {
+function BestVideos({ analytics }: { analytics: VideoAnalytics }) {
return (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
{bestVideosOf(analytics).map(({ label, video }) => (
@@ -25,7 +27,12 @@ function BestVideos({ analytics }) {
);
}
-export default function ChannelOverviewTab({ channel, analytics }) {
+export interface ChannelOverviewTabProps {
+ channel: ChannelDetails;
+ analytics: VideoAnalytics;
+}
+
+export default function ChannelOverviewTab({ channel, analytics }: ChannelOverviewTabProps) {
return (
<>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
diff --git a/frontend/src/features/analytics/channel/ChannelPublishingTab.tsx b/frontend/src/features/analytics/channel/ChannelPublishingTab.tsx
index fa965c9..c78912e 100644
--- a/frontend/src/features/analytics/channel/ChannelPublishingTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelPublishingTab.tsx
@@ -5,8 +5,13 @@ import ChartPanel from '@/components/ChartPanel';
import { SERIES, axisProps, gridProps, tooltipCursor, tooltipStyle } from '@/lib/chart';
import { dayDataOf, hourDataOf, peakHourLabel } from './channelChartData.ts';
import MetricGrid from './MetricGrid';
+import type { VideoAnalytics } from '@shared/types/youtube.ts';
-export default function ChannelPublishingTab({ analytics }) {
+export interface ChannelPublishingTabProps {
+ analytics: VideoAnalytics;
+}
+
+export default function ChannelPublishingTab({ analytics }: ChannelPublishingTabProps) {
return (
<>
<MetricGrid>
diff --git a/frontend/src/features/analytics/channel/ChannelShortsTab.tsx b/frontend/src/features/analytics/channel/ChannelShortsTab.tsx
index 82321a8..b2785f8 100644
--- a/frontend/src/features/analytics/channel/ChannelShortsTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelShortsTab.tsx
@@ -1,3 +1,4 @@
+import type { TooltipValueType } from 'recharts';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, PieChart, Pie, Cell, Legend } from 'recharts';
import { Eye, Flame, VideoIcon } from 'lucide-react';
import MetricBox from '@/components/MetricBox';
@@ -6,12 +7,17 @@ import { SERIES, axisProps, gridProps, legendStyle, tooltipCursor, tooltipStyle
import { fmtNum, fmtNumFull } from '../../../utils/formatters';
import { shortsComparisonOf, splitDataOf } from './channelChartData.ts';
import MetricGrid from './MetricGrid';
+import type { VideoAnalytics } from '@shared/types/youtube.ts';
-function fullNumber(value) {
- return fmtNumFull(value);
+function fullNumber(value: TooltipValueType | undefined): string {
+ return fmtNumFull(value as number);
}
-export default function ChannelShortsTab({ analytics }) {
+export interface ChannelShortsTabProps {
+ analytics: VideoAnalytics;
+}
+
+export default function ChannelShortsTab({ analytics }: ChannelShortsTabProps) {
const splitData = splitDataOf(analytics);
return (
<>
diff --git a/frontend/src/features/analytics/channel/ChannelTagsTab.tsx b/frontend/src/features/analytics/channel/ChannelTagsTab.tsx
index ed7a8b8..deadabf 100644
--- a/frontend/src/features/analytics/channel/ChannelTagsTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelTagsTab.tsx
@@ -6,8 +6,13 @@ import { SERIES, axisProps, gridProps, tooltipCursor, tooltipStyle } from '@/lib
import { fmtPercent } from '../../../utils/formatters';
import MetricGrid from './MetricGrid';
import TagCloud from './TagCloud';
+import type { VideoAnalytics } from '@shared/types/youtube.ts';
-export default function ChannelTagsTab({ analytics }) {
+export interface ChannelTagsTabProps {
+ analytics: VideoAnalytics;
+}
+
+export default function ChannelTagsTab({ analytics }: ChannelTagsTabProps) {
const tags = analytics.tagFrequency || [];
return (
<>
diff --git a/frontend/src/features/analytics/channel/ChannelVideoTable.tsx b/frontend/src/features/analytics/channel/ChannelVideoTable.tsx
index 0903cb6..a4b3293 100644
--- a/frontend/src/features/analytics/channel/ChannelVideoTable.tsx
+++ b/frontend/src/features/analytics/channel/ChannelVideoTable.tsx
@@ -4,9 +4,19 @@ import { Badge } from '@/components/ui/badge';
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 type { YouTubeVideoSummary } from '@shared/types/youtube.ts';
import { watchUrl } from './channelChartData.ts';
-function VideoRow({ video, rank }) {
+interface VideoRowProps {
+ video: YouTubeVideoSummary;
+ rank: number;
+}
+
+export interface ChannelVideoTableProps {
+ videos: YouTubeVideoSummary[] | null | undefined;
+}
+
+function VideoRow({ video, rank }: VideoRowProps) {
return (
<TableRow>
<TableCell className="text-right font-mono text-caption text-ink-faint">{rank}</TableCell>
@@ -17,7 +27,7 @@ function VideoRow({ video, rank }) {
<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>
+ <Badge variant={parseFloat(video.engagementRate as string) > 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>
@@ -30,7 +40,7 @@ function VideoRow({ video, rank }) {
);
}
-export default function ChannelVideoTable({ videos }) {
+export default function ChannelVideoTable({ videos }: ChannelVideoTableProps) {
const rows = (videos || []).filter(Boolean);
return (
<SurfaceBox content={false} className="overflow-hidden">
diff --git a/frontend/src/features/analytics/channel/ChannelVideosTab.tsx b/frontend/src/features/analytics/channel/ChannelVideosTab.tsx
index 23f9a4a..6580708 100644
--- a/frontend/src/features/analytics/channel/ChannelVideosTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelVideosTab.tsx
@@ -1,15 +1,21 @@
+import type { TooltipValueType } from 'recharts';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, Legend } from 'recharts';
import ChartPanel from '@/components/ChartPanel';
import { SERIES, axisProps, axisTick, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
import { fmtNum, fmtNumFull } from '../../../utils/formatters';
import { topVideoRowsOf, topVideosChartOf } from './channelChartData.ts';
import ChannelVideoTable from './ChannelVideoTable';
+import type { VideoAnalytics } from '@shared/types/youtube.ts';
-function fullNumber(value) {
- return fmtNumFull(value);
+function fullNumber(value: TooltipValueType | undefined): string {
+ return fmtNumFull(value as number);
}
-export default function ChannelVideosTab({ analytics }) {
+export interface ChannelVideosTabProps {
+ analytics: VideoAnalytics;
+}
+
+export default function ChannelVideosTab({ analytics }: ChannelVideosTabProps) {
return (
<>
<ChartPanel title="Top 10 videos by views" height={320}>
diff --git a/frontend/src/features/analytics/channel/MetricGrid.tsx b/frontend/src/features/analytics/channel/MetricGrid.tsx
index 5e79d04..ef121a2 100644
--- a/frontend/src/features/analytics/channel/MetricGrid.tsx
+++ b/frontend/src/features/analytics/channel/MetricGrid.tsx
@@ -1,5 +1,11 @@
+import type { ReactNode } from 'react';
import { cn } from '@/lib/utils';
-export default function MetricGrid({ className, children }) {
+export interface MetricGridProps {
+ className?: string;
+ children: ReactNode;
+}
+
+export default function MetricGrid({ className, children }: MetricGridProps) {
return <div className={cn('grid grid-cols-2 gap-3 sm:grid-cols-4', className)}>{children}</div>;
}
diff --git a/frontend/src/features/analytics/channel/TagCloud.tsx b/frontend/src/features/analytics/channel/TagCloud.tsx
index 07ef17e..4b38241 100644
--- a/frontend/src/features/analytics/channel/TagCloud.tsx
+++ b/frontend/src/features/analytics/channel/TagCloud.tsx
@@ -1,7 +1,12 @@
import { Badge } from '@/components/ui/badge';
import SurfaceBox from '@/components/SurfaceBox';
+import type { YouTubeTagCount } from '@shared/types/youtube.ts';
-export default function TagCloud({ tags }) {
+export interface TagCloudProps {
+ tags: YouTubeTagCount[];
+}
+
+export default function TagCloud({ tags }: TagCloudProps) {
return (
<SurfaceBox title="Most used tags">
{tags.length === 0 ? (
diff --git a/frontend/src/features/analytics/channel/TrendArea.tsx b/frontend/src/features/analytics/channel/TrendArea.tsx
index 2b00587..4903c60 100644
--- a/frontend/src/features/analytics/channel/TrendArea.tsx
+++ b/frontend/src/features/analytics/channel/TrendArea.tsx
@@ -1,16 +1,27 @@
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip } from 'recharts';
+import type { TooltipValueType } from 'recharts';
import { axisProps, gridProps, tooltipStyle } from '@/lib/chart';
import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import type { YouTubeMonthlyRate, YouTubeMonthlyViews } from '@shared/types/youtube.ts';
-function percentTick(value) {
+export interface TrendAreaProps {
+ data: (YouTubeMonthlyViews | YouTubeMonthlyRate)[];
+ dataKey?: string;
+ color: string;
+ name: string;
+ percent?: boolean;
+ gradientId: string;
+}
+
+function percentTick(value: number | string): string {
return `${value}%`;
}
-function fullNumber(value) {
- return fmtNumFull(value);
+function fullNumber(value: TooltipValueType | undefined): string {
+ return fmtNumFull(value as number);
}
-export default function TrendArea({ data, dataKey = 'value', color, name, percent = false, gradientId }) {
+export default function TrendArea({ data, dataKey = 'value', color, name, percent = false, gradientId }: TrendAreaProps) {
return (
<AreaChart data={data}>
<defs>
diff --git a/frontend/src/features/analytics/channel/channelChartData.ts b/frontend/src/features/analytics/channel/channelChartData.ts
index 425d369..0087263 100644
--- a/frontend/src/features/analytics/channel/channelChartData.ts
+++ b/frontend/src/features/analytics/channel/channelChartData.ts
@@ -1,32 +1,44 @@
import { SERIES } from '../../../lib/chart.ts';
import { CATEGORY_MAP, fmtDate, fmtNum, fmtPercent } from '../../../utils/formatters.ts';
+import type {
+ VideoAnalytics, YouTubeAnalyticsPayload, YouTubeDurationDistribution, YouTubeMonthlyViews, YouTubeVideoSummary,
+ YouTubeViewsDistribution,
+} from '../../../../../shared/types/youtube.ts';
-export function watchUrl(videoId) {
+// the channel as GET /api/accounts/:id/analytics sends it: the stored account plus derived metrics
+export type ChannelDetails = YouTubeAnalyticsPayload['channel'];
+
+export interface BestVideo {
+ label: string;
+ video: YouTubeVideoSummary;
+}
+
+export function watchUrl(videoId: string): string {
return `https://www.youtube.com/watch?v=${videoId}`;
}
-export function channelMeta(channel) {
+export function channelMeta(channel: Pick<ChannelDetails, 'customUrl' | 'country' | 'channelAgeYears' | 'publishedAt'>): string[] {
return [
channel.customUrl,
channel.country && channel.country !== 'Unknown' ? channel.country : null,
`${channel.channelAgeYears} years old`,
`Since ${fmtDate(channel.publishedAt)}`,
- ].filter(Boolean);
+ ].filter(Boolean) as string[];
}
-export function dayDataOf(distribution) {
+export function dayDataOf(distribution: Record<string, number> | null | undefined) {
if (!distribution) return [];
return Object.entries(distribution).map(([day, count]) => ({ day, count }));
}
-export function hourDataOf(distribution) {
+export function hourDataOf(distribution: Record<string, number> | null | undefined) {
if (!distribution) return [];
return Object.entries(distribution)
.sort((a, b) => parseInt(a[0], 10) - parseInt(b[0], 10))
.map(([hour, count]) => ({ hour: `${hour}:00`, count }));
}
-export function durationDataOf(distribution) {
+export function durationDataOf(distribution: YouTubeDurationDistribution | null | undefined) {
if (!distribution) return [];
return [
{ name: 'Shorts (under 1m)', value: distribution.short, color: SERIES.primary },
@@ -36,19 +48,19 @@ export function durationDataOf(distribution) {
].filter(slice => slice.value > 0);
}
-export function categoryDataOf(distribution) {
+export function categoryDataOf(distribution: Record<string, number> | null | undefined) {
if (!distribution) return [];
return Object.entries(distribution).map(([catId, count]) => ({ name: CATEGORY_MAP[catId] || `Category ${catId}`, value: count }));
}
-export function splitDataOf(analytics) {
+export function splitDataOf(analytics: Pick<VideoAnalytics, 'shortsCount' | 'regularCount'>) {
return [
{ name: 'Shorts', value: analytics.shortsCount, color: SERIES.primary },
{ name: 'Regular', value: analytics.regularCount, color: SERIES.cool },
].filter(slice => slice.value > 0);
}
-export function shortsComparisonOf(analytics) {
+export function shortsComparisonOf(analytics: Pick<VideoAnalytics, 'avgShortViews' | 'avgRegularViews' | 'avgShortLikes' | 'avgRegularLikes'>) {
return [
{ metric: 'Average views', Shorts: analytics.avgShortViews, Regular: analytics.avgRegularViews },
{ metric: 'Average likes', Shorts: analytics.avgShortLikes, Regular: analytics.avgRegularLikes },
@@ -56,53 +68,53 @@ export function shortsComparisonOf(analytics) {
}
// every title gets the ellipsis, even short ones
-export function topVideosChartOf(videos) {
+export function topVideosChartOf(videos: (YouTubeVideoSummary | null)[] | null | undefined) {
return (videos || []).map(video => ({
name: `${(video?.title || '').slice(0, 28)}…`, views: video?.viewCount || 0, likes: video?.likeCount || 0,
}));
}
// most viewed and most liked overlap, so each video is listed once, by views
-export function topVideoRowsOf(analytics) {
+export function topVideoRowsOf(analytics: Partial<Pick<VideoAnalytics, 'top10ByViews' | 'top10ByLikes'>>): YouTubeVideoSummary[] {
return (analytics.top10ByViews || []).concat(analytics.top10ByLikes || [])
.filter((video, i, all) => video && all.findIndex(other => other?.videoId === video?.videoId) === i)
.sort((a, b) => (b?.viewCount || 0) - (a?.viewCount || 0));
}
-export function viewRangeDataOf(viewsDistribution) {
- return (viewsDistribution?.ranges || []).map((range, i) => ({ range, count: viewsDistribution.counts[i] || 0 }));
+export function viewRangeDataOf(viewsDistribution: YouTubeViewsDistribution | null | undefined) {
+ return (viewsDistribution?.ranges || []).map((range, i) => ({ range, count: viewsDistribution!.counts[i] || 0 }));
}
-export function uploadsByMonthOf(viewsTrend) {
+export function uploadsByMonthOf(viewsTrend: YouTubeMonthlyViews[] | null | undefined) {
return (viewsTrend || []).map(point => ({ month: point.month, uploads: point.count }));
}
-export function rateOf(part, total) {
+export function rateOf(part: number, total: number): string {
if (total > 0) return fmtPercent(part / total * 100);
return '0%';
}
-export function likesPerComment(analytics) {
+export function likesPerComment(analytics: Pick<VideoAnalytics, 'totalLikes' | 'totalComments'>): string {
if (analytics.totalComments > 0) return `${(analytics.totalLikes / analytics.totalComments).toFixed(1)}:1`;
return 'Not available';
}
// only a missing hour reads as unavailable; null still prints as an hour
-export function peakHourLabel(hour) {
+export function peakHourLabel(hour: number | null | undefined): string {
if (hour !== undefined) return `${hour}:00 UTC`;
return 'Not available';
}
-export function bestVideosOf(analytics) {
+export function bestVideosOf(analytics: Pick<VideoAnalytics, 'bestByViews' | 'bestByLikes' | 'bestByComments' | 'bestByEngagement'>): BestVideo[] {
return [
{ label: 'Most viewed', video: analytics.bestByViews },
{ label: 'Most liked', video: analytics.bestByLikes },
{ label: 'Most comments', video: analytics.bestByComments },
{ label: 'Best engagement', video: analytics.bestByEngagement },
- ].filter(({ video }) => video);
+ ].filter(({ video }) => video) as BestVideo[];
}
-export function likesLabel(likeCount) {
+export function likesLabel(likeCount: number | null | undefined): string {
if (likeCount == null) return 'likes hidden';
return `${fmtNum(likeCount)} likes`;
}
diff --git a/frontend/src/features/analytics/channel/useChannelAnalytics.ts b/frontend/src/features/analytics/channel/useChannelAnalytics.ts
index c4d2a6a..d671d1a 100644
--- a/frontend/src/features/analytics/channel/useChannelAnalytics.ts
+++ b/frontend/src/features/analytics/channel/useChannelAnalytics.ts
@@ -1,16 +1,18 @@
import { useCallback, useEffect, useState } from 'react';
import { api } from '../../../services/api';
+import type { AppContextValue } from '../../../context/AppContext';
+import type { YouTubeAnalyticsPayload } from '@shared/types/youtube.ts';
-export function useChannelAnalytics(id, showToast) {
- const [data, setData] = useState(null);
+export function useChannelAnalytics(id: string | undefined, showToast: AppContextValue['showToast']) {
+ const [data, setData] = useState<YouTubeAnalyticsPayload | null>(null);
const [loading, setLoading] = useState(true);
const loadAnalytics = useCallback(async () => {
setLoading(true);
try {
- setData(await api.getAnalytics(id));
+ setData(await api.getAnalytics(id!));
} catch (err) {
- showToast(`Couldn't load channel analytics. ${err.message}`, 'error');
+ showToast(`Couldn't load channel analytics. ${(err as Error).message}`, 'error');
} finally {
setLoading(false);
}
diff --git a/frontend/src/features/analytics/overview/AccountCell.tsx b/frontend/src/features/analytics/overview/AccountCell.tsx
index 3fd757f..53596fe 100644
--- a/frontend/src/features/analytics/overview/AccountCell.tsx
+++ b/frontend/src/features/analytics/overview/AccountCell.tsx
@@ -1,8 +1,15 @@
import { TableCell } from '@/components/ui/table';
import { AccountAvatar } from '@/components/platform';
+import type { ReactNode } from 'react';
import { accountHandle } from '@/lib/accounts';
+import type { AccountFields } from '@/lib/accounts';
-export default function AccountCell({ account, name }) {
+export interface AccountCellProps {
+ account: AccountFields;
+ name: ReactNode;
+}
+
+export default function AccountCell({ account, name }: AccountCellProps) {
return (
<TableCell>
<div className="flex items-center gap-2.5">
diff --git a/frontend/src/features/analytics/overview/AccountRankRow.tsx b/frontend/src/features/analytics/overview/AccountRankRow.tsx
index 1f09a86..992ab98 100644
--- a/frontend/src/features/analytics/overview/AccountRankRow.tsx
+++ b/frontend/src/features/analytics/overview/AccountRankRow.tsx
@@ -1,9 +1,17 @@
import { useNavigate } from 'react-router-dom';
import ListRow, { RankNumber } from '@/components/ListRow';
import { AccountAvatar } from '@/components/platform';
+import type { ReactNode } from 'react';
import { accountHandle, accountName, accountPath } from '@/lib/accounts';
+import type { AccountFields } from '@/lib/accounts';
-export default function AccountRankRow({ account, rank, trailing }) {
+export interface AccountRankRowProps {
+ account: AccountFields;
+ rank: number;
+ trailing: ReactNode;
+}
+
+export default function AccountRankRow({ account, rank, trailing }: AccountRankRowProps) {
const navigate = useNavigate();
return (
<ListRow
diff --git a/frontend/src/features/analytics/overview/AccountsTab.tsx b/frontend/src/features/analytics/overview/AccountsTab.tsx
index 9350573..f842ef0 100644
--- a/frontend/src/features/analytics/overview/AccountsTab.tsx
+++ b/frontend/src/features/analytics/overview/AccountsTab.tsx
@@ -4,11 +4,16 @@ import { RankNumber } from '@/components/ListRow';
import { PlatformBadge } from '@/components/platform';
import { accountName, platformOf } from '@/lib/accounts';
import { timeAgo } from '../../../utils/formatters';
+import type { AppAccount } from '../../../utils/formatters';
import { accountAudienceLabel, accountContentLabel } from './overviewLabels.ts';
import AccountCell from './AccountCell';
import OpenAnalytics from './OpenAnalytics';
-export default function AccountsTab({ accounts }) {
+export interface AccountsTabProps {
+ accounts: AppAccount[];
+}
+
+export default function AccountsTab({ accounts }: AccountsTabProps) {
return (
<SurfaceBox content={false} className="overflow-hidden">
<Table>
diff --git a/frontend/src/features/analytics/overview/AudienceChart.tsx b/frontend/src/features/analytics/overview/AudienceChart.tsx
index 4083f6d..091a7d8 100644
--- a/frontend/src/features/analytics/overview/AudienceChart.tsx
+++ b/frontend/src/features/analytics/overview/AudienceChart.tsx
@@ -1,15 +1,22 @@
import {
AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, ResponsiveContainer,
} from 'recharts';
+import type { DotItemDotProps, TooltipPayloadEntry, TooltipValueType } from 'recharts';
import { axisProps, gridProps, tooltipStyle } from '@/lib/chart';
import { fmtNum, fmtNumFull } from '../../../utils/formatters';
import { audienceDotColor } from './overviewCharts.ts';
+import type { AudienceLegendItem, AudiencePoint } from './overviewCharts.ts';
-function formatAudienceTooltip(value, name, props) {
- return [fmtNumFull(value), props.payload.type === 'category' ? 'Karma' : 'Audience'];
+export interface AudienceChartProps {
+ data: AudiencePoint[];
+ legend: AudienceLegendItem[];
}
-function renderAudienceDot({ cx, cy, payload, index }) {
+function formatAudienceTooltip(value: TooltipValueType | undefined, name: string | number | undefined, props: TooltipPayloadEntry): [string, string] {
+ return [fmtNumFull(value as number), props.payload.type === 'category' ? 'Karma' : 'Audience'];
+}
+
+function renderAudienceDot({ cx, cy, payload, index }: DotItemDotProps) {
return (
<circle
key={`dot-${index}`}
@@ -23,7 +30,7 @@ function renderAudienceDot({ cx, cy, payload, index }) {
);
}
-export default function AudienceChart({ data, legend }) {
+export default function AudienceChart({ data, legend }: AudienceChartProps) {
return (
<>
<ResponsiveContainer width="100%" height={260} debounce={200}>
diff --git a/frontend/src/features/analytics/overview/AudienceTab.tsx b/frontend/src/features/analytics/overview/AudienceTab.tsx
index 88db7d9..1c91691 100644
--- a/frontend/src/features/analytics/overview/AudienceTab.tsx
+++ b/frontend/src/features/analytics/overview/AudienceTab.tsx
@@ -7,8 +7,13 @@ import { platformOf } from '@/lib/accounts';
import AudienceChart from './AudienceChart';
import AccountRankRow from './AccountRankRow';
import CategoryRow from './CategoryRow';
+import type { OverviewStats } from './useOverviewStats';
-export default function AudienceTab({ stats }) {
+export interface AudienceTabProps {
+ stats: OverviewStats;
+}
+
+export default function AudienceTab({ stats }: AudienceTabProps) {
const audienceData = stats.charts.audience;
return (
<>
diff --git a/frontend/src/features/analytics/overview/CategoryRow.tsx b/frontend/src/features/analytics/overview/CategoryRow.tsx
index 3fa09b7..acf8ef7 100644
--- a/frontend/src/features/analytics/overview/CategoryRow.tsx
+++ b/frontend/src/features/analytics/overview/CategoryRow.tsx
@@ -1,9 +1,16 @@
import { useNavigate } from 'react-router-dom';
import { Tag } from 'lucide-react';
import ListRow from '@/components/ListRow';
+import type { ReactNode } from 'react';
import { categoryMeta } from './overviewLabels.ts';
+import type { CategoryStat } from './overviewTrackedStats.ts';
-export default function CategoryRow({ stat, trailing }) {
+export interface CategoryRowProps {
+ stat: CategoryStat;
+ trailing: ReactNode;
+}
+
+export default function CategoryRow({ stat, trailing }: CategoryRowProps) {
const navigate = useNavigate();
return (
<ListRow
diff --git a/frontend/src/features/analytics/overview/CommentsTab.tsx b/frontend/src/features/analytics/overview/CommentsTab.tsx
index a9b9e6c..56ffcbc 100644
--- a/frontend/src/features/analytics/overview/CommentsTab.tsx
+++ b/frontend/src/features/analytics/overview/CommentsTab.tsx
@@ -8,8 +8,13 @@ import { EmptyState } from '@/components/StateViews';
import { SERIES } from '@/lib/chart';
import { fmtNum, fmtPercent } from '../../../utils/formatters';
import { pluralWord } from './overviewLabels.ts';
+import type { OverviewStats } from './useOverviewStats';
-export default function CommentsTab({ stats }) {
+export interface CommentsTabProps {
+ stats: OverviewStats;
+}
+
+export default function CommentsTab({ stats }: CommentsTabProps) {
const { summary, charts } = stats;
const { totalComments, totalContent } = summary;
return (
diff --git a/frontend/src/features/analytics/overview/ContentTab.tsx b/frontend/src/features/analytics/overview/ContentTab.tsx
index 7f00ccb..0ac2518 100644
--- a/frontend/src/features/analytics/overview/ContentTab.tsx
+++ b/frontend/src/features/analytics/overview/ContentTab.tsx
@@ -9,14 +9,16 @@ import { IG_CONTENT_TYPES } from '../../../utils/instagramContent';
import { countLabel, igTypeSummary, topContentLabel } from './overviewLabels.ts';
import AccountRankRow from './AccountRankRow';
import CategoryRow from './CategoryRow';
+import type { OverviewStats } from './useOverviewStats';
+import type { CategoryStat } from './overviewTrackedStats.ts';
-function instagramContentSubtitle(stats) {
+function instagramContentSubtitle(stats: OverviewStats): string {
const { igTypes } = stats.cacheTotals;
if (IG_CONTENT_TYPES.some(type => igTypes[type].count > 0)) return igTypeSummary(igTypes, 'count');
return countLabel(stats.groups.instagram.length, 'account');
}
-function CategoryTrailing({ stat }) {
+function CategoryTrailing({ stat }: { stat: CategoryStat }) {
return (
<span className="flex flex-col items-end gap-0.5 text-caption">
{stat.views > 0 && <span className="font-medium text-ink">{fmtNum(stat.views)} views</span>}
@@ -25,7 +27,11 @@ function CategoryTrailing({ stat }) {
);
}
-export default function ContentTab({ stats }) {
+export interface ContentTabProps {
+ stats: OverviewStats;
+}
+
+export default function ContentTab({ stats }: ContentTabProps) {
const { groups, totals, cacheTotals, trackedStats, categoryStats } = stats;
return (
<>
diff --git a/frontend/src/features/analytics/overview/InstagramViewsTable.tsx b/frontend/src/features/analytics/overview/InstagramViewsTable.tsx
index e5c03b2..1e6c080 100644
--- a/frontend/src/features/analytics/overview/InstagramViewsTable.tsx
+++ b/frontend/src/features/analytics/overview/InstagramViewsTable.tsx
@@ -5,8 +5,21 @@ import { fmtNum } from '../../../utils/formatters';
import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';
import AccountCell from './AccountCell';
import OpenAnalytics from './OpenAnalytics';
+import type { AppAccount } from '../../../utils/formatters';
+import type { AccountCacheFields, IGAccountRow } from './overviewStats.ts';
-function InstagramViewsRow({ account, cache, isSyncing }) {
+interface InstagramViewsRowProps {
+ account: AppAccount;
+ cache: AccountCacheFields | undefined;
+ isSyncing: boolean;
+}
+
+export interface InstagramViewsTableProps {
+ rows: IGAccountRow<AppAccount>[];
+ isSyncing: boolean;
+}
+
+function InstagramViewsRow({ account, cache, isSyncing }: InstagramViewsRowProps) {
const warmed = cache?.cacheWarmed;
const pendingLabel = isSyncing ? 'Syncing' : '-';
return (
@@ -32,7 +45,7 @@ function InstagramViewsRow({ account, cache, isSyncing }) {
);
}
-export default function InstagramViewsTable({ rows, isSyncing }) {
+export default function InstagramViewsTable({ rows, isSyncing }: InstagramViewsTableProps) {
return (
<SurfaceBox title="Instagram views by content type" content={false} className="overflow-hidden">
<Table>
diff --git a/frontend/src/features/analytics/overview/LikesTab.tsx b/frontend/src/features/analytics/overview/LikesTab.tsx
index 8b8deb0..11b76dd 100644
--- a/frontend/src/features/analytics/overview/LikesTab.tsx
+++ b/frontend/src/features/analytics/overview/LikesTab.tsx
@@ -8,13 +8,18 @@ import { EmptyState } from '@/components/StateViews';
import { PLATFORM_META } from '@/lib/accounts';
import { SERIES } from '@/lib/chart';
import { fmtNum, fmtPercent } from '../../../utils/formatters';
+import type { OverviewStats } from './useOverviewStats';
-function instagramLikesSubtitle(stats) {
+function instagramLikesSubtitle(stats: OverviewStats): string {
if (stats.groups.instagram.length > 0) return `${fmtPercent(stats.summary.likeShare.instagram)} of all likes`;
return 'No Instagram accounts';
}
-export default function LikesTab({ stats }) {
+export interface LikesTabProps {
+ stats: OverviewStats;
+}
+
+export default function LikesTab({ stats }: LikesTabProps) {
const { totals, cacheTotals, trackedStats, summary, charts } = stats;
const { totalLikes } = summary;
return (
diff --git a/frontend/src/features/analytics/overview/MetricTabsList.tsx b/frontend/src/features/analytics/overview/MetricTabsList.tsx
index 7ba4ad7..5a4acc7 100644
--- a/frontend/src/features/analytics/overview/MetricTabsList.tsx
+++ b/frontend/src/features/analytics/overview/MetricTabsList.tsx
@@ -1,9 +1,16 @@
+import type { ComponentProps } from 'react';
import { TabsList, TabsTrigger } from '@/components/ui/tabs';
+import type { MetricTab } from './overviewLabels.ts';
-export default function MetricTabsList({ tabs }) {
+export interface MetricTabsListProps {
+ tabs: MetricTab[];
+}
+
+export default function MetricTabsList({ tabs }: MetricTabsListProps) {
return (
<TabsList
- variant="none"
+ // "none" is not a declared variant; cva ignores it, so the list gets no variant classes
+ variant={'none' as ComponentProps<typeof TabsList>['variant']}
aria-label="Overview metrics"
className="grid w-full grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6"
>
diff --git a/frontend/src/features/analytics/overview/OpenAnalytics.tsx b/frontend/src/features/analytics/overview/OpenAnalytics.tsx
index eb183ad..8c2a3f6 100644
--- a/frontend/src/features/analytics/overview/OpenAnalytics.tsx
+++ b/frontend/src/features/analytics/overview/OpenAnalytics.tsx
@@ -2,9 +2,16 @@ import { useNavigate } from 'react-router-dom';
import { ArrowUpRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import type { ReactNode } from 'react';
import { accountPath } from '@/lib/accounts';
+import type { AccountFields } from '@/lib/accounts';
-export default function OpenAnalytics({ account, name }) {
+export interface OpenAnalyticsProps {
+ account: AccountFields;
+ name: ReactNode;
+}
+
+export default function OpenAnalytics({ account, name }: OpenAnalyticsProps) {
const navigate = useNavigate();
return (
<Tooltip>
diff --git a/frontend/src/features/analytics/overview/OverviewHeader.tsx b/frontend/src/features/analytics/overview/OverviewHeader.tsx
index 4b3a167..d95cbdc 100644
--- a/frontend/src/features/analytics/overview/OverviewHeader.tsx
+++ b/frontend/src/features/analytics/overview/OverviewHeader.tsx
@@ -4,8 +4,17 @@ import PageHeader from '@/components/PageHeader';
import { cn } from '@/lib/utils';
import { greetingTitle } from './greeting.ts';
import { overviewDescription } from './overviewLabels.ts';
+import type { OverviewAccountFields } from './overviewStats.ts';
-export default function OverviewHeader({ accounts, email, isSyncing, loading, onRefresh }) {
+export interface OverviewHeaderProps {
+ accounts: OverviewAccountFields[];
+ email: string | null | undefined;
+ isSyncing: boolean;
+ loading: boolean;
+ onRefresh: () => void;
+}
+
+export default function OverviewHeader({ accounts, email, isSyncing, loading, onRefresh }: OverviewHeaderProps) {
return (
<PageHeader
size="display"
diff --git a/frontend/src/features/analytics/overview/ViewsTab.tsx b/frontend/src/features/analytics/overview/ViewsTab.tsx
index 60533fb..f42bdf5 100644
--- a/frontend/src/features/analytics/overview/ViewsTab.tsx
+++ b/frontend/src/features/analytics/overview/ViewsTab.tsx
@@ -7,13 +7,19 @@ import { fmtNum } from '../../../utils/formatters';
import { countLabel, igTypeSummary } from './overviewLabels.ts';
import InstagramViewsTable from './InstagramViewsTable';
import YouTubeViewsTable from './YouTubeViewsTable';
+import type { OverviewStats } from './useOverviewStats';
-function instagramViewsSubtitle(stats) {
+export interface ViewsTabProps {
+ stats: OverviewStats;
+ isSyncing: boolean;
+}
+
+function instagramViewsSubtitle(stats: OverviewStats): string {
if (stats.groups.instagram.length > 0) return igTypeSummary(stats.cacheTotals.igTypes, 'views');
return 'No Instagram accounts';
}
-export default function ViewsTab({ stats, isSyncing }) {
+export default function ViewsTab({ stats, isSyncing }: ViewsTabProps) {
const { groups, totals, cacheTotals, trackedStats, summary } = stats;
return (
<>
diff --git a/frontend/src/features/analytics/overview/YouTubeViewsTable.tsx b/frontend/src/features/analytics/overview/YouTubeViewsTable.tsx
index a8eb56f..d726a3a 100644
--- a/frontend/src/features/analytics/overview/YouTubeViewsTable.tsx
+++ b/frontend/src/features/analytics/overview/YouTubeViewsTable.tsx
@@ -4,8 +4,13 @@ import { RankNumber } from '@/components/ListRow';
import { fmtNum, fmtNumFull, timeAgo } from '../../../utils/formatters';
import AccountCell from './AccountCell';
import OpenAnalytics from './OpenAnalytics';
+import type { AppAccount } from '../../../utils/formatters';
-export default function YouTubeViewsTable({ accounts }) {
+export interface YouTubeViewsTableProps {
+ accounts: AppAccount[];
+}
+
+export default function YouTubeViewsTable({ accounts }: YouTubeViewsTableProps) {
return (
<SurfaceBox title="YouTube views by channel" content={false} className="overflow-hidden">
<Table>
diff --git a/frontend/src/features/analytics/overview/greeting.ts b/frontend/src/features/analytics/overview/greeting.ts
index fa651a3..37f6d29 100644
--- a/frontend/src/features/analytics/overview/greeting.ts
+++ b/frontend/src/features/analytics/overview/greeting.ts
@@ -1,4 +1,4 @@
-export function greeting(date = new Date()) {
+export function greeting(date: Date = new Date()): string {
const hour = date.getHours();
if (hour < 12) return 'Good morning';
if (hour < 18) return 'Good afternoon';
@@ -6,13 +6,13 @@ export function greeting(date = new Date()) {
}
// first part of the email's local name, so "[email protected]" greets "Jane"
-export function greetingName(email) {
+export function greetingName(email: string | null | undefined): string {
const firstName = (email || '').split('@')[0].split(/[._-]/)[0];
if (!firstName) return '';
return firstName[0].toUpperCase() + firstName.slice(1);
}
-export function greetingTitle(email, date = new Date()) {
+export function greetingTitle(email: string | null | undefined, date: Date = new Date()): string {
const name = greetingName(email);
if (!name) return greeting(date);
return `${greeting(date)}, ${name}`;
diff --git a/frontend/src/features/analytics/overview/overviewCharts.ts b/frontend/src/features/analytics/overview/overviewCharts.ts
index ba5ff54..b111f0f 100644
--- a/frontend/src/features/analytics/overview/overviewCharts.ts
+++ b/frontend/src/features/analytics/overview/overviewCharts.ts
@@ -1,37 +1,65 @@
import { PLATFORM_META } from '../../../lib/accounts.ts';
import { SERIES } from '../../../lib/chart.ts';
+import type { TrackedMetrics } from '../../../utils/trackedContent.ts';
+import type { Platform } from '../../../../../shared/types/domain.ts';
+import type { OverviewAccountFields } from './overviewStats.ts';
+import type { CategoryStat } from './overviewTrackedStats.ts';
+
+export type AccountGroups = Record<Platform, OverviewAccountFields[]>;
+
+export type AudiencePointType = Platform | 'category';
+
+export interface AudiencePoint {
+ name: string;
+ value: number;
+ type: AudiencePointType;
+}
+
+export interface AudienceLegendItem {
+ color: string;
+ label: string;
+}
+
+// the tracked post fields the charts read
+export interface ChartTrackedItem extends TrackedMetrics {
+ title?: string;
+ label?: string;
+ url?: string;
+}
+
+export type CategoryChartStat = Pick<CategoryStat, 'category' | 'rdKarma' | 'views' | 'ytComments' | 'rdComments'>;
export const CATEGORY_SERIES = SERIES.neutral;
const CHART_ITEMS = 12;
-function shortName(text, max) {
+function shortName(text: string, max: number): string {
return text.slice(0, max) + (text.length > max ? '…' : '');
}
-function itemName(item) {
+function itemName(item: ChartTrackedItem): string {
return (item.title || item.label || item.url || '').slice(0, 16);
}
// karma only for categories: adding views would mix reach into an audience chart
-export function audienceChartDataOf(groups, categoryStats) {
+export function audienceChartDataOf(groups: AccountGroups, categoryStats: CategoryChartStat[]): AudiencePoint[] {
return [
- ...groups.youtube.map(account => ({
+ ...groups.youtube.map((account): AudiencePoint => ({
name: shortName(account.title || '', 12),
value: account.subscriberCount || 0,
type: 'youtube',
})),
- ...groups.instagram.map(account => ({
+ ...groups.instagram.map((account): AudiencePoint => ({
name: shortName(account.title || account.username || '', 12),
value: account.followersCount || 0,
type: 'instagram',
})),
- ...groups.reddit.map(account => ({
+ ...groups.reddit.map((account): AudiencePoint => ({
name: `u/${(account.username || '')}`.slice(0, 12),
value: account.totalKarma || 0,
type: 'reddit',
})),
- ...categoryStats.map(stat => ({
+ ...categoryStats.map((stat): AudiencePoint => ({
name: shortName(stat.category, 12),
value: stat.rdKarma,
type: 'category',
@@ -39,21 +67,21 @@ export function audienceChartDataOf(groups, categoryStats) {
];
}
-export function audienceLegendOf(groups, categoryStats) {
+export function audienceLegendOf(groups: AccountGroups, categoryStats: CategoryChartStat[]): AudienceLegendItem[] {
return [
groups.youtube.length ? { color: PLATFORM_META.youtube.series, label: 'YouTube subscribers' } : null,
groups.instagram.length ? { color: PLATFORM_META.instagram.series, label: 'Instagram followers' } : null,
groups.reddit.length ? { color: PLATFORM_META.reddit.series, label: 'Reddit karma' } : null,
categoryStats.length ? { color: CATEGORY_SERIES, label: 'Category karma' } : null,
- ].filter(Boolean);
+ ].filter(Boolean) as AudienceLegendItem[];
}
-export function audienceDotColor(type) {
+export function audienceDotColor(type: AudiencePointType): string {
if (type === 'category') return CATEGORY_SERIES;
return PLATFORM_META[type]?.series;
}
-export function commentByContentOf(trackedContent) {
+export function commentByContentOf(trackedContent: ChartTrackedItem[]) {
return trackedContent
.map(item => ({
name: itemName(item),
@@ -63,7 +91,7 @@ export function commentByContentOf(trackedContent) {
.slice(0, CHART_ITEMS);
}
-export function engagementByContentOf(trackedContent) {
+export function engagementByContentOf(trackedContent: ChartTrackedItem[]) {
return trackedContent
.map(item => ({
name: itemName(item),
@@ -73,19 +101,19 @@ export function engagementByContentOf(trackedContent) {
.slice(0, CHART_ITEMS);
}
-export function categoryViewDataOf(categoryStats) {
+export function categoryViewDataOf(categoryStats: CategoryChartStat[]) {
return categoryStats
.map(stat => ({ name: stat.category.slice(0, 16), views: stat.views }))
.sort((a, b) => b.views - a.views);
}
-export function commentByCategoryOf(categoryStats) {
+export function commentByCategoryOf(categoryStats: CategoryChartStat[]) {
return categoryStats
.map(stat => ({ name: stat.category.slice(0, 16), comments: stat.ytComments + stat.rdComments }))
.sort((a, b) => b.comments - a.comments);
}
-export function karmaByAccountOf(redditAccounts) {
+export function karmaByAccountOf(redditAccounts: OverviewAccountFields[]) {
return [...redditAccounts]
.sort((a, b) => (b.postKarma || 0) - (a.postKarma || 0))
.map(account => ({ name: `u/${account.username || ''}`.slice(0, 16), karma: account.postKarma || 0 }));
diff --git a/frontend/src/features/analytics/overview/overviewLabels.ts b/frontend/src/features/analytics/overview/overviewLabels.ts
index a47fbd8..cbe0004 100644
--- a/frontend/src/features/analytics/overview/overviewLabels.ts
+++ b/frontend/src/features/analytics/overview/overviewLabels.ts
@@ -1,36 +1,61 @@
import { platformOf, platformSummary } from '../../../lib/accounts.ts';
import { fmtNum } from '../../../utils/formatters.ts';
import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent.ts';
+import type { NumberLike } from '../../../utils/formatters.ts';
+import type { AccountTotals, CacheTotals, IGTypeTotals, OverviewAccountFields } from './overviewStats.ts';
+import type { CategoryStat, TrackedStats } from './overviewTrackedStats.ts';
-export function pluralWord(count, word) {
+// the parts of useOverviewStats() the metric tabs read
+export interface MetricTabStats {
+ totals: Pick<AccountTotals, 'subscribers' | 'followers' | 'karma' | 'views' | 'videos' | 'posts'>;
+ cacheTotals: Pick<CacheTotals, 'igViews' | 'rdPosts'>;
+ trackedStats: Pick<TrackedStats, 'total'>;
+ summary: {
+ totalAudience: number;
+ totalViews: number;
+ trackedViewTotal: number;
+ totalContent: number;
+ totalComments: number;
+ totalLikes: number;
+ };
+}
+
+export interface MetricTab {
+ value: string;
+ label: string;
+ figure: string | number;
+ detail: string;
+}
+
+export function pluralWord(count: number, word: string): string {
if (count !== 1) return `${word}s`;
return word;
}
-export function countLabel(count, word) {
+export function countLabel(count: number, word: string): string {
return `${count} ${pluralWord(count, word)}`;
}
-export function overviewDescription(accounts) {
+export function overviewDescription(accounts: OverviewAccountFields[]): string {
if (accounts.length === 0) return 'Add your first account to start tracking.';
return `Tracking ${countLabel(accounts.length, 'account')}: ${platformSummary(accounts)}.`;
}
-function detailOf(parts, fallback) {
+function detailOf(parts: (string | null)[], fallback: string): string {
return parts.filter(Boolean).join(', ') || fallback;
}
-function partOf(value, suffix) {
+function partOf(value: NumberLike, suffix: string): string | null {
return value ? `${fmtNum(value)} ${suffix}` : null;
}
-export function syncDetail(isSyncing, total) {
+export function syncDetail(isSyncing: boolean, total: number): string {
if (isSyncing) return 'Syncing analytics';
if (total > 0) return 'Across all platforms';
return 'Open an analytics page to load';
}
-export function metricTabsOf(accounts, stats, isSyncing) {
+export function metricTabsOf(accounts: OverviewAccountFields[], stats: MetricTabStats, isSyncing: boolean): MetricTab[] {
const { totals, cacheTotals, trackedStats, summary } = stats;
return [
{
@@ -64,13 +89,13 @@ export function metricTabsOf(accounts, stats, isSyncing) {
];
}
-export function igTypeSummary(igTypes, field) {
+export function igTypeSummary(igTypes: Record<string, IGTypeTotals>, field: keyof IGTypeTotals): string {
return IG_CONTENT_TYPES
.map(type => `${fmtNum(igTypes[type][field])} ${IG_CONTENT_TYPE_META[type].plural.toLowerCase()}`)
.join(', ');
}
-export function categoryMeta(stat) {
+export function categoryMeta(stat: Pick<CategoryStat, 'count' | 'ytCount' | 'rdCount'>): string {
return [
countLabel(stat.count, 'item'),
stat.ytCount > 0 && `${stat.ytCount} YouTube`,
@@ -78,21 +103,21 @@ export function categoryMeta(stat) {
].filter(Boolean).join(', ');
}
-export function topContentLabel(account) {
+export function topContentLabel(account: OverviewAccountFields): string {
const platform = platformOf(account);
if (platform === 'instagram') return `${fmtNum(account.mediaCount)} items`;
if (platform === 'reddit') return `${fmtNum(account.totalKarma)} karma`;
return `${fmtNum(account.viewCount)} views`;
}
-export function accountAudienceLabel(account) {
+export function accountAudienceLabel(account: OverviewAccountFields): string {
const platform = platformOf(account);
if (platform === 'instagram') return `${fmtNum(account.followersCount)} followers`;
if (platform === 'reddit') return `${fmtNum(account.totalKarma)} karma`;
return `${fmtNum(account.subscriberCount)} subscribers`;
}
-export function accountContentLabel(account) {
+export function accountContentLabel(account: OverviewAccountFields): string {
const platform = platformOf(account);
if (platform === 'instagram') return `${fmtNum(account.mediaCount)} items`;
if (platform === 'reddit') return `${fmtNum(account.postKarma)} post karma`;
diff --git a/frontend/src/features/analytics/overview/overviewStats.ts b/frontend/src/features/analytics/overview/overviewStats.ts
index e621ac1..13be8da 100644
--- a/frontend/src/features/analytics/overview/overviewStats.ts
+++ b/frontend/src/features/analytics/overview/overviewStats.ts
@@ -1,7 +1,70 @@
import { audienceOf } from '../../../lib/accounts.ts';
import { IG_CONTENT_TYPES } from '../../../utils/instagramContent.ts';
+import type { AccountFields } from '../../../lib/accounts.ts';
+import type { InstagramContentType, InstagramContentTypeTotals } from '../../../../../shared/types/instagram.ts';
+import type { TrackedStats } from './overviewTrackedStats.ts';
-function addAccountTotals(totals, account) {
+// the account fields the overview reads; app accounts and plain api accounts both fit
+export interface OverviewAccountFields extends AccountFields {
+ mediaCount?: number;
+ viewCount?: number;
+ videoCount?: number;
+ postKarma?: number;
+ commentKarma?: number;
+}
+
+export interface OverviewAccount extends OverviewAccountFields {
+ id: string;
+}
+
+// the analytics cache fields the overview reads; each platform's summary sets only its own
+export interface AccountCacheFields {
+ cacheWarmed?: boolean;
+ syncing?: boolean;
+ totalLikes?: number;
+ totalComments?: number;
+ totalViews?: number;
+ contentTypes?: Partial<Record<InstagramContentType, Partial<InstagramContentTypeTotals>>>;
+ fetchedPosts?: number;
+ totalScore?: number;
+}
+
+export type AccountCache = Record<string, AccountCacheFields>;
+
+export interface AccountTotals {
+ subscribers: number;
+ views: number;
+ videos: number;
+ followers: number;
+ posts: number;
+ karma: number;
+ postKarma: number;
+ commentKarma: number;
+}
+
+export interface IGTypeTotals {
+ count: number;
+ views: number;
+}
+
+export interface CacheTotals {
+ ytLikes: number;
+ ytComments: number;
+ igLikes: number;
+ igComments: number;
+ igViews: number;
+ rdPosts: number;
+ rdKarma: number;
+ rdComments: number;
+ igTypes: Record<string, IGTypeTotals>;
+}
+
+export interface IGAccountRow<T> {
+ account: T;
+ cache: AccountCacheFields | undefined;
+}
+
+function addAccountTotals(totals: AccountTotals, account: OverviewAccountFields): AccountTotals {
if (account.platform === 'instagram') {
return { ...totals, followers: totals.followers + (account.followersCount || 0), posts: totals.posts + (account.mediaCount || 0) };
}
@@ -21,13 +84,13 @@ function addAccountTotals(totals, account) {
};
}
-export function accountTotalsOf(accounts) {
- return accounts.reduce(addAccountTotals, {
+export function accountTotalsOf(accounts: OverviewAccountFields[]): AccountTotals {
+ return accounts.reduce<AccountTotals>(addAccountTotals, {
subscribers: 0, views: 0, videos: 0, followers: 0, posts: 0, karma: 0, postKarma: 0, commentKarma: 0,
});
}
-function addInstagramCache(result, cache) {
+function addInstagramCache(result: CacheTotals, cache: AccountCacheFields): void {
result.igLikes += cache.totalLikes ?? 0;
result.igComments += cache.totalComments ?? 0;
result.igViews += cache.totalViews ?? 0;
@@ -38,8 +101,8 @@ function addInstagramCache(result, cache) {
}
// only accounts saved as 'youtube' count here, unlike the platform splits
-export function cacheTotalsOf(accounts, analyticsCache) {
- const result = {
+export function cacheTotalsOf(accounts: OverviewAccount[], analyticsCache: AccountCache): CacheTotals {
+ const result: CacheTotals = {
ytLikes: 0, ytComments: 0, igLikes: 0, igComments: 0, igViews: 0, rdPosts: 0, rdKarma: 0, rdComments: 0,
igTypes: Object.fromEntries(IG_CONTENT_TYPES.map(type => [type, { count: 0, views: 0 }])),
};
@@ -60,12 +123,12 @@ export function cacheTotalsOf(accounts, analyticsCache) {
return result;
}
-function shareOf(part, total) {
+function shareOf(part: number, total: number): number {
return total > 0 ? (part / total) * 100 : 0;
}
// tracked items are never the user's own, so they never overlap cache totals
-export function summaryOf(totals, cacheTotals, trackedStats) {
+export function summaryOf(totals: AccountTotals, cacheTotals: CacheTotals, trackedStats: TrackedStats) {
const totalContent = totals.videos + totals.posts + cacheTotals.rdPosts + trackedStats.total;
const trackedViewTotal = trackedStats.ytViews + trackedStats.rdViews;
const ytComments = cacheTotals.ytComments + trackedStats.ytComments;
@@ -87,26 +150,26 @@ export function summaryOf(totals, cacheTotals, trackedStats) {
};
}
-function contentOf(account) {
+function contentOf(account: OverviewAccountFields): number {
if (account.platform === 'instagram') return account.mediaCount || 0;
if (account.platform === 'reddit') return account.totalKarma || 0;
return account.viewCount || 0;
}
-export function sortedByAudience(accounts) {
+export function sortedByAudience<T extends OverviewAccountFields>(accounts: T[]): T[] {
return [...accounts].sort((a, b) => audienceOf(b) - audienceOf(a));
}
-export function sortedByContent(accounts) {
+export function sortedByContent<T extends OverviewAccountFields>(accounts: T[]): T[] {
return [...accounts].sort((a, b) => contentOf(b) - contentOf(a));
}
-export function sortedByChannelViews(ytAccounts) {
+export function sortedByChannelViews<T extends OverviewAccountFields>(ytAccounts: T[]): T[] {
return [...ytAccounts].sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0));
}
-export function igAccountRowsOf(igAccounts, analyticsCache) {
+export function igAccountRowsOf<T extends OverviewAccount>(igAccounts: T[], analyticsCache: AccountCache): IGAccountRow<T>[] {
return igAccounts
- .map(account => ({ account, cache: analyticsCache[account.id] }))
+ .map((account): IGAccountRow<T> => ({ account, cache: analyticsCache[account.id] }))
.sort((x, y) => (y.cache?.totalViews ?? 0) - (x.cache?.totalViews ?? 0));
}
diff --git a/frontend/src/features/analytics/overview/overviewTrackedStats.ts b/frontend/src/features/analytics/overview/overviewTrackedStats.ts
index 747ae5d..d94c724 100644
--- a/frontend/src/features/analytics/overview/overviewTrackedStats.ts
+++ b/frontend/src/features/analytics/overview/overviewTrackedStats.ts
@@ -1,11 +1,46 @@
import { trackedViews } from '../../../utils/trackedContent.ts';
+import type { TrackedMetrics } from '../../../utils/trackedContent.ts';
-function sumOf(items, valueOf) {
+// the tracked post fields the overview reads
+export interface TrackedStatsItem extends TrackedMetrics {
+ category?: string;
+}
+
+export interface TrackedStats<T extends TrackedStatsItem = TrackedStatsItem> {
+ total: number;
+ ytItems: T[];
+ rdItems: T[];
+ ytViews: number;
+ ytLikes: number;
+ ytComments: number;
+ rdViews: number;
+ rdKarma: number;
+ rdComments: number;
+}
+
+export interface CategoryTotals {
+ category: string;
+ count: number;
+ ytCount: number;
+ rdCount: number;
+ ytViews: number;
+ ytLikes: number;
+ ytComments: number;
+ rdViews: number;
+ rdKarma: number;
+ rdComments: number;
+}
+
+export interface CategoryStat extends CategoryTotals {
+ views: number;
+}
+
+function sumOf<T>(items: T[], valueOf: (item: T) => number): number {
return items.reduce((sum, item) => sum + valueOf(item), 0);
}
// reddit post score is karma, so it rolls into karma totals
-export function trackedStatsOf(trackedContent) {
+export function trackedStatsOf<T extends TrackedStatsItem>(trackedContent: T[]): TrackedStats<T> {
const ytItems = trackedContent.filter(item => item.contentType === 'youtube');
const rdItems = trackedContent.filter(item => (item.contentType || 'reddit') === 'reddit');
return {
@@ -21,7 +56,7 @@ export function trackedStatsOf(trackedContent) {
};
}
-function emptyCategory(category) {
+function emptyCategory(category: string): CategoryTotals {
return {
category,
count: 0, ytCount: 0, rdCount: 0,
@@ -30,7 +65,7 @@ function emptyCategory(category) {
};
}
-function addToCategory(stat, item) {
+function addToCategory(stat: CategoryTotals, item: TrackedStatsItem): void {
stat.count++;
if (item.contentType === 'youtube') {
stat.ytCount++;
@@ -45,13 +80,13 @@ function addToCategory(stat, item) {
stat.rdComments += item.numComments ?? 0;
}
-export function categoryStatsOf(trackedContent) {
+export function categoryStatsOf(trackedContent: TrackedStatsItem[]): CategoryStat[] {
const withCategory = trackedContent.filter(item => item.category);
if (!withCategory.length) return [];
- const byCategory = {};
+ const byCategory: Record<string, CategoryTotals> = {};
withCategory.forEach(item => {
- if (!byCategory[item.category]) byCategory[item.category] = emptyCategory(item.category);
- addToCategory(byCategory[item.category], item);
+ if (!byCategory[item.category!]) byCategory[item.category!] = emptyCategory(item.category!);
+ addToCategory(byCategory[item.category!], item);
});
return Object.values(byCategory)
.map(stat => ({ ...stat, views: stat.ytViews + stat.rdViews }))
diff --git a/frontend/src/features/analytics/overview/useOverviewData.ts b/frontend/src/features/analytics/overview/useOverviewData.ts
index aa131be..bd21427 100644
--- a/frontend/src/features/analytics/overview/useOverviewData.ts
+++ b/frontend/src/features/analytics/overview/useOverviewData.ts
@@ -1,20 +1,23 @@
import { useEffect, useState } from 'react';
import { api } from '../../../services/api';
+import type { OverviewResponse } from '@shared/types/domain.ts';
+import type { AccountCacheFields, OverviewAccount } from './overviewStats.ts';
const SYNC_POLL_DELAYS = [4000, 8000, 16000];
-async function fetchOverview() {
+async function fetchOverview(): Promise<OverviewResponse | null> {
try {
const data = await api.getOverview();
- return data && !data.error ? data : null;
+ // OverviewResponse has no error field; request() already throws on the route's error body
+ return data && !(data as OverviewResponse & { error?: string }).error ? data : null;
} catch {
// a failed load keeps the previous overview; the next poll or visit tries again
return null;
}
}
-export function useOverviewData(accounts) {
- const [overviewData, setOverviewData] = useState({ tracked: [], analyticsCache: {} });
+export function useOverviewData(accounts: OverviewAccount[]) {
+ const [overviewData, setOverviewData] = useState<OverviewResponse>({ tracked: [], analyticsCache: {} });
const [overviewLoading, setOverviewLoading] = useState(true);
const [syncPolls, setSyncPolls] = useState(0);
@@ -29,7 +32,7 @@ export function useOverviewData(accounts) {
// poll with backoff while syncing, then stop so the label never hangs
const isSyncing = !overviewLoading && syncPolls < SYNC_POLL_DELAYS.length && accounts.some(account => {
- return overviewData.analyticsCache[account.id]?.syncing === true;
+ return (overviewData.analyticsCache[account.id] as AccountCacheFields | undefined)?.syncing === true;
});
useEffect(() => {
diff --git a/frontend/src/features/analytics/overview/useOverviewStats.ts b/frontend/src/features/analytics/overview/useOverviewStats.ts
index 60a1424..1bcc5ec 100644
--- a/frontend/src/features/analytics/overview/useOverviewStats.ts
+++ b/frontend/src/features/analytics/overview/useOverviewStats.ts
@@ -1,5 +1,9 @@
import { useMemo } from 'react';
import { groupByPlatform } from '@/lib/accounts';
+import type { AppAccount } from '@/utils/formatters';
+import type { OverviewResponse, TrackedContentItem } from '@shared/types/domain.ts';
+import type { AccountGroups } from './overviewCharts.ts';
+import type { CategoryStat } from './overviewTrackedStats.ts';
import {
accountTotalsOf, cacheTotalsOf, igAccountRowsOf, sortedByAudience, sortedByChannelViews, sortedByContent, summaryOf,
} from './overviewStats.ts';
@@ -9,7 +13,7 @@ import {
engagementByContentOf, karmaByAccountOf,
} from './overviewCharts.ts';
-function useOverviewCharts(groups, trackedContent, categoryStats) {
+function useOverviewCharts(groups: AccountGroups, trackedContent: TrackedContentItem[], categoryStats: CategoryStat[]) {
const audience = useMemo(() => audienceChartDataOf(groups, categoryStats), [groups, categoryStats]);
const commentByContent = useMemo(() => commentByContentOf(trackedContent), [trackedContent]);
const categoryViews = useMemo(() => categoryViewDataOf(categoryStats), [categoryStats]);
@@ -19,9 +23,10 @@ function useOverviewCharts(groups, trackedContent, categoryStats) {
return { audience, commentByContent, categoryViews, commentByCategory, karmaByAccount, engagementByContent };
}
-export function useOverviewStats(accounts, overviewData) {
+export function useOverviewStats(accounts: AppAccount[], overviewData: OverviewResponse) {
// memoized so the ?? fallbacks keep their identity and the memos below cache
- const trackedContent = useMemo(() => overviewData.tracked ?? [], [overviewData.tracked]);
+ // the overview sends whole tracked rows, so the fetched fields are there
+ const trackedContent = useMemo(() => overviewData.tracked as TrackedContentItem[] ?? [], [overviewData.tracked]);
const analyticsCache = useMemo(() => overviewData.analyticsCache ?? {}, [overviewData.analyticsCache]);
const groups = useMemo(() => groupByPlatform(accounts), [accounts]);
@@ -46,3 +51,5 @@ export function useOverviewStats(accounts, overviewData) {
byChannelViews: sortedByChannelViews(groups.youtube),
};
}
+
+export type OverviewStats = ReturnType<typeof useOverviewStats>;
diff --git a/frontend/src/features/analytics/reels/ReelsExplorer.tsx b/frontend/src/features/analytics/reels/ReelsExplorer.tsx
index 323f899..1492993 100644
--- a/frontend/src/features/analytics/reels/ReelsExplorer.tsx
+++ b/frontend/src/features/analytics/reels/ReelsExplorer.tsx
@@ -12,6 +12,7 @@ import { pageSlice } from '@/lib/library';
import { cn } from '@/lib/utils';
import { useInstagramMedia } from './useInstagramMedia';
import { filterAndSortMedia, reelsDescription, typeTotalsOf } from './reelsLibrary.ts';
+import type { MediaSortField } from './reelsLibrary.ts';
import ReelsMetrics from './ReelsMetrics';
import ReelsFilters from './ReelsFilters';
import ReelsGrid from './ReelsGrid';
@@ -24,7 +25,7 @@ export default function ReelsExplorer() {
const [accountFilter, setAccountFilter] = useState('all');
const [typeFilter, setTypeFilter] = useState('all');
const [tier, setTier] = useState('all');
- const [sortField, setSortField] = useState('viewCount');
+ const [sortField, setSortField] = useState<MediaSortField>('viewCount');
const [page, setPage] = useState(1);
const accountMedia = useMemo(
@@ -38,8 +39,8 @@ export default function ReelsExplorer() {
);
const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
- function resetPage(setter) {
- return value => {
+ function resetPage<T>(setter: (value: T) => void) {
+ return (value: T) => {
setter(value);
setPage(1);
};
diff --git a/frontend/src/features/analytics/reels/ReelsFilters.tsx b/frontend/src/features/analytics/reels/ReelsFilters.tsx
index b266169..90c6b8c 100644
--- a/frontend/src/features/analytics/reels/ReelsFilters.tsx
+++ b/frontend/src/features/analytics/reels/ReelsFilters.tsx
@@ -1,13 +1,55 @@
import { Clapperboard, Film, Image } from 'lucide-react';
+import type { LucideIcon } 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 type { FilterChipOption } from '@/components/FilterChips';
import { LIKE_TIERS } from '@/lib/library';
import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';
+import type { AppAccount } from '../../../utils/formatters';
+import type { InstagramContentType } from '@shared/types/instagram.ts';
+import type { MediaSortField, MediaTypeTotals } from './reelsLibrary.ts';
-const CONTENT_TYPE_ICONS = { reel: Clapperboard, post: Image, video: Film };
+interface SelectOption<V extends string> {
+ value: V;
+ label: string;
+}
+
+interface OptionSelectProps<V extends string> {
+ value: V;
+ onChange: (value: V) => void;
+ options: SelectOption<V>[];
+ className?: string;
+ label: string;
+}
+
+export interface ReelsFilterValues {
+ search: string;
+ accountFilter: string;
+ typeFilter: string;
+ tier: string;
+ sortField: MediaSortField;
+}
+
+export interface ReelsFilterHandlers {
+ onSearchChange: (value: string) => void;
+ onAccountChange: (value: string) => void;
+ onTierChange: (value: string) => void;
+ onSortChange: (value: MediaSortField) => void;
+ onTypeChange: (value: string) => void;
+}
+
+export interface ReelsFiltersProps {
+ igAccounts: AppAccount[];
+ itemCount: number;
+ typeTotals: MediaTypeTotals;
+ filters: ReelsFilterValues;
+ handlers: ReelsFilterHandlers;
+}
+
+const CONTENT_TYPE_ICONS: Record<InstagramContentType, LucideIcon> = { reel: Clapperboard, post: Image, video: Film };
-const SORT_OPTIONS = [
+const SORT_OPTIONS: SelectOption<MediaSortField>[] = [
{ value: 'viewCount', label: 'Most viewed' },
{ value: 'likeCount', label: 'Most liked' },
{ value: 'commentsCount', label: 'Most comments' },
@@ -15,16 +57,16 @@ const SORT_OPTIONS = [
{ value: 'timestamp', label: 'Newest first' },
];
-function typeChipsOf(itemCount, typeTotals) {
+function typeChipsOf(itemCount: number, typeTotals: MediaTypeTotals): FilterChipOption[] {
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 }) {
+function OptionSelect<V extends string>({ value, onChange, options, className, label }: OptionSelectProps<V>) {
return (
- <Select value={value} onValueChange={onChange} items={options}>
+ <Select value={value} onValueChange={onChange as (value: V | null) => void} items={options}>
<SelectTrigger className={className} aria-label={label}><SelectValue /></SelectTrigger>
<SelectContent>
<SelectGroup>
@@ -35,7 +77,7 @@ function OptionSelect({ value, onChange, options, className, label }) {
);
}
-export default function ReelsFilters({ igAccounts, itemCount, typeTotals, filters, handlers }) {
+export default function ReelsFilters({ igAccounts, itemCount, typeTotals, filters, handlers }: ReelsFiltersProps) {
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
@@ -43,7 +85,7 @@ export default function ReelsFilters({ igAccounts, itemCount, typeTotals, filter
{igAccounts.length > 1 && (
<Select
value={filters.accountFilter}
- onValueChange={handlers.onAccountChange}
+ onValueChange={handlers.onAccountChange as (value: string | null) => void}
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>
diff --git a/frontend/src/features/analytics/reels/ReelsGrid.tsx b/frontend/src/features/analytics/reels/ReelsGrid.tsx
index fd75b4d..b1eeb5e 100644
--- a/frontend/src/features/analytics/reels/ReelsGrid.tsx
+++ b/frontend/src/features/analytics/reels/ReelsGrid.tsx
@@ -2,8 +2,13 @@ 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';
+import type { LibraryMedia } from './reelsLibrary.ts';
-export default function ReelsGrid({ items }) {
+export interface ReelsGridProps {
+ items: LibraryMedia[];
+}
+
+export default function ReelsGrid({ items }: ReelsGridProps) {
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) => (
diff --git a/frontend/src/features/analytics/reels/ReelsMetrics.tsx b/frontend/src/features/analytics/reels/ReelsMetrics.tsx
index b3aa98d..75c9872 100644
--- a/frontend/src/features/analytics/reels/ReelsMetrics.tsx
+++ b/frontend/src/features/analytics/reels/ReelsMetrics.tsx
@@ -1,12 +1,25 @@
import { Clapperboard, Eye, Film, Image } from 'lucide-react';
+import type { LucideIcon } 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 type { InstagramContentType } from '@shared/types/instagram.ts';
import { typeViewsSubtitle, viewTotalsOf } from './reelsLibrary.ts';
+import type { MediaTypeTotal, MediaTypeTotals } from './reelsLibrary.ts';
-const CONTENT_TYPE_ICONS = { reel: Clapperboard, post: Image, video: Film };
+interface TypeMetricProps {
+ type: InstagramContentType;
+ typeTotal: MediaTypeTotal;
+}
+
+export interface ReelsMetricsProps {
+ typeTotals: MediaTypeTotals;
+ itemCount: number;
+}
+
+const CONTENT_TYPE_ICONS: Record<InstagramContentType, LucideIcon> = { reel: Clapperboard, post: Image, video: Film };
-function TypeMetric({ type, typeTotal }) {
+function TypeMetric({ type, typeTotal }: TypeMetricProps) {
const Icon = CONTENT_TYPE_ICONS[type];
return (
<MetricBox
@@ -19,7 +32,7 @@ function TypeMetric({ type, typeTotal }) {
);
}
-export default function ReelsMetrics({ typeTotals, itemCount }) {
+export default function ReelsMetrics({ typeTotals, itemCount }: ReelsMetricsProps) {
const { totalViews, viewsReported } = viewTotalsOf(typeTotals);
return (
<div className="grid grid-cols-2 gap-3 xl:grid-cols-4">
diff --git a/frontend/src/features/analytics/reels/reelsLibrary.ts b/frontend/src/features/analytics/reels/reelsLibrary.ts
index 5503ada..420bfef 100644
--- a/frontend/src/features/analytics/reels/reelsLibrary.ts
+++ b/frontend/src/features/analytics/reels/reelsLibrary.ts
@@ -1,15 +1,51 @@
import { LIKE_TIERS, filterByTier, matchesText } from '../../../lib/library.ts';
import { fmtNum } from '../../../utils/formatters.ts';
import { IG_CONTENT_TYPES } from '../../../utils/instagramContent.ts';
+import type { InstagramMedia } from '../../../../../shared/types/instagram.ts';
-function engagementRateOf(item) {
- if (item.viewCount > 0) return ((item.likeCount || 0) + (item.commentsCount || 0)) / item.viewCount * 100;
+// the fields mergeAccountMedia reads from each fulfilled media request
+export interface AccountMediaResult {
+ media?: InstagramMedia[];
+}
+
+export interface MediaAccount {
+ id: string;
+ title?: string | null;
+ username?: string;
+}
+
+// a media item in the library page, tagged with its account
+export interface LibraryMedia extends InstagramMedia {
+ accountTitle: string;
+ accountId: string;
+ engagementRate: number | null;
+}
+
+export interface MediaTypeTotal {
+ count: number;
+ views: number;
+ viewsReported: number;
+}
+
+export type MediaTypeTotals = Record<string, MediaTypeTotal>;
+
+export type MediaSortField = 'viewCount' | 'likeCount' | 'commentsCount' | 'engagementRate' | 'timestamp';
+
+export interface MediaQuery {
+ typeFilter: string;
+ search: string;
+ tier: string;
+ sortField: MediaSortField;
+}
+
+function engagementRateOf(item: Pick<InstagramMedia, 'viewCount' | 'likeCount' | 'commentsCount'>): number | null {
+ if (item.viewCount! > 0) return ((item.likeCount || 0) + (item.commentsCount || 0)) / item.viewCount! * 100;
return null;
}
// one Promise.allSettled result per account; failed accounts are skipped
-export function mergeAccountMedia(igAccounts, results) {
- const all = [];
+export function mergeAccountMedia(igAccounts: MediaAccount[], results: PromiseSettledResult<AccountMediaResult>[]): LibraryMedia[] {
+ const all: LibraryMedia[] = [];
results.forEach((result, i) => {
if (result.status !== 'fulfilled') return;
const account = igAccounts[i];
@@ -25,7 +61,7 @@ export function mergeAccountMedia(igAccounts, results) {
return all;
}
-export function typeTotalsOf(media) {
+export function typeTotalsOf(media: Pick<InstagramMedia, 'contentType' | 'viewCount'>[]): MediaTypeTotals {
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;
@@ -38,31 +74,31 @@ export function typeTotalsOf(media) {
return totals;
}
-export function viewTotalsOf(typeTotals) {
+export function viewTotalsOf(typeTotals: MediaTypeTotals) {
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) {
+function sortValue(item: LibraryMedia, field: MediaSortField): number {
if (field === 'timestamp') return new Date(item.timestamp).getTime() || 0;
return item[field] ?? -1;
}
-export function filterAndSortMedia(media, { typeFilter, search, tier, sortField }) {
+export function filterAndSortMedia(media: LibraryMedia[], { typeFilter, search, tier, sortField }: MediaQuery): LibraryMedia[] {
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) {
+export function typeViewsSubtitle(typeTotal: Pick<MediaTypeTotal, 'views' | 'viewsReported'>): string {
if (typeTotal.viewsReported > 0) return `${fmtNum(typeTotal.views)} views`;
return 'No views reported';
}
-export function reelsDescription(loading, itemCount, accountCount) {
+export function reelsDescription(loading: boolean, itemCount: number, accountCount: number): string {
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/useInstagramMedia.ts b/frontend/src/features/analytics/reels/useInstagramMedia.ts
index cdbbc28..52c6f4f 100644
--- a/frontend/src/features/analytics/reels/useInstagramMedia.ts
+++ b/frontend/src/features/analytics/reels/useInstagramMedia.ts
@@ -2,12 +2,13 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
import { useAppContext } from '../../../context/AppContext';
import { api } from '../../../services/api';
import { mergeAccountMedia } from './reelsLibrary.ts';
+import type { LibraryMedia } from './reelsLibrary.ts';
// one failed Instagram account does not hide media from the rest
export function useInstagramMedia() {
const { accounts, showToast } = useAppContext();
const igAccounts = useMemo(() => accounts.filter(account => account.platform === 'instagram'), [accounts]);
- const [media, setMedia] = useState([]);
+ const [media, setMedia] = useState<LibraryMedia[]>([]);
const [loading, setLoading] = useState(true);
const loadAllMedia = useCallback(async () => {
@@ -16,7 +17,7 @@ export function useInstagramMedia() {
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');
+ showToast(`Couldn't load Instagram content. ${(err as Error).message}`, 'error');
} finally {
setLoading(false);
}
diff --git a/frontend/src/features/analytics/shorts/ShortsExplorer.tsx b/frontend/src/features/analytics/shorts/ShortsExplorer.tsx
index 40f09c8..33a1846 100644
--- a/frontend/src/features/analytics/shorts/ShortsExplorer.tsx
+++ b/frontend/src/features/analytics/shorts/ShortsExplorer.tsx
@@ -13,10 +13,11 @@ import { cn } from '@/lib/utils';
import ShortsFilters from './ShortsFilters';
import ShortsGrid from './ShortsGrid';
import { shortsOf, filterAndSortShorts, shortsDescription } from './shortsLibrary.ts';
+import type { ShortsSortField, ShortsSortOption } from './shortsLibrary.ts';
const ITEMS_PER_PAGE = 24;
-const SORT_OPTIONS = [
+const SORT_OPTIONS: ShortsSortOption[] = [
{ value: 'viewCount', label: 'Most viewed' },
{ value: 'likeCount', label: 'Most liked' },
{ value: 'commentCount', label: 'Most comments' },
@@ -29,7 +30,7 @@ export default function ShortsExplorer() {
const [search, setSearch] = useState('');
const [channelFilter, setChannelFilter] = useState('all');
const [tier, setTier] = useState('all');
- const [sortField, setSortField] = useState('viewCount');
+ const [sortField, setSortField] = useState<ShortsSortField>('viewCount');
const [page, setPage] = useState(1);
const shorts = useMemo(() => shortsOf(videos), [videos]);
@@ -41,8 +42,8 @@ export default function ShortsExplorer() {
const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
- function resetPage(setter) {
- return value => {
+ function resetPage<T>(setter: (value: T) => void) {
+ return (value: T) => {
setter(value);
setPage(1);
};
diff --git a/frontend/src/features/analytics/shorts/ShortsFilters.tsx b/frontend/src/features/analytics/shorts/ShortsFilters.tsx
index 1c38841..330345a 100644
--- a/frontend/src/features/analytics/shorts/ShortsFilters.tsx
+++ b/frontend/src/features/analytics/shorts/ShortsFilters.tsx
@@ -3,10 +3,25 @@ import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectVa
import SearchField from '@/components/SearchField';
import FilterChips from '@/components/FilterChips';
import { VIEW_TIERS } from '@/lib/library';
+import type { LibraryChannel } from '../videos/videoLibrary.ts';
+import type { ShortsSortField, ShortsSortOption } from './shortsLibrary.ts';
+
+export interface ShortsFiltersProps {
+ channels: LibraryChannel[];
+ sortOptions: ShortsSortOption[];
+ search: string;
+ onSearchChange: (value: string) => void;
+ channelFilter: string;
+ onChannelChange: (value: string) => void;
+ sortField: ShortsSortField;
+ onSortChange: (value: ShortsSortField) => void;
+ tier: string;
+ onTierChange: (value: string) => void;
+}
export default function ShortsFilters({
channels, sortOptions, search, onSearchChange, channelFilter, onChannelChange, sortField, onSortChange, tier, onTierChange,
-}) {
+}: ShortsFiltersProps) {
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
@@ -14,7 +29,7 @@ export default function ShortsFilters({
{channels.length > 1 && (
<Select
value={channelFilter}
- onValueChange={onChannelChange}
+ onValueChange={onChannelChange as (value: string | null) => void}
items={[{ value: 'all', label: 'All channels' }, ...channels.map(channel => ({ value: channel.id, label: channel.title }))]}
>
<SelectTrigger className="w-48" aria-label="Channel"><SelectValue /></SelectTrigger>
@@ -26,7 +41,7 @@ export default function ShortsFilters({
</SelectContent>
</Select>
)}
- <Select value={sortField} onValueChange={onSortChange} items={sortOptions}>
+ <Select value={sortField} onValueChange={onSortChange as (value: ShortsSortField | null) => void} items={sortOptions}>
<SelectTrigger className="w-44" aria-label="Sort"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectGroup>
diff --git a/frontend/src/features/analytics/shorts/ShortsGrid.tsx b/frontend/src/features/analytics/shorts/ShortsGrid.tsx
index 7b510a5..4144270 100644
--- a/frontend/src/features/analytics/shorts/ShortsGrid.tsx
+++ b/frontend/src/features/analytics/shorts/ShortsGrid.tsx
@@ -2,8 +2,13 @@ import React from 'react';
import { Eye, MessageSquare, ThumbsUp } from 'lucide-react';
import MediaCard, { MediaChip } from '@/components/MediaCard';
import { fmtNum, fmtDuration, fmtCount } from '../../../utils/formatters';
+import type { LibraryVideo } from '../videos/videoLibrary.ts';
-export default function ShortsGrid({ shorts }) {
+export interface ShortsGridProps {
+ shorts: LibraryVideo[];
+}
+
+export default function ShortsGrid({ shorts }: ShortsGridProps) {
return (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6">
{shorts.map((video, i) => (
diff --git a/frontend/src/features/analytics/shorts/shortsLibrary.ts b/frontend/src/features/analytics/shorts/shortsLibrary.ts
index 131981c..29a107e 100644
--- a/frontend/src/features/analytics/shorts/shortsLibrary.ts
+++ b/frontend/src/features/analytics/shorts/shortsLibrary.ts
@@ -1,25 +1,40 @@
import { VIEW_TIERS, filterByTier, matchesText } from '../../../lib/library.ts';
import { fmtNum } from '../../../utils/formatters.ts';
+import type { LibraryVideo } from '../videos/videoLibrary.ts';
+
+export type ShortsSortField = 'viewCount' | 'likeCount' | 'commentCount' | 'engagementRate' | 'publishedAt';
+
+export interface ShortsSortOption {
+ value: ShortsSortField;
+ label: string;
+}
+
+export interface ShortsQuery {
+ channelFilter: string;
+ search: string;
+ tier: string;
+ sortField: ShortsSortField;
+}
const SHORT_MAX_SECONDS = 60;
-export function shortsOf(videos) {
+export function shortsOf(videos: LibraryVideo[]): LibraryVideo[] {
return videos.filter(video => video.durationSeconds > 0 && video.durationSeconds <= SHORT_MAX_SECONDS);
}
-function sortValue(item, field) {
+function sortValue(item: LibraryVideo, field: ShortsSortField): number {
if (field === 'publishedAt') return new Date(item.publishedAt).getTime() || 0;
return Number(item[field] ?? 0);
}
-export function filterAndSortShorts(shorts, { channelFilter, search, tier, sortField }) {
+export function filterAndSortShorts(shorts: LibraryVideo[], { channelFilter, search, tier, sortField }: ShortsQuery): LibraryVideo[] {
let result = channelFilter === 'all' ? shorts : shorts.filter(video => video.channelId === channelFilter);
result = result.filter(video => matchesText([video.title], search));
result = filterByTier(result, VIEW_TIERS, tier, 'viewCount');
return [...result].sort((a, b) => sortValue(b, sortField) - sortValue(a, sortField));
}
-export function shortsDescription(loading, shortCount, channelCount) {
+export function shortsDescription(loading: boolean, shortCount: number, channelCount: number): string {
if (loading) return 'Loading Shorts from your channels';
return `${fmtNum(shortCount)} Shorts across ${channelCount} channel${channelCount === 1 ? '' : 's'}`;
}
diff --git a/frontend/src/features/analytics/videos/LayoutToggle.tsx b/frontend/src/features/analytics/videos/LayoutToggle.tsx
index de7cc5e..dc09b7f 100644
--- a/frontend/src/features/analytics/videos/LayoutToggle.tsx
+++ b/frontend/src/features/analytics/videos/LayoutToggle.tsx
@@ -1,9 +1,23 @@
import { LayoutGrid, List } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
-const LAYOUTS = [{ value: 'table', label: 'List', Icon: List }, { value: 'grid', label: 'Grid', Icon: LayoutGrid }];
+export type LayoutMode = 'table' | 'grid';
-export default function LayoutToggle({ value, onChange }) {
+interface LayoutOption {
+ value: LayoutMode;
+ label: string;
+ Icon: LucideIcon;
+}
+
+export interface LayoutToggleProps {
+ value: LayoutMode;
+ onChange: (value: LayoutMode) => void;
+}
+
+const LAYOUTS: LayoutOption[] = [{ value: 'table', label: 'List', Icon: List }, { value: 'grid', label: 'Grid', Icon: LayoutGrid }];
+
+export default function LayoutToggle({ value, onChange }: LayoutToggleProps) {
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 => {
diff --git a/frontend/src/features/analytics/videos/VideoExplorer.tsx b/frontend/src/features/analytics/videos/VideoExplorer.tsx
index 1e68570..1daaea7 100644
--- a/frontend/src/features/analytics/videos/VideoExplorer.tsx
+++ b/frontend/src/features/analytics/videos/VideoExplorer.tsx
@@ -9,17 +9,30 @@ import SurfaceBox from '@/components/SurfaceBox';
import Pager from '@/components/Pager';
import { EmptyState } from '@/components/StateViews';
import { pageSlice } from '@/lib/library';
+import type { 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.ts';
+import type { LibraryVideo, VideoSort, VideoSortField } from './videoLibrary.ts';
import VideoFilters from './VideoFilters';
import VideoListTable from './VideoListTable';
import VideoGrid from './VideoGrid';
+import type { LayoutMode } from './LayoutToggle';
const ITEMS_PER_PAGE = 25;
-function VideoResults({ filtered, paged, viewMode, sort, onSort, showChannel, onClearFilters }) {
+interface VideoResultsProps {
+ filtered: LibraryVideo[];
+ paged: PageSlice<LibraryVideo>;
+ viewMode: LayoutMode;
+ sort: VideoSort;
+ onSort: (field: VideoSortField) => void;
+ showChannel: boolean;
+ onClearFilters: () => void;
+}
+
+function VideoResults({ filtered, paged, viewMode, sort, onSort, showChannel, onClearFilters }: VideoResultsProps) {
if (filtered.length === 0) {
return (
<SurfaceBox>
@@ -42,8 +55,8 @@ export default function VideoExplorer() {
const [search, setSearch] = useState('');
const [channelFilter, setChannelFilter] = useState('all');
const [tier, setTier] = useState('all');
- const [sort, setSort] = useState({ field: 'viewCount', order: 'desc' });
- const [viewMode, setViewMode] = useState('table');
+ const [sort, setSort] = useState<VideoSort>({ field: 'viewCount', order: 'desc' });
+ const [viewMode, setViewMode] = useState<LayoutMode>('table');
const [page, setPage] = useState(1);
const filtered = useMemo(
@@ -53,13 +66,13 @@ export default function VideoExplorer() {
const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
const stats = useMemo(() => videoStatsOf(filtered), [filtered]);
- function resetPage(setter) {
- return value => {
+ function resetPage<T>(setter: (value: T) => void) {
+ return (value: T) => {
setter(value);
setPage(1);
};
}
- const handleSort = field => setSort(prev => nextSort(prev, field));
+ const handleSort = (field: VideoSortField) => setSort(prev => nextSort(prev, field));
const clearFilters = () => { setSearch(''); setTier('all'); setChannelFilter('all'); setPage(1); };
const header = (
diff --git a/frontend/src/features/analytics/videos/VideoFilters.tsx b/frontend/src/features/analytics/videos/VideoFilters.tsx
index 234efa7..e2b8ff1 100644
--- a/frontend/src/features/analytics/videos/VideoFilters.tsx
+++ b/frontend/src/features/analytics/videos/VideoFilters.tsx
@@ -3,12 +3,32 @@ import SearchField from '@/components/SearchField';
import FilterChips from '@/components/FilterChips';
import { VIEW_TIERS } from '@/lib/library';
import LayoutToggle from './LayoutToggle';
+import type { LayoutMode } from './LayoutToggle';
+import type { LibraryChannel } from './videoLibrary.ts';
-function ChannelSelect({ channels, value, onChange }) {
+interface ChannelSelectProps {
+ channels: LibraryChannel[];
+ value: string;
+ onChange: (value: string) => void;
+}
+
+export interface VideoFiltersProps {
+ channels: LibraryChannel[];
+ search: string;
+ onSearchChange: (value: string) => void;
+ channelFilter: string;
+ onChannelChange: (value: string) => void;
+ viewMode: LayoutMode;
+ onViewModeChange: (value: LayoutMode) => void;
+ tier: string;
+ onTierChange: (value: string) => void;
+}
+
+function ChannelSelect({ channels, value, onChange }: ChannelSelectProps) {
return (
<Select
value={value}
- onValueChange={onChange}
+ onValueChange={onChange as (value: string | null) => void}
items={[{ value: 'all', label: 'All channels' }, ...channels.map(channel => ({ value: channel.id, label: channel.title }))]}
>
<SelectTrigger className="w-48" aria-label="Channel"><SelectValue /></SelectTrigger>
@@ -24,7 +44,7 @@ function ChannelSelect({ channels, value, onChange }) {
export default function VideoFilters({
channels, search, onSearchChange, channelFilter, onChannelChange, viewMode, onViewModeChange, tier, onTierChange,
-}) {
+}: VideoFiltersProps) {
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
diff --git a/frontend/src/features/analytics/videos/VideoGrid.tsx b/frontend/src/features/analytics/videos/VideoGrid.tsx
index aa1c8ff..0e07a2e 100644
--- a/frontend/src/features/analytics/videos/VideoGrid.tsx
+++ b/frontend/src/features/analytics/videos/VideoGrid.tsx
@@ -2,8 +2,14 @@ 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.ts';
+import type { LibraryVideo } from './videoLibrary.ts';
-export default function VideoGrid({ items, showChannel }) {
+export interface VideoGridProps {
+ items: LibraryVideo[];
+ showChannel: boolean;
+}
+
+export default function VideoGrid({ items, showChannel }: VideoGridProps) {
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) => (
diff --git a/frontend/src/features/analytics/videos/VideoListTable.tsx b/frontend/src/features/analytics/videos/VideoListTable.tsx
index 7f92c91..47d3270 100644
--- a/frontend/src/features/analytics/videos/VideoListTable.tsx
+++ b/frontend/src/features/analytics/videos/VideoListTable.tsx
@@ -5,10 +5,25 @@ 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 type { PageSlice } from '@/lib/library';
import { watchUrl } from './videoLibrary.ts';
+import type { LibraryVideo, VideoSort, VideoSortField } from './videoLibrary.ts';
import VideoSortHeader from './VideoSortHeader';
-function VideoRow({ video, rank, showChannel }) {
+interface VideoRowProps {
+ video: LibraryVideo;
+ rank: number;
+ showChannel: boolean;
+}
+
+export interface VideoListTableProps {
+ paged: PageSlice<LibraryVideo>;
+ sort: VideoSort;
+ onSort: (field: VideoSortField) => void;
+ showChannel: boolean;
+}
+
+function VideoRow({ video, rank, showChannel }: VideoRowProps) {
return (
<TableRow>
<TableCell className="text-right font-mono text-caption text-ink-faint">{rank}</TableCell>
@@ -43,7 +58,7 @@ function VideoRow({ video, rank, showChannel }) {
);
}
-export default function VideoListTable({ paged, sort, onSort, showChannel }) {
+export default function VideoListTable({ paged, sort, onSort, showChannel }: VideoListTableProps) {
return (
<SurfaceBox content={false} className="overflow-hidden">
<Table>
diff --git a/frontend/src/features/analytics/videos/VideoSortHeader.tsx b/frontend/src/features/analytics/videos/VideoSortHeader.tsx
index dbe3e75..6acfe1c 100644
--- a/frontend/src/features/analytics/videos/VideoSortHeader.tsx
+++ b/frontend/src/features/analytics/videos/VideoSortHeader.tsx
@@ -1,8 +1,18 @@
import { ArrowDown, ArrowUp } from 'lucide-react';
import { cn } from '@/lib/utils';
+import type { ReactNode } from 'react';
import { ariaSortOf } from './videoLibrary.ts';
+import type { VideoSort, VideoSortField } from './videoLibrary.ts';
-export default function VideoSortHeader({ field, label, sort, onSort, align = 'left' }) {
+export interface VideoSortHeaderProps {
+ field: VideoSortField;
+ label: ReactNode;
+ sort: VideoSort;
+ onSort: (field: VideoSortField) => void;
+ align?: 'left' | 'right';
+}
+
+export default function VideoSortHeader({ field, label, sort, onSort, align = 'left' }: VideoSortHeaderProps) {
const active = sort.field === field;
const Arrow = sort.order === 'asc' ? ArrowUp : ArrowDown;
return (
diff --git a/frontend/src/features/analytics/videos/useChannelVideos.ts b/frontend/src/features/analytics/videos/useChannelVideos.ts
index 01d49c4..b917b4f 100644
--- a/frontend/src/features/analytics/videos/useChannelVideos.ts
+++ b/frontend/src/features/analytics/videos/useChannelVideos.ts
@@ -2,13 +2,15 @@ import { useCallback, useEffect, useState } from 'react';
import { api } from '../../../services/api';
import { useAppContext } from '../../../context/AppContext';
import { platformOf } from '@/lib/accounts';
+import type { AppAccount } from '../../../utils/formatters';
import { mergeChannelVideos } from './videoLibrary';
+import type { LibraryChannel, LibraryVideo } from './videoLibrary';
// Loads every video from every YouTube channel. Shared by the Videos and Shorts pages.
export function useChannelVideos() {
const { accounts, showToast } = useAppContext();
- const [videos, setVideos] = useState([]);
- const [channels, setChannels] = useState([]);
+ const [videos, setVideos] = useState<LibraryVideo[]>([]);
+ const [channels, setChannels] = useState<LibraryChannel<AppAccount>[]>([]);
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
@@ -20,7 +22,7 @@ export function useChannelVideos() {
setVideos(merged.videos);
setChannels(merged.channels);
} catch (err) {
- showToast(`Couldn't load videos. ${err.message}`, 'error');
+ showToast(`Couldn't load videos. ${(err as Error).message}`, 'error');
} finally {
setLoading(false);
}
diff --git a/frontend/src/features/analytics/videos/videoLibrary.ts b/frontend/src/features/analytics/videos/videoLibrary.ts
index 3af3c1a..26ba6b2 100644
--- a/frontend/src/features/analytics/videos/videoLibrary.ts
+++ b/frontend/src/features/analytics/videos/videoLibrary.ts
@@ -1,10 +1,59 @@
import { VIEW_TIERS, filterByTier, matchesText, engagementPercent, parseIsoDuration } from '../../../lib/library.ts';
import { fmtNum } from '../../../utils/formatters.ts';
+import type { YouTubeVideo } from '../../../../../shared/types/youtube.ts';
+
+// a video as GET /api/accounts/:id/videos sends it; thumbnail and durationSeconds are fallbacks the route never sets
+export interface ChannelVideo extends YouTubeVideo {
+ thumbnail?: string;
+ durationSeconds?: number;
+}
+
+// the fields mergeChannelVideos reads from each fulfilled videos request
+export interface ChannelVideosResult {
+ videos?: ChannelVideo[];
+ data?: { videos?: ChannelVideo[] };
+}
+
+export interface VideoChannelAccount {
+ id: string;
+ title?: string | null;
+ channelTitle?: string;
+}
+
+export interface LibraryChannel<A extends VideoChannelAccount = VideoChannelAccount> {
+ id: string;
+ title: string;
+ account: A;
+}
+
+// a video in the library pages, tagged with its channel
+export interface LibraryVideo extends YouTubeVideo {
+ thumbnail: string;
+ channelId: string;
+ engagementRate: string;
+ durationSeconds: number;
+}
+
+export type VideoSortField = 'title' | 'viewCount' | 'likeCount' | 'commentCount' | 'engagementRate' | 'durationSeconds' | 'publishedAt';
+
+export type SortOrder = 'asc' | 'desc';
+
+export interface VideoSort {
+ field: VideoSortField;
+ order: SortOrder;
+}
+
+export interface VideoQuery {
+ channelFilter: string;
+ search: string;
+ tier: string;
+ sort: VideoSort;
+}
// failed channels are left out; each video gains its channel and derived fields
-export function mergeChannelVideos(channelAccounts, results) {
- const videos = [];
- const channels = [];
+export function mergeChannelVideos<A extends VideoChannelAccount>(channelAccounts: A[], results: PromiseSettledResult<ChannelVideosResult>[]) {
+ const videos: LibraryVideo[] = [];
+ const channels: LibraryChannel<A>[] = [];
results.forEach((result, i) => {
if (result.status !== 'fulfilled') return;
const acct = channelAccounts[i];
@@ -25,19 +74,19 @@ export function mergeChannelVideos(channelAccounts, results) {
return { videos, channels };
}
-export function watchUrl(videoId) {
+export function watchUrl(videoId: string): string {
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) {
+function compareField(a: LibraryVideo, b: LibraryVideo, field: VideoSortField): number {
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 }) {
+export function filterAndSortVideos(videos: LibraryVideo[], { channelFilter, search, tier, sort }: VideoQuery): LibraryVideo[] {
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');
@@ -45,8 +94,8 @@ export function filterAndSortVideos(videos, { channelFilter, search, tier, sort
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);
+export function videoStatsOf(videos: Pick<YouTubeVideo, 'viewCount' | 'likeCount' | 'commentCount'>[]) {
+ const sum = (key: 'viewCount' | 'likeCount' | 'commentCount') => videos.reduce((total, video) => total + (video[key] || 0), 0);
const views = sum('viewCount');
return {
total: videos.length,
@@ -58,18 +107,18 @@ export function videoStatsOf(videos) {
}
// a new column starts descending; the same column flips direction
-export function nextSort(previous, field) {
+export function nextSort(previous: VideoSort, field: VideoSortField): VideoSort {
if (previous.field !== field) return { field, order: 'desc' };
return { field, order: previous.order === 'asc' ? 'desc' : 'asc' };
}
-export function ariaSortOf(sort, field) {
+export function ariaSortOf(sort: VideoSort, field: VideoSortField): 'ascending' | 'descending' | undefined {
if (sort.field !== field) return undefined;
if (sort.order === 'asc') return 'ascending';
return 'descending';
}
-export function videosDescription(loading, videoCount, channelCount) {
+export function videosDescription(loading: boolean, videoCount: number, channelCount: number): string {
if (loading) return 'Loading videos from your channels';
return `${fmtNum(videoCount)} videos across ${channelCount} channel${channelCount === 1 ? '' : 's'}`;
}