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 frontend API layer, contexts, helpers and shell

spacesdrived3dc060fdfd3
diff --git a/frontend/src/components/ChartPanel.tsx b/frontend/src/components/ChartPanel.tsx
index e3bee1c..fe73289 100644
--- a/frontend/src/components/ChartPanel.tsx
+++ b/frontend/src/components/ChartPanel.tsx
@@ -3,7 +3,17 @@ import { ResponsiveContainer } from 'recharts';
import SurfaceBox from './SurfaceBox';
// Titled chart container. Pass `empty` to show a quiet message instead of an empty plot.
-export default function ChartPanel({ title, subheader, height = 280, empty = false, emptyMessage = 'Not enough data yet', className, children }) {
+export interface ChartPanelProps {
+ title?: React.ReactNode;
+ subheader?: React.ReactNode;
+ height?: number;
+ empty?: boolean;
+ emptyMessage?: React.ReactNode;
+ className?: string;
+ children: React.ReactNode;
+}
+
+export default function ChartPanel({ title, subheader, height = 280, empty = false, emptyMessage = 'Not enough data yet', className, children }: ChartPanelProps) {
return (
<SurfaceBox title={title} subheader={subheader} className={className} contentClassName="px-3 pt-4 pb-3">
{empty ? (
diff --git a/frontend/src/components/ChoiceCard.tsx b/frontend/src/components/ChoiceCard.tsx
index c436ecd..6a06acd 100644
--- a/frontend/src/components/ChoiceCard.tsx
+++ b/frontend/src/components/ChoiceCard.tsx
@@ -3,7 +3,17 @@ import { Check } from 'lucide-react';
import { cn } from '@/lib/utils';
// a radio when `selected` is defined, otherwise a plain button
-export default function ChoiceCard({ icon, title, description, selected, onSelect, disabled, className }) {
+export interface ChoiceCardProps {
+ icon?: React.ReactNode;
+ title: React.ReactNode;
+ description?: React.ReactNode;
+ selected?: boolean;
+ onSelect?: React.MouseEventHandler<HTMLButtonElement>;
+ disabled?: boolean;
+ className?: string;
+}
+
+export default function ChoiceCard({ icon, title, description, selected, onSelect, disabled, className }: ChoiceCardProps) {
const isRadio = selected !== undefined;
return (
<button
diff --git a/frontend/src/components/ColumnHint.tsx b/frontend/src/components/ColumnHint.tsx
index c8bce28..bd676aa 100644
--- a/frontend/src/components/ColumnHint.tsx
+++ b/frontend/src/components/ColumnHint.tsx
@@ -1,8 +1,14 @@
+import type React from 'react';
import { Info } from 'lucide-react';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
// A table header label with an info button that explains what the column measures.
-export default function ColumnHint({ label, hint }) {
+export interface ColumnHintProps {
+ label: string;
+ hint: React.ReactNode;
+}
+
+export default function ColumnHint({ label, hint }: ColumnHintProps) {
return (
<span className="inline-flex items-center justify-end gap-1">
{label}
diff --git a/frontend/src/components/CommandPalette.tsx b/frontend/src/components/CommandPalette.tsx
index ad1b33d..dd48749 100644
--- a/frontend/src/components/CommandPalette.tsx
+++ b/frontend/src/components/CommandPalette.tsx
@@ -4,6 +4,7 @@ import { useSmoothTheme } from '@/hooks/use-smooth-theme';
import {
LayoutDashboard, PlaySquare, Scissors, Clapperboard, MessagesSquare, Bookmark, Send,
Users, Settings, RefreshCw, Sun, Moon, Monitor, LogOut, Tag, Plus, BookOpen } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
import {
Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandShortcut,
} from '@/components/ui/command';
@@ -11,32 +12,52 @@ import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/compone
import { AccountAvatar } from '@/components/platform';
import { filterCommands, groupCommands } from '@/lib/commandSearch';
import { accountName, accountPath, PLATFORM_META, platformOf } from '@/lib/accounts';
+import type { AccountFields } from '@/lib/accounts';
+import type { SearchCommand } from '@/lib/commandSearch';
import { NAV_GROUPS } from '@/layout/navigation';
-const PAGE_ICONS = {
+const PAGE_ICONS: Record<string, LucideIcon> = {
'/': LayoutDashboard, '/videos': PlaySquare, '/shorts': Scissors, '/reels': Clapperboard,
'/reddit-posts': MessagesSquare, '/tracked-content': Bookmark, '/upload': Send,
'/accounts': Users, '/settings': Settings,
};
-export default function CommandPalette({ open, onOpenChange, accounts, categories, onRefreshAll, onSignOut }) {
+export interface PaletteCommand extends SearchCommand {
+ id: string;
+ group: string;
+ keywords: string[];
+ icon?: LucideIcon;
+ avatar?: AccountFields;
+ run?: () => unknown;
+}
+
+export interface CommandPaletteProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ accounts: AccountFields[];
+ categories: string[];
+ onRefreshAll: () => unknown;
+ onSignOut: () => unknown;
+}
+
+export default function CommandPalette({ open, onOpenChange, accounts, categories, onRefreshAll, onSignOut }: CommandPaletteProps) {
const navigate = useNavigate();
const { setTheme } = useSmoothTheme();
const [query, setQuery] = useState('');
- const handleOpenChange = next => {
+ const handleOpenChange = (next: boolean) => {
if (!next) setQuery('');
onOpenChange(next);
};
- const commands = useMemo(() => [
+ const commands = useMemo((): PaletteCommand[] => [
...NAV_GROUPS.flatMap(group => group.items.map(item => ({
id: `page:${item.path}`, group: 'Pages', label: item.label, keywords: [group.label],
icon: PAGE_ICONS[item.path], run: () => navigate(item.path),
}))),
...accounts.map(account => ({
id: `account:${account.id}`, group: 'Accounts', label: accountName(account),
- keywords: [PLATFORM_META[platformOf(account)].label, account.username, account.customUrl].filter(Boolean),
+ keywords: [PLATFORM_META[platformOf(account)].label, account.username, account.customUrl].filter(Boolean) as string[],
avatar: account, run: () => navigate(accountPath(account)),
})),
...categories.map(category => ({
@@ -54,7 +75,7 @@ export default function CommandPalette({ open, onOpenChange, accounts, categorie
const grouped = useMemo(() => groupCommands(filterCommands(commands, query)), [commands, query]);
- const runCommand = command => {
+ const runCommand = (command: PaletteCommand) => {
handleOpenChange(false);
command.run?.();
};
diff --git a/frontend/src/components/ConfirmDialog.tsx b/frontend/src/components/ConfirmDialog.tsx
index 72aeb8a..f9a5c40 100644
--- a/frontend/src/components/ConfirmDialog.tsx
+++ b/frontend/src/components/ConfirmDialog.tsx
@@ -7,6 +7,19 @@ import {
import { Spinner } from '@/components/ui/spinner';
import HoldToConfirmButton from './HoldToConfirmButton';
+export interface ConfirmDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ title: React.ReactNode;
+ description?: React.ReactNode;
+ confirmLabel?: string;
+ cancelLabel?: React.ReactNode;
+ onConfirm: () => void;
+ busy?: boolean;
+ hold?: boolean;
+ icon?: React.ReactNode;
+}
+
// destructive actions use `hold` so a stray click cannot confirm them
export default function ConfirmDialog({
open,
@@ -19,7 +32,7 @@ export default function ConfirmDialog({
busy = false,
hold = false,
icon = <Trash2 />,
-}) {
+}: ConfirmDialogProps) {
return (
<AlertDialog open={open} onOpenChange={next => { if (!busy) onOpenChange(next); }}>
<AlertDialogContent>
diff --git a/frontend/src/components/DetailPanel.tsx b/frontend/src/components/DetailPanel.tsx
index 69baf42..58be805 100644
--- a/frontend/src/components/DetailPanel.tsx
+++ b/frontend/src/components/DetailPanel.tsx
@@ -2,7 +2,15 @@ import React from 'react';
import { cn } from '@/lib/utils';
// sticky on wide screens, stacked below the main area on narrow ones
-export default function DetailPanel({ title, description, children, footer, className }) {
+export interface DetailPanelProps {
+ title?: React.ReactNode;
+ description?: React.ReactNode;
+ children?: React.ReactNode;
+ footer?: React.ReactNode;
+ className?: string;
+}
+
+export default function DetailPanel({ title, description, children, footer, className }: DetailPanelProps) {
return (
<aside
className={cn(
@@ -23,7 +31,15 @@ export default function DetailPanel({ title, description, children, footer, clas
}
// Label, hint and control in one settings-style row.
-export function FieldRow({ label, hint, htmlFor, children, className }) {
+export interface FieldRowProps {
+ label: React.ReactNode;
+ hint?: React.ReactNode;
+ htmlFor?: string;
+ children?: React.ReactNode;
+ className?: string;
+}
+
+export function FieldRow({ label, hint, htmlFor, children, className }: FieldRowProps) {
return (
<div className={cn('flex flex-col gap-2', className)}>
<div className="flex flex-col gap-0.5">
diff --git a/frontend/src/components/FilterChips.tsx b/frontend/src/components/FilterChips.tsx
index e6399f5..58fe1e6 100644
--- a/frontend/src/components/FilterChips.tsx
+++ b/frontend/src/components/FilterChips.tsx
@@ -1,8 +1,24 @@
import React from 'react';
+import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
// Single-select chip group. Options are { value, label, icon?, count? }.
-export default function FilterChips({ options, value, onChange, className, label = 'Filter' }) {
+export interface FilterChipOption<V extends string = string> {
+ value: V;
+ label: React.ReactNode;
+ icon?: LucideIcon;
+ count?: number;
+}
+
+export interface FilterChipsProps<V extends string = string> {
+ options: readonly FilterChipOption<V>[];
+ value: V;
+ onChange: (value: V) => void;
+ className?: string;
+ label?: string;
+}
+
+export default function FilterChips<V extends string = string>({ options, value, onChange, className, label = 'Filter' }: FilterChipsProps<V>) {
return (
<div role="radiogroup" aria-label={label} className={cn('flex flex-wrap items-center gap-1.5', className)}>
{options.map(option => {
diff --git a/frontend/src/components/GoogleSignInButton.tsx b/frontend/src/components/GoogleSignInButton.tsx
index dda5c5d..6140f80 100644
--- a/frontend/src/components/GoogleSignInButton.tsx
+++ b/frontend/src/components/GoogleSignInButton.tsx
@@ -2,12 +2,19 @@ import { useEffect, useRef, useState } from 'react';
import { useTheme } from 'next-themes';
import { Skeleton } from '@/components/ui/skeleton';
import { GOOGLE_CLIENT_ID, createNonce, loadGoogleIdentity } from '@/lib/googleIdentity';
+import type { GoogleButtonConfiguration } from '@/lib/googleIdentity';
// Google renders its own button inside an iframe; its width is capped at 400px by Google.
const MAX_WIDTH = 400;
-export default function GoogleSignInButton({ onCredential, onError, text = 'continue_with' }) {
- const containerRef = useRef(null);
+export interface GoogleSignInButtonProps {
+ onCredential: (credential: string, rawNonce: string) => void;
+ onError?: (err: Error) => void;
+ text?: GoogleButtonConfiguration['text'];
+}
+
+export default function GoogleSignInButton({ onCredential, onError, text = 'continue_with' }: GoogleSignInButtonProps) {
+ const containerRef = useRef<HTMLDivElement>(null);
const handlers = useRef({ onCredential, onError });
const { resolvedTheme } = useTheme();
const [ready, setReady] = useState(false);
@@ -42,7 +49,7 @@ export default function GoogleSignInButton({ onCredential, onError, text = 'cont
});
setReady(true);
} catch (err) {
- if (!cancelled) handlers.current.onError?.(err);
+ if (!cancelled) handlers.current.onError?.(err as Error);
}
})();
diff --git a/frontend/src/components/HoldToConfirmButton.tsx b/frontend/src/components/HoldToConfirmButton.tsx
index a195fb2..606760a 100644
--- a/frontend/src/components/HoldToConfirmButton.tsx
+++ b/frontend/src/components/HoldToConfirmButton.tsx
@@ -4,6 +4,17 @@ import { cn } from '@/lib/utils';
const HOLD_KEYS = new Set([' ', 'Enter']);
+type HoldController = ReturnType<typeof createHoldController>;
+
+export interface HoldToConfirmButtonProps {
+ onConfirm: () => void;
+ children?: React.ReactNode;
+ holdingLabel?: React.ReactNode;
+ duration?: number;
+ disabled?: boolean;
+ className?: string;
+}
+
// Destructive confirm that must be held, by pointer or by Space/Enter. A plain click never fires it.
export default function HoldToConfirmButton({
onConfirm,
@@ -12,9 +23,9 @@ export default function HoldToConfirmButton({
duration = DEFAULT_HOLD_MS,
disabled = false,
className,
-}) {
+}: HoldToConfirmButtonProps) {
const [progress, setProgress] = useState(0);
- const controllerRef = useRef(null);
+ const controllerRef = useRef<HoldController | null>(null);
const confirmRef = useRef(onConfirm);
useEffect(() => { confirmRef.current = onConfirm; }, [onConfirm]);
diff --git a/frontend/src/components/ImageLightbox.tsx b/frontend/src/components/ImageLightbox.tsx
index ff55f40..b41ac33 100644
--- a/frontend/src/components/ImageLightbox.tsx
+++ b/frontend/src/components/ImageLightbox.tsx
@@ -2,12 +2,19 @@ import React, { useState } from 'react';
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { cn } from '@/lib/utils';
+export interface ImageLightboxProps {
+ src?: string | null;
+ alt?: string;
+ className?: string;
+ thumbClassName?: string;
+}
+
export default function ImageLightbox({
src,
alt = '',
className = '',
thumbClassName = 'h-10 w-16',
-}) {
+}: ImageLightboxProps) {
const [open, setOpen] = useState(false);
if (!src) return null;
diff --git a/frontend/src/components/InstagramTesterNotice.tsx b/frontend/src/components/InstagramTesterNotice.tsx
index 8d13269..6a92657 100644
--- a/frontend/src/components/InstagramTesterNotice.tsx
+++ b/frontend/src/components/InstagramTesterNotice.tsx
@@ -16,8 +16,18 @@ const REQUEST_BODY = [
].join('\n');
// While the Meta app is in development mode, Instagram only lets accepted testers sign in.
-export default function InstagramTesterNotice({ compact = false, className }) {
- const steps = [
+export interface InstagramTesterNoticeProps {
+ compact?: boolean;
+ className?: string;
+}
+
+interface TesterStep {
+ title: string;
+ body: React.ReactNode;
+}
+
+export default function InstagramTesterNotice({ compact = false, className }: InstagramTesterNoticeProps) {
+ const steps: TesterStep[] = [
{
title: 'Ask to be added as a tester',
body: (
diff --git a/frontend/src/components/ListRow.tsx b/frontend/src/components/ListRow.tsx
index 9d172cd..43baf45 100644
--- a/frontend/src/components/ListRow.tsx
+++ b/frontend/src/components/ListRow.tsx
@@ -2,7 +2,12 @@ import React from 'react';
import { cn } from '@/lib/utils';
// Rank shown in mono so digits align; the leader carries the brand accent.
-export function RankNumber({ rank, className }) {
+export interface RankNumberProps {
+ rank: number;
+ className?: string;
+}
+
+export function RankNumber({ rank, className }: RankNumberProps) {
return (
<span
className={cn(
@@ -16,6 +21,16 @@ export function RankNumber({ rank, className }) {
);
}
+export interface ListRowProps {
+ leading?: React.ReactNode;
+ title: React.ReactNode;
+ meta?: React.ReactNode;
+ trailing?: React.ReactNode;
+ onClick?: React.MouseEventHandler<HTMLElement>;
+ selected?: boolean;
+ className?: string;
+}
+
// Dense, clickable row: leading media, a title with one line of metadata, and trailing content.
export default function ListRow({
leading,
@@ -25,7 +40,7 @@ export default function ListRow({
onClick,
selected = false,
className,
-}) {
+}: ListRowProps) {
const Element = onClick ? 'button' : 'div';
return (
<Element
diff --git a/frontend/src/components/MediaCard.tsx b/frontend/src/components/MediaCard.tsx
index b34556c..2f3d1e0 100644
--- a/frontend/src/components/MediaCard.tsx
+++ b/frontend/src/components/MediaCard.tsx
@@ -2,10 +2,17 @@ import React from 'react';
import { ImageOff } from 'lucide-react';
import { cn } from '@/lib/utils';
-const ASPECTS = { video: 'aspect-video', vertical: 'aspect-[9/16]', square: 'aspect-square' };
+export type MediaAspect = 'video' | 'vertical' | 'square';
+
+const ASPECTS: Record<MediaAspect, string> = { video: 'aspect-video', vertical: 'aspect-[9/16]', square: 'aspect-square' };
// Thumbnail card for library grids. Overlay chips sit on a dark scrim so they read on any image.
-export function MediaChip({ children, className }) {
+export interface MediaChipProps {
+ children?: React.ReactNode;
+ className?: string;
+}
+
+export function MediaChip({ children, className }: MediaChipProps) {
return (
<span className={cn('inline-flex items-center gap-1 rounded-pill bg-[#0C0809]/75 px-2 py-0.5 text-[0.6875rem] font-semibold text-white backdrop-blur-sm [&_svg]:size-3', className)}>
{children}
@@ -13,6 +20,18 @@ export function MediaChip({ children, className }) {
);
}
+export interface MediaCardProps {
+ image?: string | null;
+ aspect?: MediaAspect;
+ title?: React.ReactNode;
+ meta?: React.ReactNode;
+ topLeft?: React.ReactNode;
+ topRight?: React.ReactNode;
+ bottomRight?: React.ReactNode;
+ href?: string;
+ className?: string;
+}
+
export default function MediaCard({
image,
aspect = 'video',
@@ -23,7 +42,7 @@ export default function MediaCard({
bottomRight,
href,
className,
-}) {
+}: MediaCardProps) {
const Element = href ? 'a' : 'div';
return (
<Element
diff --git a/frontend/src/components/MetricAreaChart.tsx b/frontend/src/components/MetricAreaChart.tsx
index f9ce679..16c7ab5 100644
--- a/frontend/src/components/MetricAreaChart.tsx
+++ b/frontend/src/components/MetricAreaChart.tsx
@@ -4,8 +4,18 @@ import {
Tooltip as ReTooltip, ResponsiveContainer,
} from 'recharts';
import { fmtNum, fmtNumFull } from '../utils/formatters';
+import type { NumberLike } from '../utils/formatters';
import { axisProps, gridProps, tooltipStyle } from '@/lib/chart';
+export interface MetricAreaChartProps {
+ data?: readonly object[] | null;
+ dataKey: string;
+ label: string;
+ color?: string;
+ height?: number;
+ emptyMessage?: React.ReactNode;
+}
+
export default function MetricAreaChart({
data,
dataKey,
@@ -13,7 +23,7 @@ export default function MetricAreaChart({
color = 'var(--chart-1)',
height = 240,
emptyMessage = 'No data to display',
-}) {
+}: MetricAreaChartProps) {
// useId keeps each instance's gradient unique; colons are invalid inside a url() reference
const gradientId = `metric-area-${useId().replace(/:/g, '')}`;
@@ -36,7 +46,7 @@ export default function MetricAreaChart({
<ReTooltip
contentStyle={tooltipStyle}
cursor={{ stroke: 'var(--line-strong)' }}
- formatter={(v) => [fmtNumFull(v), label]}
+ formatter={(v) => [fmtNumFull(v as NumberLike), label]}
/>
<Area
type="monotone"
diff --git a/frontend/src/components/MetricBox.tsx b/frontend/src/components/MetricBox.tsx
index 7011876..ec05b6a 100644
--- a/frontend/src/components/MetricBox.tsx
+++ b/frontend/src/components/MetricBox.tsx
@@ -3,6 +3,19 @@ import { TrendingUp, TrendingDown } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';
+export interface MetricBoxProps {
+ icon?: React.ReactNode;
+ label: React.ReactNode;
+ value?: React.ReactNode;
+ subtitle?: React.ReactNode;
+ loading?: boolean;
+ small?: boolean;
+ trend?: number;
+ trendLabel?: React.ReactNode;
+ highlight?: boolean;
+ className?: string;
+}
+
// Quiet metric tile: neutral icon, large tabular value, label and one line of context.
export default function MetricBox({
icon,
@@ -15,7 +28,7 @@ export default function MetricBox({
trendLabel,
highlight = false,
className,
-}) {
+}: MetricBoxProps) {
return (
<div
className={cn(
diff --git a/frontend/src/components/PageHeader.tsx b/frontend/src/components/PageHeader.tsx
index 3580a0c..94155bc 100644
--- a/frontend/src/components/PageHeader.tsx
+++ b/frontend/src/components/PageHeader.tsx
@@ -3,6 +3,22 @@ import { Link } from 'react-router-dom';
import { ArrowLeft } from 'lucide-react';
import { cn } from '@/lib/utils';
+export interface PageHeaderBack {
+ to: string;
+ label: React.ReactNode;
+}
+
+export interface PageHeaderProps {
+ title: React.ReactNode;
+ description?: React.ReactNode;
+ eyebrow?: React.ReactNode;
+ actions?: React.ReactNode;
+ back?: PageHeaderBack;
+ media?: React.ReactNode;
+ size?: 'default' | 'display';
+ className?: string;
+}
+
// Page title block. One per page; actions sit on the right and wrap under the title on narrow screens.
export default function PageHeader({
title,
@@ -13,7 +29,7 @@ export default function PageHeader({
media,
size = 'default',
className,
-}) {
+}: PageHeaderProps) {
return (
<header className={cn('flex flex-col gap-4', className)}>
{back && (
diff --git a/frontend/src/components/Pager.tsx b/frontend/src/components/Pager.tsx
index 2479415..1dec5ae 100644
--- a/frontend/src/components/Pager.tsx
+++ b/frontend/src/components/Pager.tsx
@@ -2,7 +2,16 @@ import React from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
-export default function Pager({ page, pageCount, onPageChange, total, shown, noun = 'items' }) {
+export interface PagerProps {
+ page: number;
+ pageCount: number;
+ onPageChange: (page: number) => void;
+ total: number;
+ shown: number;
+ noun?: string;
+}
+
+export default function Pager({ page, pageCount, onPageChange, total, shown, noun = 'items' }: PagerProps) {
if (pageCount <= 1) {
return total > 0 ? <p className="text-center text-caption text-ink-faint">{total} {noun}</p> : null;
}
diff --git a/frontend/src/components/ProtectedRoute.tsx b/frontend/src/components/ProtectedRoute.tsx
index ee67c25..8722e0f 100644
--- a/frontend/src/components/ProtectedRoute.tsx
+++ b/frontend/src/components/ProtectedRoute.tsx
@@ -1,7 +1,12 @@
+import type React from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
-export default function ProtectedRoute({ children }) {
+export interface ProtectedRouteProps {
+ children: React.ReactNode;
+}
+
+export default function ProtectedRoute({ children }: ProtectedRouteProps) {
const { session } = useAuth();
if (session === undefined) return null; // still loading session
if (!session) return <Navigate to="/login" replace />;
diff --git a/frontend/src/components/SearchField.tsx b/frontend/src/components/SearchField.tsx
index 5a00e33..9166024 100644
--- a/frontend/src/components/SearchField.tsx
+++ b/frontend/src/components/SearchField.tsx
@@ -2,7 +2,13 @@ import React from 'react';
import { Search, X } from 'lucide-react';
import { cn } from '@/lib/utils';
-export default function SearchField({ value, onChange, placeholder = 'Search', className, inputClassName, ...props }) {
+export interface SearchFieldProps extends Omit<React.ComponentProps<'input'>, 'value' | 'onChange'> {
+ value: string;
+ onChange: (value: string) => void;
+ inputClassName?: string;
+}
+
+export default function SearchField({ value, onChange, placeholder = 'Search', className, inputClassName, ...props }: SearchFieldProps) {
return (
<div className={cn('relative flex min-w-0 items-center', className)}>
<Search className="pointer-events-none absolute left-3.5 size-4 stroke-[1.75] text-ink-faint" aria-hidden="true" />
diff --git a/frontend/src/components/SectionHeader.tsx b/frontend/src/components/SectionHeader.tsx
index 061cef1..78ea9b5 100644
--- a/frontend/src/components/SectionHeader.tsx
+++ b/frontend/src/components/SectionHeader.tsx
@@ -1,7 +1,14 @@
import React from 'react';
import { cn } from '@/lib/utils';
-export default function SectionHeader({ title, description, actions, className }) {
+export interface SectionHeaderProps {
+ title: React.ReactNode;
+ description?: React.ReactNode;
+ actions?: React.ReactNode;
+ className?: string;
+}
+
+export default function SectionHeader({ title, description, actions, className }: SectionHeaderProps) {
return (
<div className={cn('flex flex-wrap items-end justify-between gap-3', className)}>
<div className="min-w-0">
diff --git a/frontend/src/components/StateViews.tsx b/frontend/src/components/StateViews.tsx
index e7e18ce..227d257 100644
--- a/frontend/src/components/StateViews.tsx
+++ b/frontend/src/components/StateViews.tsx
@@ -5,7 +5,16 @@ import { Skeleton } from '@/components/ui/skeleton';
import { Spinner } from '@/components/ui/spinner';
import { cn } from '@/lib/utils';
-export function EmptyState({ icon, title, description, action, className, compact = false }) {
+export interface EmptyStateProps {
+ icon?: React.ReactNode;
+ title: React.ReactNode;
+ description?: React.ReactNode;
+ action?: React.ReactNode;
+ className?: string;
+ compact?: boolean;
+}
+
+export function EmptyState({ icon, title, description, action, className, compact = false }: EmptyStateProps) {
return (
<div
className={cn(
@@ -28,7 +37,14 @@ export function EmptyState({ icon, title, description, action, className, compac
);
}
-export function ErrorState({ title = 'This page could not load', description, onRetry, className }) {
+export interface ErrorStateProps {
+ title?: React.ReactNode;
+ description?: React.ReactNode;
+ onRetry?: () => void;
+ className?: string;
+}
+
+export function ErrorState({ title = 'This page could not load', description, onRetry, className }: ErrorStateProps) {
return (
<div role="alert" className={cn('flex flex-col items-center justify-center gap-4 px-6 py-14 text-center', className)}>
<span className="flex size-11 items-center justify-center rounded-card bg-danger-soft text-danger">
@@ -45,7 +61,12 @@ export function ErrorState({ title = 'This page could not load', description, on
);
}
-export function LoadingState({ label = 'Loading', className }) {
+export interface LoadingStateProps {
+ label?: React.ReactNode;
+ className?: string;
+}
+
+export function LoadingState({ label = 'Loading', className }: LoadingStateProps) {
return (
<div role="status" className={cn('flex min-h-[40vh] flex-col items-center justify-center gap-3', className)}>
<Spinner className="size-6 text-brand" />
@@ -55,7 +76,11 @@ export function LoadingState({ label = 'Loading', className }) {
}
// Placeholder that mirrors the real page layout: header, metric row, and a large panel.
-export function PageSkeleton({ metrics = 4 }) {
+export interface PageSkeletonProps {
+ metrics?: number;
+}
+
+export function PageSkeleton({ metrics = 4 }: PageSkeletonProps) {
return (
<div className="flex flex-col gap-8" aria-busy="true" aria-label="Loading page">
<div className="flex flex-col gap-2">
diff --git a/frontend/src/components/SurfaceBox.tsx b/frontend/src/components/SurfaceBox.tsx
index 01b42a3..7d3f22f 100644
--- a/frontend/src/components/SurfaceBox.tsx
+++ b/frontend/src/components/SurfaceBox.tsx
@@ -1,6 +1,17 @@
import React from 'react';
import { cn } from '@/lib/utils';
+export interface SurfaceBoxProps extends Omit<React.ComponentProps<'section'>, 'title' | 'content'> {
+ children?: React.ReactNode;
+ title?: React.ReactNode;
+ subheader?: React.ReactNode;
+ secondary?: React.ReactNode;
+ content?: boolean;
+ contentClassName?: string;
+ className?: string;
+ noPadding?: boolean;
+}
+
// the one container for grouped content; without a title it is a plain panel
export default function SurfaceBox({
children,
@@ -12,7 +23,7 @@ export default function SurfaceBox({
className = '',
noPadding = false,
...props
-}) {
+}: SurfaceBoxProps) {
return (
<section
className={cn('flex flex-col rounded-card border border-line bg-surface-raised text-ink', className)}
diff --git a/frontend/src/components/brand/Logo.tsx b/frontend/src/components/brand/Logo.tsx
index 52b841f..bd11e0c 100644
--- a/frontend/src/components/brand/Logo.tsx
+++ b/frontend/src/components/brand/Logo.tsx
@@ -4,7 +4,12 @@ import { cn } from '@/lib/utils';
const LOGO_DIR = '/Logos';
// css shows one of both lockups, so it is right before the theme hook runs
-export function Logo({ variant = 'lockup', className }) {
+export interface LogoProps {
+ variant?: 'lockup' | 'wordmark' | 'mark';
+ className?: string;
+}
+
+export function Logo({ variant = 'lockup', className }: LogoProps) {
if (variant === 'wordmark') {
return (
<span className={cn('inline-flex shrink-0 select-none', className)}>
diff --git a/frontend/src/components/brand/platform-icons.tsx b/frontend/src/components/brand/platform-icons.tsx
index 615265f..e23a979 100644
--- a/frontend/src/components/brand/platform-icons.tsx
+++ b/frontend/src/components/brand/platform-icons.tsx
@@ -1,4 +1,8 @@
-export function YouTubeIcon({ className, ...props }) {
+import type React from 'react';
+
+export type PlatformIconProps = React.SVGProps<SVGSVGElement>;
+
+export function YouTubeIcon({ className, ...props }: PlatformIconProps) {
return (
<svg viewBox="0 0 24 24" className={className} fill="currentColor" aria-hidden="true" {...props}>
<path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" />
@@ -6,7 +10,7 @@ export function YouTubeIcon({ className, ...props }) {
);
}
-export function InstagramIcon({ className, ...props }) {
+export function InstagramIcon({ className, ...props }: PlatformIconProps) {
return (
<svg viewBox="0 0 24 24" className={className} fill="currentColor" aria-hidden="true" {...props}>
<path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z" />
@@ -14,7 +18,7 @@ export function InstagramIcon({ className, ...props }) {
);
}
-export function RedditIcon({ className, ...props }) {
+export function RedditIcon({ className, ...props }: PlatformIconProps) {
return (
<svg viewBox="0 0 24 24" className={className} fill="currentColor" aria-hidden="true" {...props}>
<path d="M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0zm5.01 4.744c.688 0 1.25.561 1.25 1.249a1.25 1.25 0 0 1-2.498.056l-2.597-.547-.8 3.747c1.824.07 3.48.632 4.674 1.488.308-.309.73-.491 1.207-.491.968 0 1.754.786 1.754 1.754 0 .716-.435 1.333-1.01 1.614a3.111 3.111 0 0 1 .042.52c0 2.694-3.13 4.87-7.004 4.87-3.874 0-7.004-2.176-7.004-4.87 0-.183.015-.366.043-.534A1.748 1.748 0 0 1 4.028 12c0-.968.786-1.754 1.754-1.754.463 0 .898.196 1.207.49 1.207-.883 2.878-1.43 4.744-1.487l.885-4.182a.342.342 0 0 1 .14-.197.35.35 0 0 1 .238-.042l2.906.617a1.214 1.214 0 0 1 1.108-.701zM9.25 12C8.561 12 8 12.562 8 13.25c0 .687.561 1.248 1.25 1.248.687 0 1.248-.561 1.248-1.249 0-.688-.561-1.249-1.249-1.249zm5.5 0c-.687 0-1.248.561-1.248 1.25 0 .687.561 1.248 1.249 1.248.688 0 1.249-.561 1.249-1.249 0-.687-.562-1.249-1.25-1.249zm-5.466 3.99a.327.327 0 0 0-.231.094.33.33 0 0 0 0 .463c.842.842 2.484.913 2.961.913.477 0 2.105-.056 2.961-.913a.361.361 0 0 0 .029-.463.33.33 0 0 0-.464 0c-.547.533-1.684.73-2.512.73-.828 0-1.979-.196-2.512-.73a.326.326 0 0 0-.232-.095z" />
diff --git a/frontend/src/components/platform.tsx b/frontend/src/components/platform.tsx
index f7c6808..8555028 100644
--- a/frontend/src/components/platform.tsx
+++ b/frontend/src/components/platform.tsx
@@ -1,18 +1,31 @@
import React from 'react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { YouTubeIcon, InstagramIcon, RedditIcon } from '@/components/brand/platform-icons';
+import type { PlatformIconProps as SvgIconProps } from '@/components/brand/platform-icons';
import { PLATFORM_META, platformOf, accountImage, accountInitials, accountName } from '@/lib/accounts';
import { cn } from '@/lib/utils';
+import type { AccountFields } from '@/lib/accounts';
+import type { Platform } from '@shared/types/domain.ts';
-const ICONS = { youtube: YouTubeIcon, instagram: InstagramIcon, reddit: RedditIcon };
+const ICONS: Record<Platform, React.ComponentType<SvgIconProps>> = { youtube: YouTubeIcon, instagram: InstagramIcon, reddit: RedditIcon };
-export function PlatformIcon({ platform, className }) {
- const Icon = ICONS[platform] || YouTubeIcon;
+export type AccountAvatarSize = 'xs' | 'sm' | 'default' | 'lg' | 'xl';
+
+// platform stays a string: tracked posts pass their free-form content type
+export interface PlatformIconProps {
+ platform: string;
+ className?: string;
+}
+
+export function PlatformIcon({ platform, className }: PlatformIconProps) {
+ const Icon = ICONS[platform as Platform] || YouTubeIcon;
return <Icon className={cn('size-4 shrink-0', className)} />;
}
-export function PlatformBadge({ platform, className }) {
- const key = PLATFORM_META[platform] ? platform : 'youtube';
+export type PlatformBadgeProps = PlatformIconProps;
+
+export function PlatformBadge({ platform, className }: PlatformBadgeProps) {
+ const key = PLATFORM_META[platform as Platform] ? platform : 'youtube';
return (
<span
className={cn(
@@ -21,15 +34,22 @@ export function PlatformBadge({ platform, className }) {
)}
>
<PlatformIcon platform={key} className="size-3" />
- {PLATFORM_META[key].label}
+ {PLATFORM_META[key as Platform].label}
</span>
);
}
// Avatar with a small platform glyph in the corner, so platform reads without colour alone
-export function AccountAvatar({ account, size = 'default', showPlatform = false, className }) {
+export interface AccountAvatarProps {
+ account: AccountFields;
+ size?: AccountAvatarSize;
+ showPlatform?: boolean;
+ className?: string;
+}
+
+export function AccountAvatar({ account, size = 'default', showPlatform = false, className }: AccountAvatarProps) {
const platform = platformOf(account);
- const sizes = { xs: 'size-5', sm: 'size-6', default: 'size-8', lg: 'size-11', xl: 'size-16' };
+ const sizes: Record<AccountAvatarSize, string> = { xs: 'size-5', sm: 'size-6', default: 'size-8', lg: 'size-11', xl: 'size-16' };
return (
<span className={cn('relative inline-flex shrink-0', className)}>
<Avatar className={cn(sizes[size] || sizes.default)}>
diff --git a/frontend/src/context/AppContext.tsx b/frontend/src/context/AppContext.tsx
index ba6460b..f00da56 100644
--- a/frontend/src/context/AppContext.tsx
+++ b/frontend/src/context/AppContext.tsx
@@ -1,15 +1,28 @@
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
+import type { Dispatch, ReactNode, SetStateAction } from 'react';
import { toast } from 'sonner';
import { api } from '../services/api';
import { normalizeAccount } from '../utils/formatters';
+import type { AppAccount } from '../utils/formatters';
-const AppContext = createContext(null);
+export type ToastSeverity = 'success' | 'error' | 'warning' | 'info';
-export function AppProvider({ children }) {
- const [accounts, setAccounts] = useState([]);
+export interface AppContextValue {
+ accounts: AppAccount[];
+ setAccounts: Dispatch<SetStateAction<AppAccount[]>>;
+ loading: boolean;
+ showToast: (message: string, severity?: ToastSeverity) => void;
+ loadAccounts: () => Promise<void>;
+ refreshAll: () => Promise<void>;
+}
+
+const AppContext = createContext<AppContextValue | null>(null);
+
+export function AppProvider({ children }: { children: ReactNode }) {
+ const [accounts, setAccounts] = useState<AppAccount[]>([]);
const [loading, setLoading] = useState(false);
- const showToast = useCallback((message, severity = 'success') => {
+ const showToast = useCallback((message: string, severity: ToastSeverity = 'success') => {
if (severity === 'error') toast.error(message);
else if (severity === 'warning') toast.warning(message);
else if (severity === 'info') toast.info(message);
@@ -21,7 +34,7 @@ export function AppProvider({ children }) {
const data = await api.getAccounts();
setAccounts(data.map(normalizeAccount));
} catch (err) {
- showToast(`Couldn't load your accounts. ${err.message}`, 'error');
+ showToast(`Couldn't load your accounts. ${(err as Error).message}`, 'error');
}
}, [showToast]);
@@ -32,7 +45,7 @@ export function AppProvider({ children }) {
setAccounts((res.accounts || []).map(normalizeAccount));
showToast('All accounts refreshed');
} catch (err) {
- showToast(`Refresh failed. ${err.message}`, 'error');
+ showToast(`Refresh failed. ${(err as Error).message}`, 'error');
} finally {
setLoading(false);
}
@@ -47,7 +60,7 @@ export function AppProvider({ children }) {
);
}
-export function useAppContext() {
+export function useAppContext(): AppContextValue {
const ctx = useContext(AppContext);
if (!ctx) throw new Error('useAppContext must be used within AppProvider');
return ctx;
diff --git a/frontend/src/context/AuthContext.tsx b/frontend/src/context/AuthContext.tsx
index 65cd1b9..404e4d1 100644
--- a/frontend/src/context/AuthContext.tsx
+++ b/frontend/src/context/AuthContext.tsx
@@ -1,10 +1,23 @@
import { createContext, useContext, useEffect, useState } from 'react';
+import type { ReactNode } from 'react';
+import type { Session, User } from '@supabase/supabase-js';
import { supabase } from '../lib/supabase';
-const AuthContext = createContext(null);
+type Auth = typeof supabase.auth;
-export function AuthProvider({ children }) {
- const [session, setSession] = useState(undefined); // undefined = still loading
+export interface AuthContextValue {
+ session: Session | null | undefined;
+ user: User | null;
+ signIn: (email: string, password: string) => ReturnType<Auth['signInWithPassword']>;
+ signUp: (email: string, password: string) => ReturnType<Auth['signUp']>;
+ signInWithGoogle: (idToken: string, nonce: string) => ReturnType<Auth['signInWithIdToken']>;
+ signOut: () => ReturnType<Auth['signOut']>;
+}
+
+const AuthContext = createContext<AuthContextValue | null>(null);
+
+export function AuthProvider({ children }: { children: ReactNode }) {
+ const [session, setSession] = useState<Session | null | undefined>(undefined); // undefined = still loading
useEffect(() => {
supabase.auth.getSession().then(({ data: { session } }) => setSession(session));
@@ -14,14 +27,14 @@ export function AuthProvider({ children }) {
return () => subscription.unsubscribe();
}, []);
- const signIn = (email, password) =>
+ const signIn = (email: string, password: string) =>
supabase.auth.signInWithPassword({ email, password });
- const signUp = (email, password) =>
+ const signUp = (email: string, password: string) =>
supabase.auth.signUp({ email, password });
// the raw nonce lets supabase confirm the google token came from this sign-in
- const signInWithGoogle = (idToken, nonce) =>
+ const signInWithGoogle = (idToken: string, nonce: string) =>
supabase.auth.signInWithIdToken({ provider: 'google', token: idToken, nonce });
const signOut = () => supabase.auth.signOut();
@@ -33,7 +46,7 @@ export function AuthProvider({ children }) {
);
}
-export function useAuth() {
+export function useAuth(): AuthContextValue {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
return ctx;
diff --git a/frontend/src/hooks/use-account-analytics.ts b/frontend/src/hooks/use-account-analytics.ts
index 0e4d70f..0d6b4eb 100644
--- a/frontend/src/hooks/use-account-analytics.ts
+++ b/frontend/src/hooks/use-account-analytics.ts
@@ -2,12 +2,21 @@ import { useCallback, useEffect, useState } from 'react';
import { useAppContext } from '../context/AppContext';
import { api } from '../services/api';
+export interface AccountAnalyticsPayload<P, A> {
+ profile: P;
+ analytics: A;
+}
+
// pass a stable method such as api.getIGAnalytics so it loads once per account
-export function useAccountAnalytics(account, fetchAnalytics, label) {
+export function useAccountAnalytics<P, A>(
+ account: { id?: string } | null | undefined,
+ fetchAnalytics: (id: string) => Promise<AccountAnalyticsPayload<P, A>>,
+ label: string,
+) {
const { showToast } = useAppContext();
const [loading, setLoading] = useState(true);
- const [profile, setProfile] = useState(null);
- const [analytics, setAnalytics] = useState(null);
+ const [profile, setProfile] = useState<P | null>(null);
+ const [analytics, setAnalytics] = useState<A | null>(null);
const [refreshing, setRefreshing] = useState(false);
// keyed on the account id so a background refresh does not refetch analytics
@@ -20,7 +29,7 @@ export function useAccountAnalytics(account, fetchAnalytics, label) {
setProfile(data.profile);
setAnalytics(data.analytics);
} catch (err) {
- showToast(`Couldn't load ${label} analytics. ${err.message}`, 'error');
+ showToast(`Couldn't load ${label} analytics. ${(err as Error).message}`, 'error');
} finally {
setLoading(false);
}
@@ -31,11 +40,11 @@ export function useAccountAnalytics(account, fetchAnalytics, label) {
const handleRefresh = async () => {
setRefreshing(true);
try {
- await api.refreshAccount(accountId);
+ await api.refreshAccount(accountId!);
await loadAnalytics();
showToast(`${label} account refreshed`);
} catch (err) {
- showToast(`Refresh failed. ${err.message}`, 'error');
+ showToast(`Refresh failed. ${(err as Error).message}`, 'error');
} finally {
setRefreshing(false);
}
diff --git a/frontend/src/hooks/use-cloudinary-config.ts b/frontend/src/hooks/use-cloudinary-config.ts
index 864b0d7..c0a7780 100644
--- a/frontend/src/hooks/use-cloudinary-config.ts
+++ b/frontend/src/hooks/use-cloudinary-config.ts
@@ -1,7 +1,8 @@
import { useEffect, useState } from 'react';
import { api } from '../services/api';
+import type { CloudinaryConfigResponse } from '@shared/types/instagram.ts';
-async function fetchCloudinaryConfig() {
+async function fetchCloudinaryConfig(): Promise<CloudinaryConfigResponse | null> {
try {
const res = await api.getCloudinaryConfig();
return res?.success ? res : null;
@@ -12,8 +13,8 @@ async function fetchCloudinaryConfig() {
}
// reloadKey lets a page refetch the config when something it depends on changes
-export function useCloudinaryConfig(reloadKey) {
- const [config, setConfig] = useState(null);
+export function useCloudinaryConfig(reloadKey?: unknown): CloudinaryConfigResponse | null {
+ const [config, setConfig] = useState<CloudinaryConfigResponse | null>(null);
useEffect(() => {
const loadConfig = async () => {
diff --git a/frontend/src/hooks/use-command-palette-shortcut.ts b/frontend/src/hooks/use-command-palette-shortcut.ts
index b2301a1..68911b5 100644
--- a/frontend/src/hooks/use-command-palette-shortcut.ts
+++ b/frontend/src/hooks/use-command-palette-shortcut.ts
@@ -1,9 +1,10 @@
import { useEffect } from 'react';
+import type { Dispatch, SetStateAction } from 'react';
// Ctrl+K on Windows and Linux, Cmd+K on macOS, toggles the command palette from anywhere.
-export function useCommandPaletteShortcut(setOpen) {
+export function useCommandPaletteShortcut(setOpen: Dispatch<SetStateAction<boolean>>): void {
useEffect(() => {
- const onKeyDown = e => {
+ const onKeyDown = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault();
setOpen(open => !open);
diff --git a/frontend/src/hooks/use-mobile.ts b/frontend/src/hooks/use-mobile.ts
index 9c47a0d..15f7453 100644
--- a/frontend/src/hooks/use-mobile.ts
+++ b/frontend/src/hooks/use-mobile.ts
@@ -2,8 +2,8 @@ import * as React from "react"
const MOBILE_BREAKPOINT = 768
-export function useIsMobile() {
- const [isMobile, setIsMobile] = React.useState(undefined)
+export function useIsMobile(): boolean {
+ const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
diff --git a/frontend/src/hooks/use-smooth-theme.ts b/frontend/src/hooks/use-smooth-theme.ts
index f6b163c..11dc6fc 100644
--- a/frontend/src/hooks/use-smooth-theme.ts
+++ b/frontend/src/hooks/use-smooth-theme.ts
@@ -1,7 +1,7 @@
import { useCallback } from 'react';
import { useTheme } from 'next-themes';
-function resolve(theme) {
+function resolve(theme: string): string {
if (theme !== 'system') return theme;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
@@ -10,7 +10,7 @@ function resolve(theme) {
export function useSmoothTheme() {
const { theme, resolvedTheme, setTheme } = useTheme();
- const setThemeSmooth = useCallback(next => {
+ const setThemeSmooth = useCallback((next: string) => {
const apply = () => {
const resolved = resolve(next);
const root = document.documentElement;
diff --git a/frontend/src/layout/Header.tsx b/frontend/src/layout/Header.tsx
index dfb0b93..8a24f4f 100644
--- a/frontend/src/layout/Header.tsx
+++ b/frontend/src/layout/Header.tsx
@@ -9,7 +9,11 @@ import { routeTitle } from './navigation';
import { useAppContext } from '../context/AppContext';
import { cn } from '@/lib/utils';
-export default function TopBar({ onOpenPalette }) {
+export interface TopBarProps {
+ onOpenPalette: () => void;
+}
+
+export default function TopBar({ onOpenPalette }: TopBarProps) {
const location = useLocation();
const { loading, refreshAll, accounts } = useAppContext();
const { resolvedTheme, setTheme } = useSmoothTheme();
diff --git a/frontend/src/layout/Sidebar.tsx b/frontend/src/layout/Sidebar.tsx
index 70454b3..707c1b4 100644
--- a/frontend/src/layout/Sidebar.tsx
+++ b/frontend/src/layout/Sidebar.tsx
@@ -1,4 +1,5 @@
import React from 'react';
+import type { ReactNode } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { useSmoothTheme } from '@/hooks/use-smooth-theme';
import { Search, Tag, Settings, LogOut, Sun, Moon, Monitor, ChevronsUpDown, BookOpen } from 'lucide-react';
@@ -20,12 +21,18 @@ import { useAuth } from '../context/AuthContext';
const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);
-export default function AppSidebar({ categories, onOpenPalette, onSignOut }) {
+export interface AppSidebarProps {
+ categories: string[];
+ onOpenPalette: () => void;
+ onSignOut: () => void;
+}
+
+export default function AppSidebar({ categories, onOpenPalette, onSignOut }: AppSidebarProps) {
const location = useLocation();
const { accounts } = useAppContext();
const { setOpenMobile } = useSidebar();
- const nav = (path, label, children, tooltip = label) => (
+ const nav = (path: string, label: string, children: ReactNode, tooltip = label) => (
<SidebarMenuButton
isActive={isNavActive(path, location.pathname)}
tooltip={tooltip}
@@ -123,7 +130,7 @@ export default function AppSidebar({ categories, onOpenPalette, onSignOut }) {
);
}
-function UserMenu({ onSignOut }) {
+function UserMenu({ onSignOut }: { onSignOut: () => void }) {
const navigate = useNavigate();
const { user } = useAuth();
const { theme, setTheme } = useSmoothTheme();
diff --git a/frontend/src/layout/index.tsx b/frontend/src/layout/index.tsx
index cdbf722..de97401 100644
--- a/frontend/src/layout/index.tsx
+++ b/frontend/src/layout/index.tsx
@@ -15,7 +15,7 @@ export default function AppShell() {
const { accounts, refreshAll } = useAppContext();
const { signOut } = useAuth();
const [paletteOpen, setPaletteOpen] = useState(false);
- const [categories, setCategories] = useState([]);
+ const [categories, setCategories] = useState<string[]>([]);
useCommandPaletteShortcut(setPaletteOpen);
diff --git a/frontend/src/layout/navigation.ts b/frontend/src/layout/navigation.ts
index 269f4dd..b1e7c52 100644
--- a/frontend/src/layout/navigation.ts
+++ b/frontend/src/layout/navigation.ts
@@ -1,9 +1,33 @@
import {
LayoutDashboard, PlaySquare, Scissors, Clapperboard, MessagesSquare, Bookmark, Send, Users, Settings,
} from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
+
+export interface NavItem {
+ path: string;
+ label: string;
+ icon: LucideIcon;
+}
+
+export interface NavGroup {
+ label: string;
+ items: NavItem[];
+}
+
+// parent is null for the overview, which sits at the top of the breadcrumb
+export interface RouteTitle {
+ label: string;
+ parent: string | null;
+}
+
+interface DetailRoute {
+ prefix: string;
+ label: string;
+ parent: string;
+}
// Single source for navigation: the sidebar, top bar title and command palette all read from here.
-export const NAV_GROUPS = [
+export const NAV_GROUPS: NavGroup[] = [
{
label: 'Analytics',
items: [
@@ -30,7 +54,7 @@ export const NAV_GROUPS = [
},
];
-const DETAIL_ROUTES = [
+const DETAIL_ROUTES: DetailRoute[] = [
{ prefix: '/channel/', label: 'YouTube channel', parent: 'Analytics' },
{ prefix: '/instagram/', label: 'Instagram account', parent: 'Analytics' },
{ prefix: '/reddit/', label: 'Reddit account', parent: 'Analytics' },
@@ -38,12 +62,12 @@ const DETAIL_ROUTES = [
{ prefix: '/tracked-content/category/', label: 'Category', parent: 'Tracked content' },
];
-export function isNavActive(path, pathname) {
+export function isNavActive(path: string, pathname: string): boolean {
if (path === '/') return pathname === '/';
return pathname === path || pathname.startsWith(`${path}/`);
}
-export function routeTitle(pathname) {
+export function routeTitle(pathname: string): RouteTitle | null {
for (const group of NAV_GROUPS) {
const item = group.items.find(i => i.path === pathname);
if (item) return { label: item.label, parent: item.path === '/' ? null : group.label };
diff --git a/frontend/src/lib/accounts.ts b/frontend/src/lib/accounts.ts
index d206e65..ebda184 100644
--- a/frontend/src/lib/accounts.ts
+++ b/frontend/src/lib/accounts.ts
@@ -1,31 +1,56 @@
-export const PLATFORMS = ['youtube', 'instagram', 'reddit'];
+import type { Platform } from '../../../shared/types/domain.ts';
-export const PLATFORM_META = {
+export interface PlatformMeta {
+ label: string;
+ audienceLabel: string;
+ series: string;
+}
+
+// the account fields these helpers read; raw api accounts and normalized app accounts both fit
+export interface AccountFields {
+ id?: string;
+ platform?: string;
+ title?: string | null;
+ username?: string;
+ channelId?: string;
+ customUrl?: string;
+ thumbnail?: string;
+ profilePictureUrl?: string;
+ thumbnails?: { default?: string };
+ iconUrl?: string;
+ followersCount?: number;
+ totalKarma?: number;
+ subscriberCount?: number;
+}
+
+export const PLATFORMS: Platform[] = ['youtube', 'instagram', 'reddit'];
+
+export const PLATFORM_META: Record<Platform, PlatformMeta> = {
youtube: { label: 'YouTube', audienceLabel: 'subscribers', series: 'var(--chart-1)' },
instagram: { label: 'Instagram', audienceLabel: 'followers', series: 'var(--chart-3)' },
reddit: { label: 'Reddit', audienceLabel: 'karma', series: 'var(--chart-4)' },
};
// Accounts saved before multi-platform support have no platform field and are YouTube channels
-export function platformOf(account) {
+export function platformOf(account: AccountFields | null | undefined): Platform {
const platform = account?.platform;
return platform === 'instagram' || platform === 'reddit' ? platform : 'youtube';
}
-export function accountPath(account) {
+export function accountPath(account: AccountFields): string {
const platform = platformOf(account);
if (platform === 'instagram') return `/instagram/${account.id}`;
if (platform === 'reddit') return `/reddit/${account.id}`;
return `/channel/${account.id}`;
}
-export function accountName(account) {
+export function accountName(account: AccountFields | null | undefined): string {
if (!account) return '';
if (platformOf(account) === 'reddit') return `u/${account.username || ''}`;
return account.title || account.username || account.channelId || '';
}
-export function accountHandle(account) {
+export function accountHandle(account: AccountFields | null | undefined): string {
if (!account) return '';
const platform = platformOf(account);
if (platform === 'instagram') return account.username ? `@${account.username}` : '';
@@ -33,31 +58,31 @@ export function accountHandle(account) {
return account.customUrl || account.channelId || '';
}
-export function accountImage(account) {
+export function accountImage(account: AccountFields | null | undefined): string {
if (!account) return '';
return account.thumbnail || account.profilePictureUrl || account.thumbnails?.default || account.iconUrl || '';
}
-export function accountInitials(account) {
+export function accountInitials(account: AccountFields | null | undefined): string {
const source = account?.title || account?.username || '?';
return source.replace(/^u\//, '').slice(0, 2).toUpperCase();
}
-export function audienceOf(account) {
+export function audienceOf(account: AccountFields): number {
const platform = platformOf(account);
if (platform === 'instagram') return account.followersCount || 0;
if (platform === 'reddit') return account.totalKarma || 0;
return account.subscriberCount || 0;
}
-export function groupByPlatform(accounts) {
- const groups = { youtube: [], instagram: [], reddit: [] };
+export function groupByPlatform<T extends AccountFields>(accounts: T[] | null | undefined): Record<Platform, T[]> {
+ const groups: Record<Platform, T[]> = { youtube: [], instagram: [], reddit: [] };
for (const account of accounts || []) groups[platformOf(account)].push(account);
return groups;
}
// "2 YouTube, 1 Instagram" style summary, empty platforms omitted
-export function platformSummary(accounts) {
+export function platformSummary(accounts: AccountFields[] | null | undefined): string {
const groups = groupByPlatform(accounts);
return PLATFORMS
.filter(p => groups[p].length > 0)
diff --git a/frontend/src/lib/chart.ts b/frontend/src/lib/chart.ts
index d89abdf..03021b4 100644
--- a/frontend/src/lib/chart.ts
+++ b/frontend/src/lib/chart.ts
@@ -10,7 +10,7 @@ export const SERIES = {
export const SERIES_ORDER = [SERIES.primary, SERIES.neutral, SERIES.warm, SERIES.cool, SERIES.deep];
-export const seriesAt = index => SERIES_ORDER[index % SERIES_ORDER.length];
+export const seriesAt = (index: number): string => SERIES_ORDER[index % SERIES_ORDER.length];
export const axisTick = { fill: 'var(--ink-faint)', fontSize: 11, fontFamily: 'var(--font-sans)' };
diff --git a/frontend/src/lib/commandSearch.ts b/frontend/src/lib/commandSearch.ts
index 59ade48..34d8654 100644
--- a/frontend/src/lib/commandSearch.ts
+++ b/frontend/src/lib/commandSearch.ts
@@ -1,11 +1,23 @@
// Ranking for the command palette. Pure so it can be unit tested without a DOM.
-function normalize(text) {
+// the command fields ranking and grouping read; callers add their own
+export interface SearchCommand {
+ label: string;
+ group?: string;
+ keywords?: string[];
+}
+
+export interface CommandGroup<T extends SearchCommand> {
+ group: string;
+ items: T[];
+}
+
+function normalize(text: string | null | undefined): string {
return String(text || '').toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '').trim();
}
// Higher is better; 0 means no match. Every query word must appear in the label or keywords.
-export function scoreCommand(command, query) {
+export function scoreCommand(command: SearchCommand, query: string): number {
const needle = normalize(query);
if (!needle) return 1;
const label = normalize(command.label);
@@ -19,7 +31,7 @@ export function scoreCommand(command, query) {
return 20;
}
-export function filterCommands(commands, query, limit = 50) {
+export function filterCommands<T extends SearchCommand>(commands: T[], query: string, limit = 50): T[] {
return commands
.map((command, index) => ({ command, index, score: scoreCommand(command, query) }))
.filter(entry => entry.score > 0)
@@ -29,12 +41,12 @@ export function filterCommands(commands, query, limit = 50) {
}
// Groups in first-seen order so the palette keeps a stable layout while typing
-export function groupCommands(commands) {
- const groups = new Map();
+export function groupCommands<T extends SearchCommand>(commands: T[]): CommandGroup<T>[] {
+ const groups = new Map<string, T[]>();
for (const command of commands) {
const key = command.group || 'Other';
if (!groups.has(key)) groups.set(key, []);
- groups.get(key).push(command);
+ groups.get(key)!.push(command);
}
return [...groups.entries()].map(([group, items]) => ({ group, items }));
}
diff --git a/frontend/src/lib/contact.ts b/frontend/src/lib/contact.ts
index a188fb7..e6e31cc 100644
--- a/frontend/src/lib/contact.ts
+++ b/frontend/src/lib/contact.ts
@@ -1,7 +1,7 @@
// contact for access and scheduling help; self-hosters set VITE_ADMIN_EMAIL
-export const ADMIN_EMAIL = import.meta.env?.VITE_ADMIN_EMAIL || '[email protected]';
+export const ADMIN_EMAIL: string = import.meta.env?.VITE_ADMIN_EMAIL || '[email protected]';
-export function adminMailto(subject, body = '') {
+export function adminMailto(subject: string, body = ''): string {
const params = new URLSearchParams({ subject });
if (body) params.set('body', body);
// URLSearchParams encodes spaces as "+", which mail clients show literally
diff --git a/frontend/src/lib/googleIdentity.ts b/frontend/src/lib/googleIdentity.ts
index 75b7f61..92856c9 100644
--- a/frontend/src/lib/googleIdentity.ts
+++ b/frontend/src/lib/googleIdentity.ts
@@ -1,17 +1,49 @@
-export const GOOGLE_CLIENT_ID = import.meta.env?.VITE_GOOGLE_CLIENT_ID || '';
+export const GOOGLE_CLIENT_ID: string = import.meta.env?.VITE_GOOGLE_CLIENT_ID || '';
+
+export interface GoogleCredentialResponse {
+ credential: string;
+ select_by?: string;
+}
+
+export interface GoogleIdConfiguration {
+ client_id: string;
+ callback: (response: GoogleCredentialResponse) => void;
+ nonce?: string;
+ use_fedcm_for_button?: boolean;
+}
+
+export type GoogleButtonText = 'signin_with' | 'signup_with' | 'continue_with' | 'signin';
+
+export interface GoogleButtonConfiguration {
+ type?: 'standard' | 'icon';
+ theme?: 'outline' | 'filled_blue' | 'filled_black';
+ size?: 'large' | 'medium' | 'small';
+ shape?: 'rectangular' | 'pill' | 'circle' | 'square';
+ text?: GoogleButtonText;
+ logo_alignment?: 'left' | 'center';
+ width?: number;
+}
+
+// the part of google.accounts.id this app calls; Google ships no types package for it
+export interface GoogleAccountsId {
+ initialize(config: GoogleIdConfiguration): void;
+ renderButton(parent: HTMLElement, options: GoogleButtonConfiguration): void;
+}
+
+type GoogleWindow = Window & { google?: { accounts?: { id?: GoogleAccountsId } } };
const GSI_SRC = 'https://accounts.google.com/gsi/client';
-let scriptPromise = null;
+let scriptPromise: Promise<GoogleAccountsId> | null = null;
// Loads Google Identity Services once per page; later calls reuse the same promise.
-export function loadGoogleIdentity() {
- if (typeof window !== 'undefined' && window.google?.accounts?.id) return Promise.resolve(window.google.accounts.id);
+export function loadGoogleIdentity(): Promise<GoogleAccountsId> {
+ if (typeof window !== 'undefined' && (window as GoogleWindow).google?.accounts?.id) return Promise.resolve((window as GoogleWindow).google!.accounts!.id!);
if (!scriptPromise) {
- scriptPromise = new Promise((resolve, reject) => {
+ scriptPromise = new Promise<GoogleAccountsId>((resolve, reject) => {
const script = document.createElement('script');
script.src = GSI_SRC;
script.async = true;
- script.onload = () => (window.google?.accounts?.id ? resolve(window.google.accounts.id) : reject(new Error('Google sign-in did not start.')));
+ script.onload = () => ((window as GoogleWindow).google?.accounts?.id ? resolve((window as GoogleWindow).google!.accounts!.id!) : reject(new Error('Google sign-in did not start.')));
script.onerror = () => {
scriptPromise = null;
reject(new Error('Google sign-in could not load. Check your connection or any content blocker, then try again.'));
@@ -22,13 +54,13 @@ export function loadGoogleIdentity() {
return scriptPromise;
}
-export async function sha256Hex(text) {
+export async function sha256Hex(text: string): Promise<string> {
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
return Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('');
}
// supabase matches the raw nonce to the token's hash, so a token cannot replay
-export async function createNonce() {
+export async function createNonce(): Promise<{ raw: string; hashed: string }> {
const bytes = crypto.getRandomValues(new Uint8Array(32));
const raw = btoa(String.fromCharCode(...bytes)).replace(/[+/=]/g, '');
return { raw, hashed: await sha256Hex(raw) };
diff --git a/frontend/src/lib/holdProgress.ts b/frontend/src/lib/holdProgress.ts
index 3061182..1e3e691 100644
--- a/frontend/src/lib/holdProgress.ts
+++ b/frontend/src/lib/holdProgress.ts
@@ -2,6 +2,15 @@
export const DEFAULT_HOLD_MS = 1200;
+export interface HoldControllerOptions {
+ duration?: number;
+ onProgress?: (progress: number) => void;
+ onComplete?: () => void;
+ now?: () => number;
+ requestFrame?: (callback: () => void) => number;
+ cancelFrame?: (id: number) => void;
+}
+
export function createHoldController({
duration = DEFAULT_HOLD_MS,
onProgress = () => {},
@@ -9,9 +18,9 @@ export function createHoldController({
now = () => performance.now(),
requestFrame = cb => requestAnimationFrame(cb),
cancelFrame = id => cancelAnimationFrame(id),
-} = {}) {
- let startedAt = null;
- let frame = null;
+}: HoldControllerOptions = {}) {
+ let startedAt: number | null = null;
+ let frame: number | null = null;
let done = false;
function tick() {
diff --git a/frontend/src/lib/library.ts b/frontend/src/lib/library.ts
index 29c1170..edb29d7 100644
--- a/frontend/src/lib/library.ts
+++ b/frontend/src/lib/library.ts
@@ -1,18 +1,33 @@
// Filtering, sorting and paging shared by the content library pages. Pure, no JSX.
-export function parseIsoDuration(iso) {
+export function parseIsoDuration(iso: string | null | undefined): number {
if (!iso || iso === 'P0D') return 0;
const parts = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
if (!parts) return 0;
- return (parseInt(parts[1] || 0, 10) * 3600) + (parseInt(parts[2] || 0, 10) * 60) + parseInt(parts[3] || 0, 10);
+ return (parseInt((parts[1] || 0) as string, 10) * 3600) + (parseInt((parts[2] || 0) as string, 10) * 60) + parseInt((parts[3] || 0) as string, 10);
}
// (likes + comments) / views as a percentage string, matching the backend's two-decimal format
-export function engagementPercent(views, likes, comments) {
- return (views || 0) > 0 ? (((likes || 0) + (comments || 0)) / views * 100).toFixed(2) : '0.00';
+export function engagementPercent(views: number | null | undefined, likes: number | null | undefined, comments: number | null | undefined): string {
+ return (views || 0) > 0 ? (((likes || 0) + (comments || 0)) / views! * 100).toFixed(2) : '0.00';
}
-export const VIEW_TIERS = [
+// a filter band; min is inclusive and max exclusive, a missing bound is open
+export interface Tier {
+ label: string;
+ value: string;
+ min?: number;
+ max?: number;
+}
+
+export interface PageSlice<T> {
+ items: T[];
+ page: number;
+ pageCount: number;
+ offset: number;
+}
+
+export const VIEW_TIERS: Tier[] = [
{ label: 'Any views', value: 'all' },
{ label: 'Over 1M', value: 'viral', min: 1000000 },
{ label: '100K to 1M', value: 'high', min: 100000, max: 1000000 },
@@ -20,7 +35,7 @@ export const VIEW_TIERS = [
{ label: 'Under 10K', value: 'low', max: 10000 },
];
-export const LIKE_TIERS = [
+export const LIKE_TIERS: Tier[] = [
{ label: 'Any likes', value: 'all' },
{ label: 'Over 100K', value: 'viral', min: 100000 },
{ label: '10K to 100K', value: 'high', min: 10000, max: 100000 },
@@ -28,19 +43,19 @@ export const LIKE_TIERS = [
{ label: 'Under 1K', value: 'low', max: 1000 },
];
-export function filterByTier(items, tiers, tierValue, field) {
+export function filterByTier<K extends string, T extends Partial<Record<K, number | null>>>(items: T[], tiers: Tier[], tierValue: string, field: K): T[] {
if (tierValue === 'all') return items;
const tier = tiers.find(t => t.value === tierValue);
if (!tier) return items;
return items.filter(item => {
- const value = item[field] || 0;
+ const value = (item[field] || 0) as number;
if (tier.min != null && value < tier.min) return false;
if (tier.max != null && value >= tier.max) return false;
return true;
});
}
-export function pageSlice(items, page, perPage) {
+export function pageSlice<T>(items: T[], page: number, perPage: number): PageSlice<T> {
const pageCount = Math.max(1, Math.ceil(items.length / perPage));
const current = Math.min(Math.max(1, page), pageCount);
return {
@@ -51,7 +66,7 @@ export function pageSlice(items, page, perPage) {
};
}
-export function matchesText(values, query) {
+export function matchesText(values: unknown[], query: string): boolean {
const needle = query.trim().toLowerCase();
if (!needle) return true;
return values.some(value => typeof value === 'string' && value.toLowerCase().includes(needle));
diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts
index b20bf01..50b28b2 100644
--- a/frontend/src/lib/utils.ts
+++ b/frontend/src/lib/utils.ts
@@ -1,6 +1,7 @@
import { clsx } from "clsx";
+import type { ClassValue } from "clsx";
import { twMerge } from "tailwind-merge"
-export function cn(...inputs) {
+export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 47742c1..2339d59 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -3,7 +3,7 @@ import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
-ReactDOM.createRoot(document.getElementById('root')).render(
+ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
diff --git a/frontend/src/pages/Login.tsx b/frontend/src/pages/Login.tsx
index 4c3e016..9b81792 100644
--- a/frontend/src/pages/Login.tsx
+++ b/frontend/src/pages/Login.tsx
@@ -1,4 +1,5 @@
import { useState } from 'react';
+import type { FormEvent } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { BookOpen } from 'lucide-react';
@@ -6,12 +7,19 @@ import { useAuth } from '../context/AuthContext';
import { Button } from '@/components/ui/button';
import { Logo } from '@/components/brand/Logo';
import GoogleSignInButton from '@/components/GoogleSignInButton';
+import type { GoogleButtonText } from '@/lib/googleIdentity';
import { GOOGLE_CLIENT_ID } from '@/lib/googleIdentity';
import LoginBrandPanel from './LoginBrandPanel';
import LoginForm from './LoginForm';
import { LOGIN_COPY, PRIVACY_URL } from './loginCopy';
+import type { LoginMode } from './loginCopy';
-function GoogleOption({ text, onCredential }) {
+interface GoogleOptionProps {
+ text: GoogleButtonText;
+ onCredential: (idToken: string, nonce: string) => void;
+}
+
+function GoogleOption({ text, onCredential }: GoogleOptionProps) {
return (
<div className="flex flex-col gap-6">
<GoogleSignInButton
@@ -31,7 +39,7 @@ function GoogleOption({ text, onCredential }) {
export default function Login() {
const { signIn, signUp, signInWithGoogle } = useAuth();
const navigate = useNavigate();
- const [mode, setMode] = useState('login');
+ const [mode, setMode] = useState<LoginMode>('login');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
// kept here, above the keyed panel, so only the mode switch link resets it
@@ -40,7 +48,7 @@ export default function Login() {
const isLogin = mode === 'login';
const copy = LOGIN_COPY[mode];
- async function handleSubmit(e) {
+ async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
setLoading(true);
try {
@@ -55,20 +63,20 @@ export default function Login() {
setMode('login');
}
} catch (err) {
- toast.error(isLogin ? `Couldn't sign in. ${err.message}` : `Couldn't create the account. ${err.message}`);
+ toast.error(isLogin ? `Couldn't sign in. ${(err as Error).message}` : `Couldn't create the account. ${(err as Error).message}`);
} finally {
setLoading(false);
}
}
- async function handleGoogleCredential(idToken, nonce) {
+ async function handleGoogleCredential(idToken: string, nonce: string) {
setLoading(true);
try {
const { error } = await signInWithGoogle(idToken, nonce);
if (error) throw error;
navigate('/');
} catch (err) {
- toast.error(`Couldn't sign in with Google. ${err.message}`);
+ toast.error(`Couldn't sign in with Google. ${(err as Error).message}`);
} finally {
setLoading(false);
}
diff --git a/frontend/src/pages/LoginForm.tsx b/frontend/src/pages/LoginForm.tsx
index dda9639..29f407d 100644
--- a/frontend/src/pages/LoginForm.tsx
+++ b/frontend/src/pages/LoginForm.tsx
@@ -1,12 +1,27 @@
+import type { FormEvent } from 'react';
import { ArrowRight, Eye, EyeOff } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import { FieldRow } from '@/components/DetailPanel';
+import type { LoginCopy } from './loginCopy';
+
+export interface LoginFormProps {
+ isLogin: boolean;
+ copy: LoginCopy;
+ email: string;
+ password: string;
+ onEmailChange: (value: string) => void;
+ onPasswordChange: (value: string) => void;
+ showPassword: boolean;
+ onTogglePassword: () => void;
+ loading: boolean;
+ onSubmit: (e: FormEvent<HTMLFormElement>) => void;
+}
export default function LoginForm({
isLogin, copy, email, password, onEmailChange, onPasswordChange, showPassword, onTogglePassword, loading, onSubmit,
-}) {
+}: LoginFormProps) {
return (
<form onSubmit={onSubmit} className="flex flex-col gap-4">
<FieldRow label="Email" htmlFor="email">
diff --git a/frontend/src/pages/loginCopy.ts b/frontend/src/pages/loginCopy.ts
index bebad37..da8bab1 100644
--- a/frontend/src/pages/loginCopy.ts
+++ b/frontend/src/pages/loginCopy.ts
@@ -1,6 +1,20 @@
+import type { GoogleButtonText } from '@/lib/googleIdentity';
+
export const PRIVACY_URL = 'https://blog.ujjwal.fyi/privacy/';
-export const LOGIN_COPY = {
+export type LoginMode = 'login' | 'signup';
+
+export interface LoginCopy {
+ title: string;
+ lead: string;
+ submit: string;
+ busy: string;
+ switchPrompt: string;
+ switchAction: string;
+ google: GoogleButtonText;
+}
+
+export const LOGIN_COPY: Record<LoginMode, LoginCopy> = {
login: {
title: 'Welcome back',
lead: 'Sign in to see every channel in one place.',
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts
index 9110748..71b291c 100644
--- a/frontend/src/services/api.ts
+++ b/frontend/src/services/api.ts
@@ -1,8 +1,34 @@
import { supabase } from '../lib/supabase';
+import type {
+ AccountListResponse, AccountRefreshAllResponse, AccountResponse, ApiFailure, GitHubSettingsRequest,
+ GitHubSettingsResponse, HealthResponse, KeysStatusResponse, OverviewResponse, ScheduledPostDeleteAllResponse,
+ ScheduledPostListResponse, ScheduledPostRequest, ScheduledPostResponse, ScheduledPostUpdateRequest,
+ ScheduledPostUpdateResponse, ScheduledPublishRunResponse, SuccessMessageResponse, SuccessResponse,
+ TrackedContentItem, TrackedContentUpdateRequest, YouTubeAccountAddResponse,
+} from '@shared/types/domain.ts';
+import type {
+ CloudinaryConfigResponse, InstagramAnalyticsResponse, InstagramAuthUrlResponse, InstagramContainerStatusResponse,
+ InstagramMediaPublishResponse, InstagramMediaResponse, InstagramPublishingLimitResponse, InstagramPublishRequest,
+ InstagramPublishResponse, InstagramTokenRefreshResponse,
+} from '@shared/types/instagram.ts';
+import type { RedditCacheData, RedditPost } from '@shared/types/reddit.ts';
+import type {
+ ResolveChannelResponse, YouTubeAnalyticsPayload, YouTubeComparisonResponse, YouTubeVideosResponse,
+} from '@shared/types/youtube.ts';
const API = import.meta.env.VITE_API_URL || 'http://localhost:8787/api';
-async function request(path, options = {}) {
+// the fields request() reads from any body to decide whether it failed
+interface ResponseStatusFields {
+ success?: boolean;
+ message?: string;
+ error?: string;
+}
+
+// callers that check success also handle a failure body the server sent with a 2xx status; success bodies carry no message
+export type ApiResult<T> = (T & { message?: undefined }) | ApiFailure;
+
+async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const { data: { session } } = await supabase.auth.getSession();
const token = session?.access_token;
@@ -13,39 +39,61 @@ async function request(path, options = {}) {
},
...options,
});
- const data = await res.json();
+ const data = await res.json() as T & ResponseStatusFields;
if (!res.ok && !data.success) throw new Error(data.message || data.error || 'Request failed');
return data;
}
const CLOUDINARY_API = 'https://api.cloudinary.com/v1_1';
-const UPLOAD_ERROR_MESSAGES = {
+export type UploadErrorReason = 'network' | 'rejected';
+
+interface UploadErrorDetails {
+ cloudinaryMessage?: string;
+ parseMessage?: string;
+}
+
+// what uploadToCloudinary rejects with
+export type UploadError = Error & UploadErrorDetails & { reason: UploadErrorReason };
+
+export type CloudinaryUploadConfig = Pick<CloudinaryConfigResponse, 'cloudName' | 'uploadPreset'>;
+
+export interface UploadOptions {
+ onProgress?: (percent: number) => void;
+}
+
+// the parts of a Cloudinary upload response the client reads
+interface CloudinaryUploadBody {
+ secure_url?: string;
+ error?: { message?: string };
+}
+
+const UPLOAD_ERROR_MESSAGES: Record<UploadErrorReason, string> = {
network: 'The upload lost its network connection',
rejected: 'Upload failed',
};
// callers read the reason and details so each page keeps its own wording
-function uploadError(reason, details = {}) {
+function uploadError(reason: UploadErrorReason, details: UploadErrorDetails = {}): UploadError {
return Object.assign(new Error(UPLOAD_ERROR_MESSAGES[reason]), { reason, ...details });
}
-function readUploadError(responseText) {
+function readUploadError(responseText: string): UploadErrorDetails {
try {
- return { cloudinaryMessage: JSON.parse(responseText).error?.message };
+ return { cloudinaryMessage: (JSON.parse(responseText) as CloudinaryUploadBody).error?.message };
} catch (err) {
- return { parseMessage: err.message };
+ return { parseMessage: (err as Error).message };
}
}
// the browser posts straight to Cloudinary so the Worker never handles binaries
-function uploadToCloudinary(file, cloudConfig, { onProgress } = {}) {
+function uploadToCloudinary(file: File, cloudConfig: CloudinaryUploadConfig, { onProgress }: UploadOptions = {}): Promise<string> {
const formData = new FormData();
formData.append('file', file);
formData.append('upload_preset', cloudConfig.uploadPreset);
const type = file.type.startsWith('video/') ? 'video' : 'image';
const xhr = new XMLHttpRequest();
- return new Promise((resolve, reject) => {
+ return new Promise<string>((resolve, reject) => {
if (onProgress) {
xhr.upload.addEventListener('progress', e => {
if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100));
@@ -53,7 +101,7 @@ function uploadToCloudinary(file, cloudConfig, { onProgress } = {}) {
}
xhr.addEventListener('load', () => {
if (xhr.status >= 200 && xhr.status < 300) {
- resolve(JSON.parse(xhr.responseText).secure_url);
+ resolve((JSON.parse(xhr.responseText) as CloudinaryUploadBody).secure_url as string);
return;
}
reject(uploadError('rejected', readUploadError(xhr.responseText)));
@@ -65,13 +113,13 @@ function uploadToCloudinary(file, cloudConfig, { onProgress } = {}) {
}
// screenshots need no progress events and show cloudinary's own error message
-async function uploadImage(file, cloudConfig) {
+async function uploadImage(file: File, cloudConfig: CloudinaryUploadConfig): Promise<string> {
const formData = new FormData();
formData.append('file', file);
formData.append('upload_preset', cloudConfig.uploadPreset);
const res = await fetch(`${CLOUDINARY_API}/${cloudConfig.cloudName}/image/upload`, { method: 'POST', body: formData });
- const json = await res.json();
+ const json = await res.json() as CloudinaryUploadBody;
if (!res.ok || !json.secure_url) {
throw new Error(json.error?.message || 'Cloudinary did not return an image URL');
}
@@ -79,66 +127,66 @@ async function uploadImage(file, cloudConfig) {
}
export const api = {
- health: () => request('/health'),
+ health: () => request<HealthResponse>('/health'),
// Server key status - all keys are env vars, this just returns configured: true/false
- getKeys: () => request('/keys'),
+ getKeys: () => request<KeysStatusResponse>('/keys'),
- getAccounts: () => request('/accounts'),
- addAccount: (input) => request('/accounts', { method: 'POST', body: JSON.stringify({ input }) }),
- deleteAccount: (id) => request(`/accounts/${id}`, { method: 'DELETE' }),
- refreshAccount: (id) => request(`/accounts/${id}/refresh`, { method: 'POST' }),
- refreshAll: () => request('/accounts/refresh-all', { method: 'POST' }),
+ getAccounts: () => request<AccountListResponse>('/accounts'),
+ addAccount: (input: string) => request<YouTubeAccountAddResponse>('/accounts', { method: 'POST', body: JSON.stringify({ input }) }),
+ deleteAccount: (id: string) => request<SuccessResponse>(`/accounts/${id}`, { method: 'DELETE' }),
+ refreshAccount: (id: string) => request<AccountResponse>(`/accounts/${id}/refresh`, { method: 'POST' }),
+ refreshAll: () => request<AccountRefreshAllResponse>('/accounts/refresh-all', { method: 'POST' }),
// Instagram OAuth - gets the auth URL to redirect the browser to
- getInstagramAuthUrl: () => request('/auth/instagram/url'),
+ getInstagramAuthUrl: () => request<InstagramAuthUrlResponse>('/auth/instagram/url'),
- addInstagramAccount: (accessToken) => request('/accounts/instagram', { method: 'POST', body: JSON.stringify({ accessToken }) }),
- refreshIGToken: (id) => request(`/accounts/${id}/refresh-ig-token`, { method: 'POST' }),
- getIGAnalytics: (id) => request(`/accounts/${id}/ig-analytics`),
- getIGMedia: (id) => request(`/accounts/${id}/ig-media`),
+ addInstagramAccount: (accessToken: string) => request<AccountResponse>('/accounts/instagram', { method: 'POST', body: JSON.stringify({ accessToken }) }),
+ refreshIGToken: (id: string) => request<InstagramTokenRefreshResponse>(`/accounts/${id}/refresh-ig-token`, { method: 'POST' }),
+ getIGAnalytics: (id: string) => request<InstagramAnalyticsResponse>(`/accounts/${id}/ig-analytics`),
+ getIGMedia: (id: string) => request<InstagramMediaResponse>(`/accounts/${id}/ig-media`),
// Channel URL/ID resolution
- resolveChannel: (input) => request('/resolve-channel', { method: 'POST', body: JSON.stringify({ input }) }),
+ resolveChannel: (input: string) => request<ResolveChannelResponse>('/resolve-channel', { method: 'POST', body: JSON.stringify({ input }) }),
// Analytics (YouTube)
- getAnalytics: (id) => request(`/accounts/${id}/analytics`),
- getVideos: (id) => request(`/accounts/${id}/videos`),
+ getAnalytics: (id: string) => request<YouTubeAnalyticsPayload>(`/accounts/${id}/analytics`),
+ getVideos: (id: string) => request<YouTubeVideosResponse>(`/accounts/${id}/videos`),
- getComparison: () => request('/comparison'),
+ getComparison: () => request<YouTubeComparisonResponse>('/comparison'),
- getCloudinaryConfig: () => request('/cloudinary-config'),
+ getCloudinaryConfig: () => request<ApiResult<CloudinaryConfigResponse>>('/cloudinary-config'),
uploadToCloudinary,
uploadImage,
// Instagram Publishing
- getIGPublishingLimit: (id) => request(`/accounts/${id}/ig-publishing-limit`),
- createIGContainer: (id, data) => request(`/accounts/${id}/ig-publish`, { method: 'POST', body: JSON.stringify(data) }),
- getIGContainerStatus: (containerId, accountId) => request(`/ig-container/${containerId}/status?accountId=${accountId}`),
- publishIGContainer: (id, containerId) => request(`/accounts/${id}/ig-media-publish`, { method: 'POST', body: JSON.stringify({ containerId }) }),
+ getIGPublishingLimit: (id: string) => request<InstagramPublishingLimitResponse>(`/accounts/${id}/ig-publishing-limit`),
+ createIGContainer: (id: string, data: InstagramPublishRequest) => request<ApiResult<InstagramPublishResponse>>(`/accounts/${id}/ig-publish`, { method: 'POST', body: JSON.stringify(data) }),
+ getIGContainerStatus: (containerId: string, accountId: string) => request<InstagramContainerStatusResponse>(`/ig-container/${containerId}/status?accountId=${accountId}`),
+ publishIGContainer: (id: string, containerId: string) => request<ApiResult<InstagramMediaPublishResponse>>(`/accounts/${id}/ig-media-publish`, { method: 'POST', body: JSON.stringify({ containerId }) }),
- addRedditAccount: (username, cookie) => request('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, cookie }) }),
- getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),
- getRedditPosts: (id) => request(`/accounts/${id}/reddit-posts`),
+ addRedditAccount: (username: string, cookie: string) => request<AccountResponse>('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, cookie }) }),
+ getRedditAnalytics: (id: string) => request<RedditCacheData>(`/accounts/${id}/reddit-analytics`),
+ getRedditPosts: (id: string) => request<RedditPost[]>(`/accounts/${id}/reddit-posts`),
// Overview dashboard (tracked content + per-account analytics cache)
- getOverview: () => request('/overview'),
+ getOverview: () => request<OverviewResponse>('/overview'),
// Tracked Content (Reddit posts and YouTube videos)
- getTrackedContent: () => request('/tracked-content'),
- addTrackedContent: (url, accountId, label, category) => request('/tracked-content', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
- updateTrackedContent: (id, updates) => request(`/tracked-content/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
- deleteTrackedContent: (id) => request(`/tracked-content/${id}`, { method: 'DELETE' }),
- refreshTrackedContent: (id) => request(`/tracked-content/${id}/refresh`, { method: 'POST' }),
+ getTrackedContent: () => request<TrackedContentItem[]>('/tracked-content'),
+ addTrackedContent: (url: string, accountId: string | null, label: string, category: string) => request<TrackedContentItem>('/tracked-content', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
+ updateTrackedContent: (id: string, updates: TrackedContentUpdateRequest) => request<TrackedContentItem>(`/tracked-content/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
+ deleteTrackedContent: (id: string) => request<SuccessResponse>(`/tracked-content/${id}`, { method: 'DELETE' }),
+ refreshTrackedContent: (id: string) => request<TrackedContentItem>(`/tracked-content/${id}/refresh`, { method: 'POST' }),
// GitHub settings
- getGithubSettings: () => request('/settings/github'),
- saveGithubSettings: (data) => request('/settings/github', { method: 'PUT', body: JSON.stringify(data) }),
-
- getScheduledPosts: () => request('/scheduled-posts'),
- createScheduledPost: (data) => request('/scheduled-posts', { method: 'POST', body: JSON.stringify(data) }),
- updateScheduledPost: (id, data) => request(`/scheduled-posts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
- deleteScheduledPost: (id) => request(`/scheduled-posts/${id}`, { method: 'DELETE' }),
- deleteAllScheduledPosts: () => request('/scheduled-posts', { method: 'DELETE' }),
- processScheduled: () => request('/process-scheduled'),
+ getGithubSettings: () => request<GitHubSettingsResponse>('/settings/github'),
+ saveGithubSettings: (data: GitHubSettingsRequest) => request<SuccessResponse>('/settings/github', { method: 'PUT', body: JSON.stringify(data) }),
+
+ getScheduledPosts: () => request<ApiResult<ScheduledPostListResponse>>('/scheduled-posts'),
+ createScheduledPost: (data: ScheduledPostRequest) => request<ApiResult<ScheduledPostResponse>>('/scheduled-posts', { method: 'POST', body: JSON.stringify(data) }),
+ updateScheduledPost: (id: string, data: ScheduledPostUpdateRequest) => request<ApiResult<ScheduledPostUpdateResponse>>(`/scheduled-posts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
+ deleteScheduledPost: (id: string) => request<SuccessMessageResponse>(`/scheduled-posts/${id}`, { method: 'DELETE' }),
+ deleteAllScheduledPosts: () => request<ScheduledPostDeleteAllResponse>('/scheduled-posts', { method: 'DELETE' }),
+ processScheduled: () => request<ScheduledPublishRunResponse>('/process-scheduled'),
};
diff --git a/frontend/src/utils/formatters.ts b/frontend/src/utils/formatters.ts
index 08748bc..7cdf435 100644
--- a/frontend/src/utils/formatters.ts
+++ b/frontend/src/utils/formatters.ts
@@ -1,4 +1,9 @@
-export function fmtNum(n) {
+import type { SafeAccount } from '../../../shared/types/domain.ts';
+
+export type NumberLike = number | string | null | undefined;
+export type DateLike = string | number | Date | null | undefined;
+
+export function fmtNum(n: NumberLike): string {
if (n == null) return '0';
n = Number(n);
if (n >= 1e9) return (n / 1e9).toFixed(1) + 'B';
@@ -8,26 +13,26 @@ export function fmtNum(n) {
}
// For counts a platform can hide (YouTube likes, disabled comments): null means hidden, not zero.
-export function fmtCount(n) {
+export function fmtCount(n: NumberLike): string {
return n == null ? 'Hidden' : fmtNum(n);
}
-export function fmtNumFull(n) {
+export function fmtNumFull(n: NumberLike): string {
if (n == null) return '0';
return Number(n).toLocaleString();
}
-export function fmtDate(d) {
+export function fmtDate(d: DateLike): string {
if (!d) return '';
return new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
}
-export function fmtDateShort(d) {
+export function fmtDateShort(d: DateLike): string {
if (!d) return '';
return new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}
-export function fmtDuration(seconds) {
+export function fmtDuration(seconds: number | null | undefined): string {
if (!seconds) return '0:00';
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
@@ -36,12 +41,12 @@ export function fmtDuration(seconds) {
return `${minutes}:${String(secs).padStart(2, '0')}`;
}
-export function fmtPercent(n) {
+export function fmtPercent(n: NumberLike): string {
if (n == null) return '0%';
return Number(n).toFixed(1) + '%';
}
-export function timeAgo(date) {
+export function timeAgo(date: DateLike): string {
if (!date) return 'Never';
const diff = Date.now() - new Date(date).getTime();
const mins = Math.floor(diff / 60000);
@@ -55,7 +60,7 @@ export function timeAgo(date) {
return `${months}mo ago`;
}
-export const CATEGORY_MAP = {
+export const CATEGORY_MAP: Record<string, string> = {
'1': 'Film & Animation', '2': 'Autos & Vehicles', '10': 'Music',
'15': 'Pets & Animals', '17': 'Sports', '18': 'Short Movies',
'19': 'Travel & Events', '20': 'Gaming', '21': 'Videoblogging',
@@ -69,8 +74,25 @@ export const CATEGORY_MAP = {
'42': 'Shorts', '43': 'Shows', '44': 'Trailers',
};
+// fields that accounts saved by older versions can still carry
+export interface LegacyAccountFields {
+ name?: string;
+ channelTitle?: string;
+ thumbnailUrl?: string;
+ thumbnail?: string;
+ currentStats?: { subscribers?: number; views?: number; videos?: number };
+}
+
+export type AccountInput = SafeAccount & LegacyAccountFields;
+
+// an account as AppContext keeps it; instagram titles fall back to igUserId, which can be null
+export type AppAccount = Omit<AccountInput, 'title' | 'thumbnail'> & {
+ title?: string | null;
+ thumbnail: string;
+};
+
// Normalize account data (handles YouTube, Instagram, and Reddit)
-export function normalizeAccount(acct) {
+export function normalizeAccount(acct: AccountInput): AppAccount {
if (!acct) return acct;
if (acct.platform === 'instagram') {
return {
diff --git a/frontend/src/utils/instagramContent.ts b/frontend/src/utils/instagramContent.ts
index 4e33807..6121e0a 100644
--- a/frontend/src/utils/instagramContent.ts
+++ b/frontend/src/utils/instagramContent.ts
@@ -1,25 +1,32 @@
import { fmtNum } from './formatters.ts';
+import type { InstagramContentType, InstagramMedia } from '../../../shared/types/instagram.ts';
-export const IG_CONTENT_TYPES = ['reel', 'post', 'video'];
+export interface IGContentTypeMeta {
+ label: string;
+ plural: string;
+ color: string;
+}
+
+export const IG_CONTENT_TYPES: InstagramContentType[] = ['reel', 'post', 'video'];
// Colours are brand chart series so they follow the theme
-export const IG_CONTENT_TYPE_META = {
+export const IG_CONTENT_TYPE_META: Record<InstagramContentType, IGContentTypeMeta> = {
reel: { label: 'Reel', plural: 'Reels', color: 'var(--chart-1)' },
post: { label: 'Post', plural: 'Posts', color: 'var(--chart-3)' },
video: { label: 'Video', plural: 'Videos', color: 'var(--chart-4)' },
};
-export function igContentTypeMeta(type) {
- return IG_CONTENT_TYPE_META[type] ?? IG_CONTENT_TYPE_META.post;
+export function igContentTypeMeta(type: string | null | undefined): IGContentTypeMeta {
+ return IG_CONTENT_TYPE_META[type as InstagramContentType] ?? IG_CONTENT_TYPE_META.post;
}
// Instagram omits views when insights are unavailable, so null means "not reported", not zero
-export function fmtIGViews(views) {
+export function fmtIGViews(views: number | null | undefined): string {
return typeof views === 'number' ? fmtNum(views) : '-';
}
// image posts can lack a thumbnail url, so they fall back to the image itself
-export function igThumbnail(item) {
+export function igThumbnail(item: Pick<InstagramMedia, 'contentType'> & Partial<Pick<InstagramMedia, 'thumbnailUrl' | 'mediaUrl'>>): string | undefined {
if (item.contentType === 'post') return item.thumbnailUrl || item.mediaUrl;
return item.thumbnailUrl;
}
diff --git a/frontend/src/utils/trackedContent.ts b/frontend/src/utils/trackedContent.ts
index 7dce7fa..bf9464e 100644
--- a/frontend/src/utils/trackedContent.ts
+++ b/frontend/src/utils/trackedContent.ts
@@ -1,33 +1,44 @@
+// the tracked post fields these helpers read
+export interface TrackedMetrics {
+ contentType?: string;
+ viewCount?: number | null;
+ manualViews?: number | null;
+ likeCount?: number | null;
+ commentCount?: number | null;
+ score?: number;
+ numComments?: number;
+}
+
// youtube reports views; reddit dropped view_count in 2018 so they are typed in
-export function trackedViews(item) {
+export function trackedViews(item: TrackedMetrics | null | undefined): number {
if (!item) return 0;
if (item.contentType === 'youtube') return item.viewCount ?? 0;
return item.manualViews ?? 0;
}
// false for reddit posts with no views entered, so the ui can tell it from zero
-export function hasTrackedViews(item) {
+export function hasTrackedViews(item: TrackedMetrics | null | undefined): boolean {
if (!item) return false;
if (item.contentType === 'youtube') return item.viewCount !== undefined && item.viewCount !== null;
return item.manualViews !== undefined && item.manualViews !== null;
}
-export function detectContentType(url) {
+export function detectContentType(url: string | null | undefined): 'reddit' | 'youtube' | null {
const lower = (url || '').toLowerCase();
if (lower.includes('reddit.com') || lower.includes('redd.it')) return 'reddit';
if (lower.includes('youtube.com') || lower.includes('youtu.be')) return 'youtube';
return null;
}
-export function isRedditItem(item) {
+export function isRedditItem(item: TrackedMetrics | null | undefined): boolean {
return (item?.contentType || 'reddit') === 'reddit';
}
// YouTube likes and Reddit karma play the same role, so lists sort and total them together
-export function trackedEngagement(item) {
+export function trackedEngagement(item: TrackedMetrics): number {
return item.contentType === 'youtube' ? (item.likeCount ?? 0) : (item.score ?? 0);
}
-export function trackedComments(item) {
+export function trackedComments(item: TrackedMetrics): number {
return item.contentType === 'youtube' ? (item.commentCount ?? 0) : (item.numComments ?? 0);
}
diff --git a/frontend/src/vite-env.d.ts b/frontend/src/vite-env.d.ts
new file mode 100644
index 0000000..aaecc25
--- /dev/null
+++ b/frontend/src/vite-env.d.ts
@@ -0,0 +1,13 @@
+/// <reference types="vite/client" />
+
+interface ImportMetaEnv {
+ readonly VITE_SUPABASE_URL?: string;
+ readonly VITE_SUPABASE_ANON_KEY?: string;
+ readonly VITE_API_URL?: string;
+ readonly VITE_ADMIN_EMAIL?: string;
+ readonly VITE_GOOGLE_CLIENT_ID?: string;
+}
+
+interface ImportMeta {
+ readonly env: ImportMetaEnv;
+}
diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.json
index b18d619..e3271ce 100644
--- a/frontend/tsconfig.node.json
+++ b/frontend/tsconfig.node.json
@@ -1,8 +1,18 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
- "lib": ["ES2024", "DOM", "DOM.Iterable"],
- "types": ["node"]
+ "lib": [
+ "ES2024",
+ "DOM",
+ "DOM.Iterable"
+ ],
+ "types": [
+ "node"
+ ]
},
- "include": ["vite.config.ts", "tests"]
+ "include": [
+ "vite.config.ts",
+ "tests",
+ "src/vite-env.d.ts"
+ ]
}