Skip to content

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

feat(analytics): design every data state and keep the view in the address

spacesdrive1074c3ef7a39
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.md
index 362dc9e..a0bb9bc 100644
--- a/docs/architecture/frontend/API_LAYER.md
+++ b/docs/architecture/frontend/API_LAYER.md
@@ -69,6 +69,13 @@ export const api = {
The response types are imported with `import type` from `@shared/types/*.ts`, so nothing from `shared/` reaches the bundle.
+### Fresh reads
+
+`getVideos(id, fresh?)`, `getIGMedia(id, fresh?)` and `getRedditAnalytics(id, fresh?)` read the server's cache by
+default. Passing `fresh = true` adds `?fresh=1`, which skips the cache; pages send it only from their Refresh button,
+so opening a page never spends platform quota by itself. The Reddit posts pages read `getRedditAnalytics`, which
+carries the posts with their `fetchedAt`; the old `getRedditPosts` method was removed.
+
## Adding a New API Method
1. Add or reuse the request and response types in `shared/types/`.
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index a940a2e..3640975 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -85,13 +85,14 @@ frontend/src/
│ │ ├── publishConstants.ts <- Content types, statuses, intervals, caption limit
│ │ └── publishHelpers.ts, scheduleHelpers.ts, queueHelpers.ts <- Pure helpers with *.test.ts
│ ├── automations/
-│ │ ├── Automations.tsx <- Page: server notices, counts, account controls, rules, activity, the rule dialog
+│ │ ├── Automations.tsx <- Page: server notices, counts, account controls, rules, activity
│ │ ├── AutomationNotices.tsx <- Webhook not set up, or replies paused on the server
│ │ ├── AutomationMetrics.tsx, AutomationAccounts.tsx, AutomationRules.tsx, AutomationActivity.tsx
-│ │ ├── RuleDialog.tsx, RuleMediaPicker.tsx, RulePublicReplies.tsx, RulePreview.tsx <- Rule form (private and public reply sections), post picker, public wordings, thread and message preview, keyword test
+│ │ ├── RuleEditorPage.tsx <- The rule editor at /automations/rules/new and /automations/rules/:id: sticky Save bar, draft, leave warning
+│ │ ├── RuleMediaPicker.tsx, RulePublicReplies.tsx, RulePreview.tsx <- Rule form (private and public reply sections), post picker, public wordings, thread and message preview, keyword test
│ │ ├── useAutomations.ts <- Overview and every rule and account action, with toasts
│ │ ├── useAutomationActivity.ts <- Filters, counts, activity pages and retry
-│ │ ├── useRuleForm.ts <- Rule dialog state, the account's posts, the test call
+│ │ ├── useRuleForm.ts <- Rule editor state, draft, field problems, the account's posts, the test call
│ │ └── automationData.ts <- Pure status labels, filters, summary, form conversion and checks (automationData.test.ts)
│ ├── settings/
│ │ ├── Settings.tsx <- Page: loads server settings, then renders each section; keeps the #hash scroll
@@ -133,23 +134,36 @@ it is named `karma` (`rdKarma`, `avgKarma`, `redditKarma`).
"Virality Score" and "Consistency Score" are separate computed indices, not karma, and keep
the word "score".
-## Shared Chart Component
+## Shared Chart Components
-`components/MetricAreaChart.tsx` renders a single-series area chart with the project's axis,
-grid, gradient, and tooltip styling. Use it instead of hand-rolling a Recharts `AreaChart`:
+Every chart sits in a `ChartFigure`: the plot, a one-sentence summary under it, and a Show table toggle with the
+same numbers. Use the shared components instead of hand-rolling a Recharts chart:
+
+| Component | Use it for |
+|---|---|
+| `ChartPanel` | A titled box around any Recharts chart; pass `summary` and `table` (`{ caption, columns, rows }`). A string title also names the focusable plot |
+| `MetricAreaChart` | One value over time (months, weeks); writes its own summary and table |
+| `RankingBarChart` | Separate things ranked by one number (accounts, categories, videos, tags): horizontal bars, largest first, an optional `kind` per bar for mixed units |
```tsx
-<MetricAreaChart
- data={[{ name: 'Item', karma: 42 }]}
- dataKey="karma"
- label="Karma"
- color={SERIES.warm} // from @/lib/chart
- emptyMessage="Track content to compare karma"
-/>
+<RankingBarChart rows={[{ name: 'Origami', value: 420 }]} label="Views" title="Views by category" color={CATEGORY_SERIES} />
```
-Each instance generates its own gradient id via `useId()`, so multiple charts on one page
-never collide.
+`lib/chart.ts` has `trendSummary` and `rankingSummary` for the sentence. Each `MetricAreaChart` generates its own
+gradient id via `useId()`, so multiple charts on one page never collide.
+
+## Shared Library Pieces
+
+The library pages (Videos, Shorts, Instagram content, Reddit posts, Tracked content) are built from the same parts:
+
+| Piece | Job |
+|---|---|
+| `features/analytics/useLibrarySources.ts` | Loads one list per account, keyed on the account ids; returns the results, failed accounts, the oldest `fetchedAt`, `initialLoading`, `refreshing` and a `refresh` that asks for fresh data |
+| `features/analytics/useLibraryParams.ts` | Search, filters, sort, layout and page in the address; a filter change returns to page 1 in one history step |
+| `SearchField`, `FilterChips`, `SortSelect` | The controls, in that order, with the account select between search and sort |
+| `ActiveFilters`, `NoResults`, `Pager` | Result count and removable filters, the no-match state that echoes the search, and the announced page range |
+| `FailedSourcesAlert`, `DataFreshness`, `RefreshButton` | Accounts that failed to load, the data's age, and the one Refresh control |
+| `lib/metricIcons.ts` | One icon per meaning (`METRIC_ICONS`, `IG_TYPE_ICONS`) |
## Image Lightbox
@@ -220,7 +234,7 @@ Each page manages its own loading/data/error state. Pages do not write to `AppCo
| Tracked Content | `/tracked-content` | Monitor Reddit posts and YouTube videos; add by URL, assign categories, bulk edit, per-row refresh |
| Tracked Category | `/tracked-content/category/:name` | Detailed per-category analytics; YouTube section (views, likes, comments, bar chart, table) and Reddit section (score, ratio, comments, bar chart, table) rendered separately |
| Video Explorer | `/videos/:id` | YouTube video library with search and sort |
-| Publish | `/upload` | Publish or schedule to Instagram, bulk upload, and the scheduled post queue |
+| Publish | `/publish` (`/upload` redirects) | Publish or schedule to Instagram, bulk upload, and the scheduled post queue |
| Automations | `/automations` | Keyword rules that answer Instagram comments with a private reply, a public reply under the comment or both, account pause and comment events, counts and the activity of both replies with separate retries (`docs/architecture/data-flows/AUTOMATION.md`) |
| Settings | `/settings` | Theme, server key status, who sets up scheduling, the optional GitHub backup guide |
| Documentation | `/docs/*` | Not a page in the app: `DocsRedirect` sends the visitor to the same path on the public docs at `https://twiligent.ujjwal.fyi/docs`. The Documentation item in the sidebar user menu and Open documentation in the command palette open the docs in a new tab |
diff --git a/frontend/src/components/ActiveFilters.tsx b/frontend/src/components/ActiveFilters.tsx
new file mode 100644
index 0000000..46ff6d2
--- /dev/null
+++ b/frontend/src/components/ActiveFilters.tsx
@@ -0,0 +1,45 @@
+import { X } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import LiveStatus from './LiveStatus';
+
+export interface ActiveFilter {
+ key: string;
+ label: string;
+ onRemove: () => void;
+}
+
+export interface ActiveFiltersProps {
+ // "12 of 340 videos", announced whenever it changes
+ countLabel: string;
+ filters: ActiveFilter[];
+ onClearAll: () => void;
+}
+
+// the result count and every filter in force, each removable, so nobody has to remember what they narrowed
+export default function ActiveFilters({ countLabel, filters, onClearAll }: ActiveFiltersProps) {
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <LiveStatus message={countLabel} visible className="text-small font-medium text-ink-muted tabular-nums" />
+ {filters.length > 0 && (
+ <ul aria-label="Active filters" className="flex flex-wrap items-center gap-1.5">
+ {filters.map(filter => (
+ <li key={filter.key}>
+ <button
+ type="button"
+ onClick={filter.onRemove}
+ aria-label={`Remove filter: ${filter.label}`}
+ className="inline-flex h-7 items-center gap-1 rounded-pill border border-line-strong/50 bg-surface-raised pr-2 pl-2.5 text-caption font-medium text-ink transition-colors hover:bg-surface-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
+ >
+ {filter.label}
+ <X className="size-3 stroke-[1.75] text-ink-muted" aria-hidden="true" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ {filters.length > 1 && (
+ <Button variant="ghost" size="xs" onClick={onClearAll}>Clear all</Button>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/components/ChartFigure.tsx b/frontend/src/components/ChartFigure.tsx
new file mode 100644
index 0000000..93a2446
--- /dev/null
+++ b/frontend/src/components/ChartFigure.tsx
@@ -0,0 +1,74 @@
+import React, { useId, useState } from 'react';
+import { Table as TableIcon, LineChart } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import { cn } from '@/lib/utils';
+
+export interface ChartTableColumn {
+ key: string;
+ label: string;
+ numeric?: boolean;
+ format?: (value: unknown) => string;
+}
+
+export interface ChartTableSpec {
+ caption: string;
+ columns: ChartTableColumn[];
+ rows: readonly object[];
+}
+
+export interface ChartFigureProps {
+ summary?: string;
+ table?: ChartTableSpec;
+ children: React.ReactNode;
+ className?: string;
+}
+
+function cellText(column: ChartTableColumn, row: object): string {
+ const value = (row as Record<string, unknown>)[column.key];
+ if (column.format) return column.format(value);
+ return value == null ? '' : String(value);
+}
+
+// a chart with its takeaway in words and its numbers as a table, for anyone who cannot read the plot
+export default function ChartFigure({ summary, table, children, className }: ChartFigureProps) {
+ const [showTable, setShowTable] = useState(false);
+ const summaryId = useId();
+ return (
+ <figure className={cn('flex flex-col gap-2', className)} aria-describedby={summary ? summaryId : undefined}>
+ {showTable && table ? (
+ <Table aria-label={table.caption} containerClassName="max-h-80 overflow-y-auto">
+ <TableHeader>
+ <TableRow>
+ {table.columns.map(column => (
+ <TableHead key={column.key} className={cn(column.numeric && 'text-right')}>{column.label}</TableHead>
+ ))}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {table.rows.map((row, index) => (
+ <TableRow key={index}>
+ {table.columns.map(column => (
+ <TableCell key={column.key} className={cn(column.numeric && 'text-right')}>{cellText(column, row)}</TableCell>
+ ))}
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ ) : (
+ children
+ )}
+ {(summary || table) && (
+ <figcaption className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 px-2">
+ {summary ? <p id={summaryId} className="max-w-prose text-small text-ink-muted">{summary}</p> : <span />}
+ {table && (
+ <Button variant="ghost" size="sm" onClick={() => setShowTable(shown => !shown)} aria-pressed={showTable}>
+ {showTable ? <LineChart data-icon="inline-start" /> : <TableIcon data-icon="inline-start" />}
+ {showTable ? 'Show chart' : 'Show table'}
+ </Button>
+ )}
+ </figcaption>
+ )}
+ </figure>
+ );
+}
diff --git a/frontend/src/components/ChartPanel.tsx b/frontend/src/components/ChartPanel.tsx
index fe73289..4a46384 100644
--- a/frontend/src/components/ChartPanel.tsx
+++ b/frontend/src/components/ChartPanel.tsx
@@ -1,27 +1,36 @@
import React from 'react';
import { ResponsiveContainer } from 'recharts';
import SurfaceBox from './SurfaceBox';
+import ChartFigure from './ChartFigure';
+import type { ChartTableSpec } from './ChartFigure';
-// Titled chart container. Pass `empty` to show a quiet message instead of an empty plot.
+// Titled chart container. Pass `empty` to show a quiet message instead of an empty plot, `summary` for the takeaway
+// in words and `table` for the same numbers as a table.
export interface ChartPanelProps {
title?: React.ReactNode;
subheader?: React.ReactNode;
+ summary?: string;
+ table?: ChartTableSpec;
height?: number;
empty?: boolean;
emptyMessage?: React.ReactNode;
className?: string;
- children: React.ReactNode;
+ children: React.ReactElement<{ title?: string; desc?: string }>;
}
-export default function ChartPanel({ title, subheader, height = 280, empty = false, emptyMessage = 'Not enough data yet', className, children }: ChartPanelProps) {
+export default function ChartPanel({ title, subheader, summary, table, height = 280, empty = false, emptyMessage = 'Not enough data yet', className, children }: ChartPanelProps) {
+ // the svg itself is a keyboard stop (recharts' accessibility layer), so it needs a name of its own
+ const plot = typeof title === 'string' ? React.cloneElement(children, { title, desc: summary }) : children;
return (
<SurfaceBox title={title} subheader={subheader} className={className} contentClassName="px-3 pt-4 pb-3">
{empty ? (
<p className="flex items-center justify-center text-small text-ink-faint" style={{ height }}>{emptyMessage}</p>
) : (
- <ResponsiveContainer width="100%" height={height} debounce={200}>
- {children}
- </ResponsiveContainer>
+ <ChartFigure summary={summary} table={table}>
+ <ResponsiveContainer width="100%" height={height} debounce={200}>
+ {plot}
+ </ResponsiveContainer>
+ </ChartFigure>
)}
</SurfaceBox>
);
diff --git a/frontend/src/components/ColumnHint.tsx b/frontend/src/components/ColumnHint.tsx
index bd676aa..f9d2473 100644
--- a/frontend/src/components/ColumnHint.tsx
+++ b/frontend/src/components/ColumnHint.tsx
@@ -1,8 +1,9 @@
import type React from 'react';
import { Info } from 'lucide-react';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
-// A table header label with an info button that explains what the column measures.
+// A table header label with an info button that explains what the column measures. A popover, not a tooltip,
+// so the explanation also opens with a tap or a key press.
export interface ColumnHintProps {
label: string;
hint: React.ReactNode;
@@ -10,16 +11,22 @@ export interface ColumnHintProps {
export default function ColumnHint({ label, hint }: ColumnHintProps) {
return (
- <span className="inline-flex items-center justify-end gap-1">
+ <span className="inline-flex items-center justify-end gap-0.5">
{label}
- <Tooltip>
- <TooltipTrigger
- render={<button type="button" aria-label={`About ${label}`} className="rounded-full text-ink-faint transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-ring" />}
+ <Popover>
+ <PopoverTrigger
+ render={
+ <button
+ type="button"
+ aria-label={`About ${label}`}
+ className="inline-flex size-6 items-center justify-center rounded-full text-ink-faint transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-ring"
+ />
+ }
>
- <Info className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent className="max-w-64 text-left">{hint}</TooltipContent>
- </Tooltip>
+ <Info className="size-3.5" aria-hidden="true" />
+ </PopoverTrigger>
+ <PopoverContent className="max-w-64 text-left text-sm font-normal whitespace-normal text-ink">{hint}</PopoverContent>
+ </Popover>
</span>
);
}
diff --git a/frontend/src/components/DataFreshness.tsx b/frontend/src/components/DataFreshness.tsx
new file mode 100644
index 0000000..571917e
--- /dev/null
+++ b/frontend/src/components/DataFreshness.tsx
@@ -0,0 +1,25 @@
+import { Clock } from 'lucide-react';
+import RelativeTime from './RelativeTime';
+import type { DateLike } from '@/utils/formatters';
+import { cn } from '@/lib/utils';
+
+export interface DataFreshnessProps {
+ fetchedAt: DateLike;
+ // "oldest channel" when several sources load at different times and the oldest is shown
+ qualifier?: string;
+ className?: string;
+}
+
+// cached analytics can be hours old, so every data view says how old its numbers are
+export default function DataFreshness({ fetchedAt, qualifier, className }: DataFreshnessProps) {
+ if (!fetchedAt) return null;
+ return (
+ <p className={cn('flex items-center gap-1.5 text-small text-ink-muted', className)}>
+ <Clock className="size-3.5 shrink-0 stroke-[1.75]" aria-hidden="true" />
+ <span>
+ <RelativeTime date={fetchedAt} prefix="Data from " />
+ {qualifier && <span> ({qualifier})</span>}
+ </span>
+ </p>
+ );
+}
diff --git a/frontend/src/components/FailedSourcesAlert.tsx b/frontend/src/components/FailedSourcesAlert.tsx
new file mode 100644
index 0000000..9869d15
--- /dev/null
+++ b/frontend/src/components/FailedSourcesAlert.tsx
@@ -0,0 +1,28 @@
+import { AlertTriangle } from 'lucide-react';
+import { Alert, AlertAction, AlertDescription, AlertTitle } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
+import { failureSummary } from '@/lib/library';
+import type { SourceFailure } from '@/lib/library';
+
+export interface FailedSourcesAlertProps {
+ failures: readonly SourceFailure[];
+ total: number;
+ noun: string;
+ onRetry: () => void;
+ retrying?: boolean;
+}
+
+// totals below leave these accounts out, so the page says which ones and why
+export default function FailedSourcesAlert({ failures, total, noun, onRetry, retrying = false }: FailedSourcesAlertProps) {
+ if (failures.length === 0) return null;
+ return (
+ <Alert variant="warning" role="alert">
+ <AlertTriangle aria-hidden="true" />
+ <AlertTitle>Some {noun} are missing</AlertTitle>
+ <AlertDescription>{failureSummary(failures, total, noun)} The figures below leave them out.</AlertDescription>
+ <AlertAction>
+ <Button size="xs" variant="outline" onClick={onRetry} disabled={retrying}>{retrying ? 'Retrying' : 'Try again'}</Button>
+ </AlertAction>
+ </Alert>
+ );
+}
diff --git a/frontend/src/components/FilterChips.tsx b/frontend/src/components/FilterChips.tsx
index 58fe1e6..43542bf 100644
--- a/frontend/src/components/FilterChips.tsx
+++ b/frontend/src/components/FilterChips.tsx
@@ -1,6 +1,7 @@
-import React from 'react';
+import React, { useMemo } from 'react';
import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
+import { useRovingRadio } from './useRovingRadio';
// Single-select chip group. Options are { value, label, icon?, count? }.
export interface FilterChipOption<V extends string = string> {
@@ -19,6 +20,8 @@ export interface FilterChipsProps<V extends string = string> {
}
export default function FilterChips<V extends string = string>({ options, value, onChange, className, label = 'Filter' }: FilterChipsProps<V>) {
+ const values = useMemo(() => options.map(option => option.value), [options]);
+ const { onKeyDown, tabIndexOf } = useRovingRadio(values, value, onChange);
return (
<div role="radiogroup" aria-label={label} className={cn('flex flex-wrap items-center gap-1.5', className)}>
{options.map(option => {
@@ -30,16 +33,18 @@ export default function FilterChips<V extends string = string>({ options, value,
type="button"
role="radio"
aria-checked={active}
+ tabIndex={tabIndexOf(option.value)}
onClick={() => onChange(option.value)}
+ onKeyDown={onKeyDown}
className={cn(
'inline-flex h-(--control-h) items-center gap-1.5 rounded-field border px-3 text-sm font-medium transition-colors duration-(--duration-fast)',
'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
active
? 'border-brand/40 bg-brand-soft text-brand-text'
- : 'border-line-control bg-surface text-ink-muted hover:bg-surface-hover hover:text-ink',
+ : 'border-input bg-surface text-ink-muted hover:bg-surface-hover hover:text-ink',
)}
>
- {Icon && <Icon className="size-3.5 stroke-[1.75]" />}
+ {Icon && <Icon className="size-3.5 stroke-[1.75]" aria-hidden="true" />}
{option.label}
{option.count !== undefined && (
<span className={cn('tabular-nums', active ? 'text-brand-text/80' : 'text-ink-faint')}>{option.count}</span>
diff --git a/frontend/src/components/ListRow.tsx b/frontend/src/components/ListRow.tsx
index 43baf45..290bfe8 100644
--- a/frontend/src/components/ListRow.tsx
+++ b/frontend/src/components/ListRow.tsx
@@ -56,8 +56,8 @@ export default function ListRow({
>
{leading}
<span className="flex min-w-0 flex-1 flex-col">
- <span className="truncate text-sm font-medium text-ink">{title}</span>
- {meta && <span className="truncate text-caption text-ink-faint">{meta}</span>}
+ <span className="truncate text-sm font-medium text-ink" title={typeof title === 'string' ? title : undefined}>{title}</span>
+ {meta && <span className="truncate text-caption text-ink-faint" title={typeof meta === 'string' ? meta : undefined}>{meta}</span>}
</span>
{trailing && <span className="flex shrink-0 items-center gap-2 text-small text-ink-muted tabular-nums">{trailing}</span>}
</Element>
diff --git a/frontend/src/components/MediaCard.tsx b/frontend/src/components/MediaCard.tsx
index c570e3c..0d380a3 100644
--- a/frontend/src/components/MediaCard.tsx
+++ b/frontend/src/components/MediaCard.tsx
@@ -14,7 +14,7 @@ export interface MediaChipProps {
export function MediaChip({ children, className }: MediaChipProps) {
return (
- <span className={cn('inline-flex items-center gap-1 rounded-pill bg-media-scrim/75 px-2 py-0.5 text-[0.6875rem] font-semibold text-on-media backdrop-blur-sm [&_svg]:size-3', className)}>
+ <span className={cn('inline-flex items-center gap-1 rounded-pill bg-media-scrim/75 px-2 py-0.5 text-caption font-semibold text-on-media backdrop-blur-sm [&_svg]:size-3', className)}>
{children}
</span>
);
@@ -29,6 +29,8 @@ export interface MediaCardProps {
topRight?: React.ReactNode;
bottomRight?: React.ReactNode;
href?: string;
+ // the link's name when the visible title is missing or shortened
+ linkLabel?: string;
className?: string;
}
@@ -41,6 +43,7 @@ export default function MediaCard({
topRight,
bottomRight,
href,
+ linkLabel,
className,
}: MediaCardProps) {
const Element = href ? 'a' : 'div';
@@ -49,6 +52,7 @@ export default function MediaCard({
href={href}
target={href ? '_blank' : undefined}
rel={href ? 'noopener noreferrer' : undefined}
+ aria-label={href ? linkLabel : undefined}
className={cn(
'group flex flex-col overflow-hidden rounded-card border border-line bg-surface-raised transition-colors duration-(--duration-fast)',
href && 'hover:border-line-strong/50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
@@ -60,7 +64,7 @@ export default function MediaCard({
<img src={image} alt="" loading="lazy" className="size-full object-cover transition-transform duration-(--duration-slow) ease-(--ease-fold) group-hover:scale-[1.02]" />
) : (
<div className="flex size-full items-center justify-center text-ink-faint">
- <ImageOff className="size-6 stroke-[1.5]" />
+ <ImageOff className="size-6 stroke-[1.5]" aria-hidden="true" />
</div>
)}
{topLeft && <div className="absolute top-2 left-2">{topLeft}</div>}
@@ -68,7 +72,7 @@ export default function MediaCard({
{bottomRight && <div className="absolute right-2 bottom-2">{bottomRight}</div>}
</div>
<div className="flex flex-1 flex-col gap-1.5 p-3">
- {title && <p className="line-clamp-2 text-small font-medium leading-snug text-ink">{title}</p>}
+ {title && <p className="line-clamp-2 text-small font-medium leading-snug text-ink" title={typeof title === 'string' ? title : undefined}>{title}</p>}
{meta && <div className="mt-auto flex items-center gap-3 text-caption text-ink-faint tabular-nums [&_svg]:size-3 [&_svg]:stroke-[1.75]">{meta}</div>}
</div>
</Element>
diff --git a/frontend/src/components/MetricAreaChart.tsx b/frontend/src/components/MetricAreaChart.tsx
index 16c7ab5..d23fa5f 100644
--- a/frontend/src/components/MetricAreaChart.tsx
+++ b/frontend/src/components/MetricAreaChart.tsx
@@ -5,12 +5,16 @@ import {
} from 'recharts';
import { fmtNum, fmtNumFull } from '../utils/formatters';
import type { NumberLike } from '../utils/formatters';
-import { axisProps, gridProps, tooltipStyle } from '@/lib/chart';
+import { axisProps, gridProps, tooltipStyle, trendSummary } from '@/lib/chart';
+import ChartFigure from './ChartFigure';
+// a value over time; for a ranking of separate things use RankingBarChart, since a line implies a sequence
export interface MetricAreaChartProps {
data?: readonly object[] | null;
dataKey: string;
label: string;
+ // names the plot and its table; defaults to the label
+ title?: string;
color?: string;
height?: number;
emptyMessage?: React.ReactNode;
@@ -20,6 +24,7 @@ export default function MetricAreaChart({
data,
dataKey,
label,
+ title = label,
color = 'var(--chart-1)',
height = 240,
emptyMessage = 'No data to display',
@@ -31,33 +36,50 @@ export default function MetricAreaChart({
return <p className="py-8 text-center text-small text-ink-faint">{emptyMessage}</p>;
}
+ const rows = data as Record<string, unknown>[];
+ const points = rows.map(row => ({ name: String(row.name ?? ''), value: Number(row[dataKey] ?? 0) }));
+ const summary = trendSummary(points, fmtNum, label.toLowerCase());
+
return (
- <ResponsiveContainer width="100%" height={height} debounce={200}>
- <AreaChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
- <defs>
- <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor={color} stopOpacity={0.2} />
- <stop offset="95%" stopColor={color} stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="name" {...axisProps} interval="preserveStartEnd" />
- <YAxis {...axisProps} tickFormatter={fmtNum} width={48} allowDecimals={false} />
- <ReTooltip
- contentStyle={tooltipStyle}
- cursor={{ stroke: 'var(--line-strong)' }}
- formatter={(v) => [fmtNumFull(v as NumberLike), label]}
- />
- <Area
- type="monotone"
- dataKey={dataKey}
- stroke={color}
- strokeWidth={2}
- fill={`url(#${gradientId})`}
- dot={{ r: 3, fill: color, stroke: 'var(--surface-raised)', strokeWidth: 2 }}
- activeDot={{ r: 6 }}
- />
- </AreaChart>
- </ResponsiveContainer>
+ <ChartFigure
+ summary={summary}
+ table={{
+ caption: title,
+ columns: [
+ { key: 'name', label: 'Period' },
+ { key: dataKey, label, numeric: true, format: value => fmtNumFull(value as NumberLike) },
+ ],
+ rows,
+ }}
+ >
+ <ResponsiveContainer width="100%" height={height} debounce={200}>
+ <AreaChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }} title={title} desc={summary}>
+ <defs>
+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor={color} stopOpacity={0.2} />
+ <stop offset="95%" stopColor={color} stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid {...gridProps} vertical={false} />
+ <XAxis dataKey="name" {...axisProps} interval="preserveStartEnd" />
+ <YAxis {...axisProps} tickFormatter={fmtNum} width={48} allowDecimals={false} />
+ <ReTooltip
+ contentStyle={tooltipStyle}
+ cursor={{ stroke: 'var(--line-strong)' }}
+ formatter={(v) => [fmtNumFull(v as NumberLike), label]}
+ />
+ <Area
+ type="monotone"
+ dataKey={dataKey}
+ name={label}
+ stroke={color}
+ strokeWidth={2}
+ fill={`url(#${gradientId})`}
+ dot={{ r: 3, fill: color, stroke: 'var(--surface-raised)', strokeWidth: 2 }}
+ activeDot={{ r: 6 }}
+ />
+ </AreaChart>
+ </ResponsiveContainer>
+ </ChartFigure>
);
}
diff --git a/frontend/src/components/MetricBox.tsx b/frontend/src/components/MetricBox.tsx
index ec05b6a..664a39f 100644
--- a/frontend/src/components/MetricBox.tsx
+++ b/frontend/src/components/MetricBox.tsx
@@ -2,33 +2,52 @@ import React from 'react';
import { TrendingUp, TrendingDown } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';
+import { trendTone } from '@/lib/library';
export interface MetricBoxProps {
icon?: React.ReactNode;
label: React.ReactNode;
value?: React.ReactNode;
subtitle?: React.ReactNode;
+ // the time frame the value covers, such as "All time" or "Last 30 days", so a number is never read without one
+ period?: string;
loading?: boolean;
small?: boolean;
trend?: number;
+ // what the trend compares against, such as "vs last month"
+ trendComparison?: string;
+ // shown in place of the subtitle, next to a trend
trendLabel?: React.ReactNode;
+ // false for metrics where a rise is bad, so the colour follows the meaning, not the sign
+ upIsGood?: boolean;
highlight?: boolean;
className?: string;
}
+function textOf(node: React.ReactNode): string | undefined {
+ return typeof node === 'string' ? node : undefined;
+}
+
// Quiet metric tile: neutral icon, large tabular value, label and one line of context.
export default function MetricBox({
icon,
label,
value,
subtitle,
+ period,
loading,
small,
trend,
+ trendComparison,
trendLabel,
+ upIsGood = true,
highlight = false,
className,
}: MetricBoxProps) {
+ const tone = trend === undefined ? 'neutral' : trendTone(trend, upIsGood);
+ const detail = trendLabel ?? subtitle;
+ const comparison = trendComparison ?? textOf(trendLabel) ?? '';
+ const context = [period, textOf(detail)].filter(Boolean).join(' · ');
return (
<div
className={cn(
@@ -41,6 +60,7 @@ export default function MetricBox({
<span className="flex min-w-0 items-center gap-2 text-small font-medium text-ink-muted">
{icon && (
<span
+ aria-hidden="true"
className={cn(
'flex shrink-0 items-center justify-center [&_svg]:size-4 [&_svg]:stroke-[1.75]',
highlight ? 'text-brand-text' : 'text-ink-faint',
@@ -49,12 +69,21 @@ export default function MetricBox({
{icon}
</span>
)}
- <span className="truncate">{label}</span>
+ <span className="truncate" title={textOf(label)}>{label}</span>
</span>
{trend !== undefined && !loading && (
- <span className={cn('flex items-center gap-0.5 text-caption font-semibold', trend >= 0 ? 'text-success' : 'text-danger')}>
- {trend >= 0 ? <TrendingUp className="size-3" /> : <TrendingDown className="size-3" />}
+ <span
+ className={cn(
+ 'flex items-center gap-0.5 text-caption font-semibold',
+ tone === 'good' && 'text-success',
+ tone === 'bad' && 'text-danger',
+ tone === 'neutral' && 'text-ink-muted',
+ )}
+ >
+ {trend >= 0 ? <TrendingUp className="size-3" aria-hidden="true" /> : <TrendingDown className="size-3" aria-hidden="true" />}
+ <span className="sr-only">{trend >= 0 ? 'Up' : 'Down'} </span>
{Math.abs(trend)}%
+ {comparison && <span className="sr-only"> {comparison}</span>}
</span>
)}
</div>
@@ -68,14 +97,18 @@ export default function MetricBox({
<div className="flex min-w-0 flex-col gap-1">
<p
className={cn(
- 'font-heading font-semibold tracking-[-0.02em] tabular-nums text-ink leading-none',
- small ? 'text-xl' : 'text-[1.75rem]',
+ 'font-heading font-semibold tabular-nums text-ink leading-none',
+ small ? 'text-page-title' : 'text-metric',
)}
>
{value}
</p>
- {(subtitle || trendLabel) && (
- <p className="truncate text-caption text-ink-faint">{trendLabel || subtitle}</p>
+ {(period || detail) && (
+ <p className="truncate text-caption text-ink-faint" title={context || undefined}>
+ {period && <span>{period}</span>}
+ {period && detail && <span aria-hidden="true"> · </span>}
+ {detail}
+ </p>
)}
</div>
)}
diff --git a/frontend/src/components/MetricDetails.tsx b/frontend/src/components/MetricDetails.tsx
new file mode 100644
index 0000000..f18e98e
--- /dev/null
+++ b/frontend/src/components/MetricDetails.tsx
@@ -0,0 +1,46 @@
+import React from 'react';
+import SurfaceBox from './SurfaceBox';
+
+export interface MetricDetail {
+ label: string;
+ value: React.ReactNode;
+ // what the number means, for derived scores a reader cannot guess
+ hint?: string;
+}
+
+export interface MetricDetailGroup {
+ title: string;
+ items: MetricDetail[];
+}
+
+export interface MetricDetailsProps {
+ title?: string;
+ subheader?: React.ReactNode;
+ groups: MetricDetailGroup[];
+}
+
+// the supporting numbers as a quiet list, so the headline tiles above stay few and the page has one entry point
+export default function MetricDetails({ title = 'Details', subheader, groups }: MetricDetailsProps) {
+ return (
+ <SurfaceBox title={title} subheader={subheader}>
+ <div className="grid grid-cols-1 gap-x-8 gap-y-6 md:grid-cols-2 xl:grid-cols-3">
+ {groups.map(group => (
+ <section key={group.title} aria-label={group.title} className="flex flex-col gap-2">
+ <h3 className="text-small font-semibold text-ink-muted">{group.title}</h3>
+ <dl className="flex flex-col divide-y divide-divider">
+ {group.items.map(item => (
+ <div key={item.label} className="flex items-baseline justify-between gap-4 py-2">
+ <dt className="min-w-0 text-sm text-ink">
+ {item.label}
+ {item.hint && <span className="block text-caption text-ink-faint">{item.hint}</span>}
+ </dt>
+ <dd className="shrink-0 text-sm font-semibold text-ink tabular-nums">{item.value}</dd>
+ </div>
+ ))}
+ </dl>
+ </section>
+ ))}
+ </div>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/components/NoResults.tsx b/frontend/src/components/NoResults.tsx
new file mode 100644
index 0000000..8cd0aa7
--- /dev/null
+++ b/frontend/src/components/NoResults.tsx
@@ -0,0 +1,22 @@
+import { SearchX } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { EmptyState } from '@/components/StateViews';
+
+export interface NoResultsProps {
+ noun: string;
+ query?: string;
+ onClear: () => void;
+}
+
+// echoes what was searched, so the person can see why nothing matched and undo it in one step
+export default function NoResults({ noun, query, onClear }: NoResultsProps) {
+ const trimmed = query?.trim();
+ return (
+ <EmptyState
+ icon={<SearchX />}
+ title={trimmed ? `No ${noun} match "${trimmed}"` : `No ${noun} match these filters`}
+ description="Try a different search or clear the filters."
+ action={<Button variant="outline" size="sm" onClick={onClear}>Clear filters</Button>}
+ />
+ );
+}
diff --git a/frontend/src/components/Pager.tsx b/frontend/src/components/Pager.tsx
index 1dec5ae..b6f7e17 100644
--- a/frontend/src/components/Pager.tsx
+++ b/frontend/src/components/Pager.tsx
@@ -1,6 +1,6 @@
-import React from 'react';
-import { ChevronLeft, ChevronRight } from 'lucide-react';
+import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
+import { pageRangeLabel } from '@/lib/library';
export interface PagerProps {
page: number;
@@ -8,28 +8,52 @@ export interface PagerProps {
onPageChange: (page: number) => void;
total: number;
shown: number;
+ pageSize?: number;
noun?: string;
+ // the element that holds the results; a page change moves focus there so the new page is read from the top
+ resultsId?: string;
}
-export default function Pager({ page, pageCount, onPageChange, total, shown, noun = 'items' }: PagerProps) {
+export default function Pager({ page, pageCount, onPageChange, total, shown, pageSize, noun = 'items', resultsId }: PagerProps) {
+ const label = pageRangeLabel({ page, pageCount, total, shown, pageSize, noun });
+
+ const goTo = (next: number) => {
+ onPageChange(next);
+ if (!resultsId) return;
+ requestAnimationFrame(() => {
+ const results = document.getElementById(resultsId);
+ if (!results) return;
+ results.scrollIntoView({ block: 'start' });
+ results.focus({ preventScroll: true });
+ });
+ };
+
if (pageCount <= 1) {
- return total > 0 ? <p className="text-center text-caption text-ink-faint">{total} {noun}</p> : null;
+ return (
+ <p role="status" aria-live="polite" className="text-center text-caption text-ink-faint">
+ {total > 0 ? label : ''}
+ </p>
+ );
}
return (
<nav aria-label="Pagination" className="flex flex-wrap items-center justify-between gap-3">
- <p className="text-caption text-ink-faint">
- Showing {shown} of {total} {noun}
- </p>
- <div className="flex items-center gap-2">
- <Button variant="outline" size="icon-sm" onClick={() => onPageChange(page - 1)} disabled={page <= 1} aria-label="Previous page">
+ <p role="status" aria-live="polite" className="text-caption text-ink-faint">{label}</p>
+ <div className="flex items-center gap-1.5">
+ <Button variant="outline" size="icon-sm" onClick={() => goTo(1)} disabled={page <= 1} aria-label="First page">
+ <ChevronsLeft />
+ </Button>
+ <Button variant="outline" size="icon-sm" onClick={() => goTo(page - 1)} disabled={page <= 1} aria-label="Previous page">
<ChevronLeft />
</Button>
<span className="min-w-20 text-center text-small text-ink-muted tabular-nums">
- {page} of {pageCount}
+ Page {page} of {pageCount}
</span>
- <Button variant="outline" size="icon-sm" onClick={() => onPageChange(page + 1)} disabled={page >= pageCount} aria-label="Next page">
+ <Button variant="outline" size="icon-sm" onClick={() => goTo(page + 1)} disabled={page >= pageCount} aria-label="Next page">
<ChevronRight />
</Button>
+ <Button variant="outline" size="icon-sm" onClick={() => goTo(pageCount)} disabled={page >= pageCount} aria-label="Last page">
+ <ChevronsRight />
+ </Button>
</div>
</nav>
);
diff --git a/frontend/src/components/RankingBarChart.tsx b/frontend/src/components/RankingBarChart.tsx
new file mode 100644
index 0000000..d922282
--- /dev/null
+++ b/frontend/src/components/RankingBarChart.tsx
@@ -0,0 +1,64 @@
+import React from 'react';
+import { Bar, BarChart, CartesianGrid, Cell, ResponsiveContainer, Tooltip as ReTooltip, XAxis, YAxis } from 'recharts';
+import { fmtNum, fmtNumFull } from '../utils/formatters';
+import type { NumberLike } from '../utils/formatters';
+import { axisProps, gridProps, rankingSummary, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import ChartFigure from './ChartFigure';
+
+export interface RankingRow {
+ name: string;
+ value: number;
+ // a second label per bar (for example the platform or unit), shown in the tooltip and the table
+ kind?: string;
+ color?: string;
+}
+
+// separate things ranked by one number: horizontal bars, largest first, because a line would suggest a trend
+export interface RankingBarChartProps {
+ rows: readonly RankingRow[];
+ label: string;
+ title: string;
+ kindLabel?: string;
+ color?: string;
+ emptyMessage?: React.ReactNode;
+}
+
+const ROW_HEIGHT = 32;
+const MIN_HEIGHT = 120;
+
+export default function RankingBarChart({ rows, label, title, kindLabel, color = 'var(--chart-2)', emptyMessage = 'No data to display' }: RankingBarChartProps) {
+ if (rows.length === 0) {
+ return <p className="py-8 text-center text-small text-ink-faint">{emptyMessage}</p>;
+ }
+ const sorted = [...rows].sort((a, b) => b.value - a.value);
+ const summary = rankingSummary(sorted, fmtNum, label.toLowerCase());
+ const height = Math.max(MIN_HEIGHT, sorted.length * ROW_HEIGHT + 24);
+ const columns = [
+ { key: 'name', label: 'Name' },
+ ...(kindLabel ? [{ key: 'kind', label: kindLabel }] : []),
+ { key: 'value', label, numeric: true, format: (value: unknown) => fmtNumFull(value as NumberLike) },
+ ];
+
+ return (
+ <ChartFigure summary={summary} table={{ caption: title, columns, rows: sorted }}>
+ <ResponsiveContainer width="100%" height={height} debounce={200}>
+ <BarChart data={sorted} layout="vertical" margin={{ top: 4, right: 16, left: 0, bottom: 4 }} title={title} desc={summary}>
+ <CartesianGrid {...gridProps} horizontal={false} />
+ <XAxis type="number" {...axisProps} tickFormatter={fmtNum} allowDecimals={false} />
+ <YAxis type="category" dataKey="name" {...axisProps} width={120} interval={0} />
+ <ReTooltip
+ contentStyle={tooltipStyle}
+ cursor={tooltipCursor}
+ formatter={(value, _name, item) => {
+ const kind = (item.payload as RankingRow).kind;
+ return [fmtNumFull(value as NumberLike), kind ? `${label} (${kind})` : label];
+ }}
+ />
+ <Bar dataKey="value" name={label} fill={color} radius={[0, 4, 4, 0]} maxBarSize={20}>
+ {sorted.map((row, index) => <Cell key={index} fill={row.color ?? color} />)}
+ </Bar>
+ </BarChart>
+ </ResponsiveContainer>
+ </ChartFigure>
+ );
+}
diff --git a/frontend/src/components/RefreshButton.tsx b/frontend/src/components/RefreshButton.tsx
new file mode 100644
index 0000000..5421618
--- /dev/null
+++ b/frontend/src/components/RefreshButton.tsx
@@ -0,0 +1,26 @@
+import { RefreshCw } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { cn } from '@/lib/utils';
+
+export interface RefreshButtonProps {
+ refreshing: boolean;
+ onRefresh: () => void;
+ disabled?: boolean;
+ // what is refreshed, for the accessible name when the page holds more than one thing
+ target?: string;
+}
+
+// the one Refresh control for page headers: same size, label and busy state everywhere
+export default function RefreshButton({ refreshing, onRefresh, disabled = false, target }: RefreshButtonProps) {
+ return (
+ <Button
+ variant="outline"
+ onClick={onRefresh}
+ disabled={refreshing || disabled}
+ aria-label={target ? `${refreshing ? 'Refreshing' : 'Refresh'} ${target}` : undefined}
+ >
+ <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} aria-hidden="true" />
+ {refreshing ? 'Refreshing' : 'Refresh'}
+ </Button>
+ );
+}
diff --git a/frontend/src/components/RowAction.tsx b/frontend/src/components/RowAction.tsx
index c63b34a..3605b41 100644
--- a/frontend/src/components/RowAction.tsx
+++ b/frontend/src/components/RowAction.tsx
@@ -5,6 +5,8 @@ import { cn } from '@/lib/utils';
export interface RowActionProps {
label: string;
+ // the row's item, so every row's button has its own accessible name ("Edit Spring recipe", not just "Edit")
+ target?: string;
onClick?: () => void;
disabled?: boolean;
children: ReactNode;
@@ -12,10 +14,11 @@ export interface RowActionProps {
danger?: boolean;
}
-export default function RowAction({ label, onClick, disabled, children, href, danger }: RowActionProps) {
+export default function RowAction({ label, target, onClick, disabled, children, href, danger }: RowActionProps) {
+ const name = target ? `${label}: ${target}` : label;
const button = href
- ? <Button variant="ghost" size="icon-xs" render={<a href={href} target="_blank" rel="noopener noreferrer" aria-label={label} />} />
- : <Button variant="ghost" size="icon-xs" onClick={onClick} disabled={disabled} aria-label={label} className={cn(danger && 'hover:bg-danger-soft hover:text-danger')} />;
+ ? <Button variant="ghost" size="icon-xs" render={<a href={href} target="_blank" rel="noopener noreferrer" aria-label={`${name} (opens in a new tab)`} />} />
+ : <Button variant="ghost" size="icon-xs" onClick={onClick} disabled={disabled} aria-label={name} className={cn(danger && 'hover:bg-danger-soft hover:text-danger')} />;
return (
<Tooltip>
<TooltipTrigger render={button}>{children}</TooltipTrigger>
diff --git a/frontend/src/components/SearchField.tsx b/frontend/src/components/SearchField.tsx
index 9166024..174cd49 100644
--- a/frontend/src/components/SearchField.tsx
+++ b/frontend/src/components/SearchField.tsx
@@ -1,7 +1,10 @@
-import React from 'react';
+import React, { useEffect, useRef, useState } from 'react';
import { Search, X } from 'lucide-react';
import { cn } from '@/lib/utils';
+// typing stays instant while filtering, the page reset and the address update wait for a pause
+const SEARCH_DEBOUNCE_MS = 250;
+
export interface SearchFieldProps extends Omit<React.ComponentProps<'input'>, 'value' | 'onChange'> {
value: string;
onChange: (value: string) => void;
@@ -9,31 +12,57 @@ export interface SearchFieldProps extends Omit<React.ComponentProps<'input'>, 'v
}
export default function SearchField({ value, onChange, placeholder = 'Search', className, inputClassName, ...props }: SearchFieldProps) {
+ const [draft, setDraft] = useState(value);
+ // the last value agreed with the parent; a different value from the parent (Clear filters, Back) replaces the draft
+ const [synced, setSynced] = useState(value);
+ const onChangeRef = useRef(onChange);
+ useEffect(() => { onChangeRef.current = onChange; });
+
+ if (value !== synced) {
+ setSynced(value);
+ setDraft(value);
+ }
+
+ useEffect(() => {
+ if (draft === synced) return undefined;
+ const timer = setTimeout(() => {
+ setSynced(draft);
+ onChangeRef.current(draft);
+ }, SEARCH_DEBOUNCE_MS);
+ return () => clearTimeout(timer);
+ }, [draft, synced]);
+
+ const clear = () => {
+ setDraft('');
+ setSynced('');
+ onChangeRef.current('');
+ };
+
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" />
<input
type="search"
- value={value}
- onChange={e => onChange(e.target.value)}
+ value={draft}
+ onChange={e => setDraft(e.target.value)}
placeholder={placeholder}
aria-label={props['aria-label'] || placeholder}
className={cn(
- 'h-(--control-h-lg) w-full min-w-0 rounded-field border border-line-control bg-surface pr-9 pl-10 text-sm text-ink transition-colors duration-(--duration-fast) outline-none',
- 'placeholder:text-ink-faint hover:border-line-strong/60 focus-visible:border-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
+ 'h-(--control-h-lg) w-full min-w-0 rounded-field border border-input bg-surface pr-9 pl-10 text-base text-ink transition-colors duration-(--duration-fast) outline-none',
+ 'placeholder:text-ink-faint hover:border-ink-muted focus-visible:border-ring focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/15',
'[&::-webkit-search-cancel-button]:appearance-none',
inputClassName,
)}
{...props}
/>
- {value && (
+ {draft && (
<button
type="button"
- onClick={() => onChange('')}
+ onClick={clear}
aria-label="Clear search"
- className="absolute right-2 flex size-6 items-center justify-center rounded-full text-ink-faint transition-colors hover:bg-surface-hover hover:text-ink"
+ className="absolute right-2 flex size-6 items-center justify-center rounded-full text-ink-faint transition-colors hover:bg-surface-hover hover:text-ink focus-visible:outline-2 focus-visible:outline-ring"
>
- <X className="size-3.5" />
+ <X className="size-3.5" aria-hidden="true" />
</button>
)}
</div>
diff --git a/frontend/src/components/SortSelect.tsx b/frontend/src/components/SortSelect.tsx
new file mode 100644
index 0000000..47c3f9d
--- /dev/null
+++ b/frontend/src/components/SortSelect.tsx
@@ -0,0 +1,26 @@
+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+
+export interface SortOption {
+ value: string;
+ label: string;
+}
+
+export interface SortSelectProps {
+ options: readonly SortOption[];
+ value: string;
+ onChange: (value: string) => void;
+}
+
+// the one sort control for every library, in grid and list alike
+export default function SortSelect({ options, value, onChange }: SortSelectProps) {
+ return (
+ <Select value={value} onValueChange={next => { if (next) onChange(next as string); }} items={[...options]}>
+ <SelectTrigger className="h-(--control-h-lg) w-48" aria-label="Sort by"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {options.map(option => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ );
+}
diff --git a/frontend/src/components/platform.tsx b/frontend/src/components/platform.tsx
index 8555028..741dad2 100644
--- a/frontend/src/components/platform.tsx
+++ b/frontend/src/components/platform.tsx
@@ -44,22 +44,24 @@ export interface AccountAvatarProps {
account: AccountFields;
size?: AccountAvatarSize;
showPlatform?: boolean;
+ // true when the name is already written next to the avatar, so a screen reader does not read it twice
+ decorative?: boolean;
className?: string;
}
-export function AccountAvatar({ account, size = 'default', showPlatform = false, className }: AccountAvatarProps) {
+export function AccountAvatar({ account, size = 'default', showPlatform = false, decorative = false, className }: AccountAvatarProps) {
const platform = platformOf(account);
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)}>
- <AvatarImage src={accountImage(account)} alt={accountName(account)} />
- <AvatarFallback className="bg-surface-sunken text-caption font-semibold text-ink-muted">
+ <AvatarImage src={accountImage(account)} alt={decorative ? '' : accountName(account)} />
+ <AvatarFallback aria-hidden={decorative || undefined} className="bg-surface-sunken text-caption font-semibold text-ink-muted">
{accountInitials(account)}
</AvatarFallback>
</Avatar>
{showPlatform && (
- <span className="absolute -right-1 -bottom-1 flex size-4 items-center justify-center rounded-full bg-surface-raised text-ink-muted ring-2 ring-surface-raised">
+ <span aria-hidden="true" className="absolute -right-1 -bottom-1 flex size-4 items-center justify-center rounded-full bg-surface-raised text-ink-muted ring-2 ring-surface-raised">
<PlatformIcon platform={platform} className="size-2.5" />
</span>
)}
diff --git a/frontend/src/components/useRovingRadio.ts b/frontend/src/components/useRovingRadio.ts
new file mode 100644
index 0000000..d27be9c
--- /dev/null
+++ b/frontend/src/components/useRovingRadio.ts
@@ -0,0 +1,31 @@
+import { useCallback } from 'react';
+import type { KeyboardEvent } from 'react';
+
+const NEXT_KEYS = ['ArrowRight', 'ArrowDown'];
+const PREVIOUS_KEYS = ['ArrowLeft', 'ArrowUp'];
+
+// a radio group is one tab stop: arrows move and select, as the WAI-ARIA radio group pattern expects
+export function useRovingRadio<V extends string>(values: readonly V[], value: V, onChange: (value: V) => void) {
+ const onKeyDown = useCallback((event: KeyboardEvent<HTMLElement>) => {
+ const index = values.indexOf(value);
+ let next = -1;
+ if (NEXT_KEYS.includes(event.key)) next = (index + 1) % values.length;
+ else if (PREVIOUS_KEYS.includes(event.key)) next = (index - 1 + values.length) % values.length;
+ else if (event.key === 'Home') next = 0;
+ else if (event.key === 'End') next = values.length - 1;
+ if (next < 0) return;
+ event.preventDefault();
+ onChange(values[next]);
+ const group = event.currentTarget.closest('[role="radiogroup"]');
+ const target = group?.querySelectorAll<HTMLElement>('[role="radio"]')[next];
+ target?.focus();
+ }, [values, value, onChange]);
+
+ const tabIndexOf = useCallback((option: V) => {
+ const selectedExists = values.includes(value);
+ if (selectedExists) return option === value ? 0 : -1;
+ return option === values[0] ? 0 : -1;
+ }, [values, value]);
+
+ return { onKeyDown, tabIndexOf };
+}
diff --git a/frontend/src/context/AppContext.tsx b/frontend/src/context/AppContext.tsx
index 68f1846..052c895 100644
--- a/frontend/src/context/AppContext.tsx
+++ b/frontend/src/context/AppContext.tsx
@@ -3,6 +3,7 @@ import type { Dispatch, ReactNode, SetStateAction } from 'react';
import { toast } from 'sonner';
import { api } from '../services/api';
import { normalizeAccount } from '../utils/formatters';
+import { accountName } from '../lib/accounts';
import type { AppAccount } from '../utils/formatters';
export type ToastSeverity = 'success' | 'error' | 'warning' | 'info';
@@ -43,10 +44,18 @@ export function AppProvider({ children }: { children: ReactNode }) {
setLoading(true);
try {
const res = await api.refreshAll();
- setAccounts((res.accounts || []).map(normalizeAccount));
- showToast('All accounts refreshed');
+ const refreshed = (res.accounts || []).map(normalizeAccount);
+ setAccounts(refreshed);
+ // one account failing must not read as all of them refreshing
+ const failed = (res.results || []).filter(result => !result.success);
+ if (failed.length === 0) {
+ showToast('All accounts refreshed');
+ } else {
+ const names = failed.map(result => accountName(refreshed.find(account => account.id === result.id)) || 'an account').join(', ');
+ showToast(`Refreshed ${refreshed.length - failed.length} of ${refreshed.length} accounts. Couldn't refresh ${names}. ${failed[0].error ?? ''}`.trim(), 'warning');
+ }
} catch (err) {
- showToast(`Refresh failed. ${(err as Error).message}`, 'error');
+ showToast(`Couldn't refresh your accounts. ${(err as Error).message}`, 'error');
} finally {
setLoading(false);
}
diff --git a/frontend/src/features/analytics/channel/ChannelAnalytics.tsx b/frontend/src/features/analytics/channel/ChannelAnalytics.tsx
index 152d459..76c349f 100644
--- a/frontend/src/features/analytics/channel/ChannelAnalytics.tsx
+++ b/frontend/src/features/analytics/channel/ChannelAnalytics.tsx
@@ -1,11 +1,14 @@
-import { useState } from 'react';
import { useParams } from 'react-router-dom';
-import { BarChart2, UserX } from 'lucide-react';
+import { UserX } from 'lucide-react';
+import { Alert, AlertAction, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import PageHeader from '@/components/PageHeader';
import SurfaceBox from '@/components/SurfaceBox';
-import { EmptyState, PageSkeleton } from '@/components/StateViews';
+import { EmptyState, ErrorState, PageSkeleton } from '@/components/StateViews';
+import { useUrlChoice } from '@/hooks/use-url-state';
+import { useDocumentTitle } from '@/hooks/use-document-title';
import { useAppContext } from '../../../context/AppContext';
import { useChannelAnalytics } from './useChannelAnalytics';
import ChannelHeader from './ChannelHeader';
@@ -30,16 +33,21 @@ const TABS = [
{ value: 'growth', label: 'Growth' },
{ value: 'shorts', label: 'Shorts and regular' },
{ value: 'tags', label: 'Tags and SEO' },
-];
+] as const;
+
+type ChannelTab = typeof TABS[number]['value'];
+
+const TAB_VALUES = TABS.map(item => item.value);
export default function ChannelAnalytics() {
const { id } = useParams();
const { accounts, showToast } = useAppContext();
const account = accounts.find(item => item.id === id);
- const { data, loading, loadAnalytics } = useChannelAnalytics(id, showToast);
- const [tab, setTab] = useState('overview');
+ const { data, initialLoading, refreshing, error, fetchedAt, retry, refresh } = useChannelAnalytics(id, showToast);
+ const [tab, setTab] = useUrlChoice<ChannelTab>('tab', TAB_VALUES, 'overview');
+ useDocumentTitle(data?.channel.title || account?.title);
- if (!account && !loading) {
+ if (!account && !initialLoading) {
return (
<div className="flex flex-col gap-6">
<PageHeader title="YouTube channel" back={BACK} />
@@ -50,19 +58,14 @@ export default function ChannelAnalytics() {
);
}
- if (loading) return <PageSkeleton metrics={4} />;
+ if (initialLoading) return <PageSkeleton metrics={4} />;
if (!data) {
return (
<div className="flex flex-col gap-6">
<PageHeader title={account?.title || 'YouTube channel'} back={BACK} />
<SurfaceBox>
- <EmptyState
- icon={<BarChart2 />}
- title="Analytics are unavailable"
- description="The channel's analytics could not be loaded. Check the YouTube API key in Settings, then try again."
- action={<Button variant="outline" size="sm" onClick={loadAnalytics}>Try again</Button>}
- />
+ <ErrorState title="Channel analytics could not load" description={error ?? undefined} onRetry={retry} />
</SurfaceBox>
</div>
);
@@ -72,17 +75,32 @@ export default function ChannelAnalytics() {
return (
<div className="flex flex-col gap-6">
- <ChannelHeader account={account} channel={channel} back={BACK} onRefresh={loadAnalytics} />
+ <ChannelHeader account={account} channel={channel} back={BACK} refreshing={refreshing} onRefresh={refresh} fetchedAt={fetchedAt} />
+ {error && (
+ <Alert variant="destructive" role="alert">
+ <AlertDescription>{error} The numbers below are from the last successful load.</AlertDescription>
+ <AlertAction><Button size="xs" variant="outline" onClick={refresh}>Try again</Button></AlertAction>
+ </Alert>
+ )}
{analytics.totalVideos === 0 ? (
<ChannelNoVideos channel={channel} />
) : (
- <Tabs value={tab} onValueChange={setTab} className="gap-6">
- <div className="scrollbar-hide -mx-4 overflow-x-auto px-4 sm:mx-0 sm:px-0">
- <TabsList className="w-max min-w-full">
- {TABS.map(item => <TabsTrigger key={item.value} value={item.value}>{item.label}</TabsTrigger>)}
- </TabsList>
+ <Tabs value={tab} onValueChange={value => setTab(value as ChannelTab)} className="gap-6" aria-busy={refreshing}>
+ {/* eight tabs do not fit a phone, so below sm the same choice is a select */}
+ <div className="sm:hidden">
+ <Select value={tab} onValueChange={value => setTab(value as ChannelTab)}>
+ <SelectTrigger className="w-full" aria-label="Section">
+ <SelectValue>{TABS.find(item => item.value === tab)?.label}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {TABS.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}
+ </SelectContent>
+ </Select>
</div>
- <TabsContent value="overview" className="flex flex-col gap-3"><ChannelOverviewTab channel={channel} analytics={analytics} /></TabsContent>
+ <TabsList className="hidden w-full flex-wrap sm:flex">
+ {TABS.map(item => <TabsTrigger key={item.value} value={item.value}>{item.label}</TabsTrigger>)}
+ </TabsList>
+ <TabsContent value="overview" className="flex flex-col gap-4"><ChannelOverviewTab channel={channel} analytics={analytics} /></TabsContent>
<TabsContent value="videos" className="flex flex-col gap-4"><ChannelVideosTab analytics={analytics} /></TabsContent>
<TabsContent value="engagement" className="flex flex-col gap-4"><ChannelEngagementTab analytics={analytics} /></TabsContent>
<TabsContent value="content" className="flex flex-col gap-4"><ChannelContentTab analytics={analytics} /></TabsContent>
diff --git a/frontend/src/features/analytics/channel/ChannelContentTab.tsx b/frontend/src/features/analytics/channel/ChannelContentTab.tsx
index ab843db..ad1ce2f 100644
--- a/frontend/src/features/analytics/channel/ChannelContentTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelContentTab.tsx
@@ -1,12 +1,16 @@
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, PieChart, Pie, Cell, Legend } from 'recharts';
-import { Film, MessageSquare, Timer, Trophy, Users, VideoIcon } from 'lucide-react';
import MetricBox from '@/components/MetricBox';
import ChartPanel from '@/components/ChartPanel';
-import { SERIES, axisProps, axisTick, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
-import { fmtPercent } from '../../../utils/formatters';
+import SurfaceBox from '@/components/SurfaceBox';
+import RankingBarChart from '@/components/RankingBarChart';
+import { SERIES, axisProps, axisTick, gridProps, legendStyle, rankingSummary, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { METRIC_ICONS } from '@/lib/metricIcons';
+import { fmtNum, fmtPercent } from '../../../utils/formatters';
import { categoryDataOf, durationDataOf, viewRangeDataOf } from './channelChartData.ts';
import type { VideoAnalytics } from '@shared/types/youtube.ts';
+const { quality: Quality, comments: Captions, consistency: Licensed, regularVideos: Embeddable, audience: Kids, duration: Duration } = METRIC_ICONS;
+
export interface ChannelContentTabProps {
analytics: VideoAnalytics;
}
@@ -14,18 +18,25 @@ export interface ChannelContentTabProps {
export default function ChannelContentTab({ analytics }: ChannelContentTabProps) {
const durationData = durationDataOf(analytics.durationDistribution);
const categoryData = categoryDataOf(analytics.categoryDistribution);
+ const viewRanges = viewRangeDataOf(analytics.viewsDistribution);
+ const period = `Last ${analytics.totalVideos} videos`;
return (
<>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<Film />} label="HD videos" value={analytics.hdCount} subtitle={fmtPercent(analytics.hdPercentage)} />
- <MetricBox small icon={<MessageSquare />} label="Captions" value={analytics.captionCount} subtitle={fmtPercent(analytics.captionPercentage)} />
- <MetricBox small icon={<Trophy />} label="Licensed" value={analytics.licensedCount} subtitle={fmtPercent(analytics.licensedPercentage)} />
- <MetricBox small icon={<VideoIcon />} label="Embeddable" value={analytics.embeddableCount} subtitle={fmtPercent(analytics.embeddablePercentage)} />
- <MetricBox small icon={<Users />} label="Made for kids" value={analytics.madeForKidsCount} />
- <MetricBox small icon={<Timer />} label="Average length" value={analytics.avgDurationFormatted} />
+ <MetricBox small icon={<Quality />} label="HD videos" value={analytics.hdCount} period={period} subtitle={`${fmtPercent(analytics.hdPercentage)} of videos`} />
+ <MetricBox small icon={<Captions />} label="With captions" value={analytics.captionCount} period={period} subtitle={`${fmtPercent(analytics.captionPercentage)} of videos`} />
+ <MetricBox small icon={<Licensed />} label="Licensed" value={analytics.licensedCount} period={period} subtitle={`${fmtPercent(analytics.licensedPercentage)} of videos`} />
+ <MetricBox small icon={<Embeddable />} label="Embeddable" value={analytics.embeddableCount} period={period} subtitle={`${fmtPercent(analytics.embeddablePercentage)} of videos`} />
+ <MetricBox small icon={<Kids />} label="Made for kids" value={analytics.madeForKidsCount} period={period} />
+ <MetricBox small icon={<Duration />} label="Average length" value={analytics.avgDurationFormatted} period={period} />
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <ChartPanel title="Length distribution" empty={durationData.length === 0}>
+ <ChartPanel
+ title="Videos by length"
+ empty={durationData.length === 0}
+ summary={rankingSummary(durationData, fmtNum, 'videos')}
+ table={{ caption: 'Videos by length', columns: [{ key: 'name', label: 'Length' }, { key: 'value', label: 'Videos', numeric: true }], rows: durationData }}
+ >
<PieChart>
<Pie data={durationData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={95} innerRadius={55} paddingAngle={2} strokeWidth={0}>
{durationData.map(slice => <Cell key={slice.name} fill={slice.color} />)}
@@ -34,23 +45,22 @@ export default function ChannelContentTab({ analytics }: ChannelContentTabProps)
<Legend iconType="circle" iconSize={8} wrapperStyle={legendStyle} />
</PieChart>
</ChartPanel>
- <ChartPanel title="Videos by category" empty={categoryData.length === 0}>
- <BarChart data={categoryData} layout="vertical">
- <CartesianGrid {...gridProps} horizontal={false} />
- <XAxis type="number" {...axisProps} />
- <YAxis dataKey="name" type="category" {...axisProps} width={120} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="value" fill={SERIES.cool} radius={[0, 4, 4, 0]} name="Videos" />
- </BarChart>
- </ChartPanel>
+ <SurfaceBox title="Videos by category">
+ <RankingBarChart rows={categoryData} label="Videos" title="Videos by category" emptyMessage="No category information on these videos" />
+ </SurfaceBox>
</div>
- <ChartPanel title="Videos by view range" height={240}>
- <BarChart data={viewRangeDataOf(analytics.viewsDistribution)}>
+ <ChartPanel
+ title="Videos by view range"
+ height={240}
+ summary={rankingSummary(viewRanges.map(row => ({ name: row.range, value: row.count })), fmtNum, 'videos')}
+ table={{ caption: 'Videos by view range', columns: [{ key: 'range', label: 'Views' }, { key: 'count', label: 'Videos', numeric: true }], rows: viewRanges }}
+ >
+ <BarChart data={viewRanges}>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="range" tick={{ ...axisTick, fontSize: 10 }} angle={-15} textAnchor="end" height={60} />
- <YAxis {...axisProps} />
+ <YAxis {...axisProps} allowDecimals={false} />
<ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="count" fill={SERIES.warm} radius={[4, 4, 0, 0]} name="Videos" />
+ <Bar dataKey="count" fill={SERIES.neutral} radius={[4, 4, 0, 0]} name="Videos" />
</BarChart>
</ChartPanel>
</>
diff --git a/frontend/src/features/analytics/channel/ChannelEngagementTab.tsx b/frontend/src/features/analytics/channel/ChannelEngagementTab.tsx
index a455841..449f1b2 100644
--- a/frontend/src/features/analytics/channel/ChannelEngagementTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelEngagementTab.tsx
@@ -1,39 +1,53 @@
-import { BarChart2, Flame, MessageSquare, ThumbsUp, TrendingUp } from 'lucide-react';
import MetricBox from '@/components/MetricBox';
import ChartPanel from '@/components/ChartPanel';
-import SectionHeader from '@/components/SectionHeader';
+import Num from '@/components/Num';
import { SERIES } from '@/lib/chart';
-import { fmtNum, fmtPercent } from '../../../utils/formatters';
-import { likesPerComment, rateOf } from './channelChartData.ts';
+import { METRIC_ICONS } from '@/lib/metricIcons';
+import { fmtPercent } from '../../../utils/formatters';
+import { likesPerComment, monthlyChartText, rateOf } from './channelChartData.ts';
import ChannelVideoTable from './ChannelVideoTable';
import TrendArea from './TrendArea';
import type { VideoAnalytics } from '@shared/types/youtube.ts';
+const { likes: Likes, rate: Rate, comments: Comments, score: Score, median: Ratio } = METRIC_ICONS;
+
export interface ChannelEngagementTabProps {
analytics: VideoAnalytics;
}
export default function ChannelEngagementTab({ analytics }: ChannelEngagementTabProps) {
+ const period = `Last ${analytics.totalVideos} videos`;
+ const engagement = monthlyChartText(analytics.engagementTrend || [], 'engagement rate', true);
+ const likeRate = monthlyChartText(analytics.likeRateTrend || [], 'like rate', true);
return (
<>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<ThumbsUp />} label="Total engagement" value={fmtNum(analytics.totalEngagement)} />
- <MetricBox small icon={<TrendingUp />} label="Engagement rate" value={fmtPercent(analytics.overallEngagementRate)} highlight />
- <MetricBox small icon={<ThumbsUp />} label="Like rate" value={rateOf(analytics.totalLikes, analytics.totalViews)} />
- <MetricBox small icon={<MessageSquare />} label="Comment rate" value={rateOf(analytics.totalComments, analytics.totalViews)} />
- <MetricBox small icon={<Flame />} label="Virality score" value={`${analytics.viralityScore}x`} />
- <MetricBox small icon={<BarChart2 />} label="Likes per comment" value={likesPerComment(analytics)} />
+ <MetricBox small icon={<Rate />} label="Engagement rate" value={fmtPercent(analytics.overallEngagementRate)} period={period} subtitle="Likes and comments per view" highlight />
+ <MetricBox small icon={<Likes />} label="Interactions" value={<Num value={analytics.totalEngagement} />} period={period} subtitle="Likes plus comments" />
+ <MetricBox small icon={<Likes />} label="Like rate" value={rateOf(analytics.totalLikes, analytics.totalViews)} period={period} subtitle="Likes per view" />
+ <MetricBox small icon={<Comments />} label="Comment rate" value={rateOf(analytics.totalComments, analytics.totalViews)} period={period} subtitle="Comments per view" />
+ <MetricBox small icon={<Score />} label="Virality" value={`${analytics.viralityScore}x`} period={period} subtitle="Best video against the average" />
+ <MetricBox small icon={<Ratio />} label="Likes per comment" value={likesPerComment(analytics)} period={period} />
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <ChartPanel title="Engagement rate by month">
- <TrendArea data={analytics.engagementTrend || []} color={SERIES.cool} name="Engagement %" percent gradientId="egGrad" />
+ <ChartPanel
+ title="Engagement rate by upload month"
+ subheader="Likes and comments per view for the videos published each month"
+ summary={engagement.summary}
+ table={{ caption: 'Engagement rate by upload month', columns: [{ key: 'month', label: 'Month' }, { key: 'value', label: 'Engagement rate', numeric: true }], rows: engagement.rows }}
+ >
+ <TrendArea data={analytics.engagementTrend || []} color={SERIES.primary} name="Engagement rate" percent gradientId="egGrad" />
</ChartPanel>
- <ChartPanel title="Like rate by month">
- <TrendArea data={analytics.likeRateTrend || []} color={SERIES.primary} name="Like rate %" percent gradientId="lrGrad" />
+ <ChartPanel
+ title="Like rate by upload month"
+ subheader="Likes per view for the videos published each month"
+ summary={likeRate.summary}
+ table={{ caption: 'Like rate by upload month', columns: [{ key: 'month', label: 'Month' }, { key: 'value', label: 'Like rate', numeric: true }], rows: likeRate.rows }}
+ >
+ <TrendArea data={analytics.likeRateTrend || []} color={SERIES.neutral} name="Like rate" percent gradientId="lrGrad" />
</ChartPanel>
</div>
- <SectionHeader title="Top 10 by engagement rate" />
- <ChannelVideoTable videos={analytics.top10ByEngagement} />
+ <ChannelVideoTable title="Top 10 by engagement rate" videos={analytics.top10ByEngagement} />
</>
);
}
diff --git a/frontend/src/features/analytics/channel/ChannelGrowthTab.tsx b/frontend/src/features/analytics/channel/ChannelGrowthTab.tsx
index a9daf1a..fb0998e 100644
--- a/frontend/src/features/analytics/channel/ChannelGrowthTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelGrowthTab.tsx
@@ -1,37 +1,65 @@
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip } from 'recharts';
-import { Eye, TrendingUp, Users } from 'lucide-react';
import MetricBox from '@/components/MetricBox';
import ChartPanel from '@/components/ChartPanel';
-import { SERIES, axisProps, gridProps, tooltipCursor, tooltipStyle } from '@/lib/chart';
-import { fmtNum } from '../../../utils/formatters';
-import { uploadsByMonthOf } from './channelChartData.ts';
+import Num from '@/components/Num';
+import { PLATFORM_META } from '@/lib/accounts';
+import { SERIES, axisProps, gridProps, tooltipCursor, tooltipStyle, trendSummary } from '@/lib/chart';
+import { METRIC_ICONS } from '@/lib/metricIcons';
+import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import type { NumberLike } from '../../../utils/formatters';
+import { monthlyChartText, uploadsByMonthOf } from './channelChartData.ts';
import MetricGrid from './MetricGrid';
import TrendArea from './TrendArea';
import type { VideoAnalytics } from '@shared/types/youtube.ts';
import type { ChannelDetails } from './channelChartData.ts';
+const { views: Views, audience: Audience, period: Estimate } = METRIC_ICONS;
+
+const full = (value: unknown) => fmtNumFull(value as NumberLike);
+
export interface ChannelGrowthTabProps {
channel: ChannelDetails;
analytics: VideoAnalytics;
}
export default function ChannelGrowthTab({ channel, analytics }: ChannelGrowthTabProps) {
+ const views = monthlyChartText(analytics.viewsTrend || [], 'views');
+ const uploads = uploadsByMonthOf(analytics.viewsTrend);
return (
<>
<MetricGrid>
- <MetricBox small icon={<TrendingUp />} label="Estimated yearly views" value={fmtNum(channel.estimatedYearlyViews)} highlight />
- <MetricBox small icon={<Users />} label="Estimated yearly subscribers" value={fmtNum(channel.estimatedYearlySubGain)} />
- <MetricBox small icon={<Eye />} label="Views per day" value={fmtNum(channel.avgViewsPerDay)} />
- <MetricBox small icon={<Users />} label="Subscribers per day" value={fmtNum(channel.avgSubGainPerDay)} />
+ <MetricBox small icon={<Views />} label="Views per day" value={<Num value={channel.avgViewsPerDay} />} period="Since the channel started" highlight />
+ <MetricBox small icon={<Audience />} label="Subscribers per day" value={<Num value={channel.avgSubGainPerDay} />} period="Since the channel started" />
+ <MetricBox small icon={<Estimate />} label="Views in a year" value={<Num value={channel.estimatedYearlyViews} />} period="Estimate" subtitle={`About ${fmtNum(channel.estimatedMonthlyViews)} a month at the daily average`} />
+ <MetricBox small icon={<Estimate />} label="Subscribers in a year" value={<Num value={channel.estimatedYearlySubGain} />} period="Estimate" subtitle={`About ${fmtNum(channel.estimatedMonthlySubGain)} a month at the daily average`} />
</MetricGrid>
- <ChartPanel title="Views by month" height={300}>
- <TrendArea data={analytics.viewsTrend || []} color={SERIES.primary} name="Views" gradientId="viewGrad" />
+ <ChartPanel
+ title="Lifetime views of videos, by upload month"
+ subheader="Every view a video has had so far, counted in the month it was published"
+ height={300}
+ summary={views.summary}
+ table={{
+ caption: 'Lifetime views of videos, by upload month',
+ columns: [{ key: 'month', label: 'Upload month' }, { key: 'value', label: 'Views', numeric: true, format: full }],
+ rows: views.rows,
+ }}
+ >
+ <TrendArea data={analytics.viewsTrend || []} color={PLATFORM_META.youtube.series} name="Views" gradientId="viewGrad" />
</ChartPanel>
- <ChartPanel title="Uploads by month" height={240}>
- <BarChart data={uploadsByMonthOf(analytics.viewsTrend)}>
+ <ChartPanel
+ title="Uploads by month"
+ height={240}
+ summary={trendSummary(uploads.map(point => ({ name: point.month, value: point.uploads })), fmtNum, 'uploads')}
+ table={{
+ caption: 'Uploads by month',
+ columns: [{ key: 'month', label: 'Month' }, { key: 'uploads', label: 'Uploads', numeric: true, format: full }],
+ rows: uploads,
+ }}
+ >
+ <BarChart data={uploads}>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="month" {...axisProps} />
- <YAxis {...axisProps} />
+ <YAxis {...axisProps} allowDecimals={false} />
<ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
<Bar dataKey="uploads" fill={SERIES.neutral} radius={[4, 4, 0, 0]} name="Uploads" />
</BarChart>
diff --git a/frontend/src/features/analytics/channel/ChannelHeader.tsx b/frontend/src/features/analytics/channel/ChannelHeader.tsx
index 6f8b99a..77297a4 100644
--- a/frontend/src/features/analytics/channel/ChannelHeader.tsx
+++ b/frontend/src/features/analytics/channel/ChannelHeader.tsx
@@ -1,7 +1,7 @@
-import { RefreshCw } from 'lucide-react';
-import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import PageHeader from '@/components/PageHeader';
+import RefreshButton from '@/components/RefreshButton';
+import DataFreshness from '@/components/DataFreshness';
import { AccountAvatar } from '@/components/platform';
import type { PageHeaderBack } from '@/components/PageHeader';
import type { AppAccount } from '../../../utils/formatters';
@@ -12,26 +12,26 @@ export interface ChannelHeaderProps {
account: AppAccount | undefined;
channel: ChannelDetails;
back: PageHeaderBack;
+ refreshing: boolean;
onRefresh: () => void;
+ fetchedAt: string | null;
}
-export default function ChannelHeader({ account, channel, back, onRefresh }: ChannelHeaderProps) {
+export default function ChannelHeader({ account, channel, back, refreshing, onRefresh, fetchedAt }: ChannelHeaderProps) {
return (
<PageHeader
back={back}
- media={<AccountAvatar account={{ ...account, thumbnail: channel.thumbnails?.high || channel.thumbnails?.medium || account?.thumbnail }} size="xl" showPlatform />}
+ media={<AccountAvatar account={{ ...account, thumbnail: channel.thumbnails?.high || channel.thumbnails?.medium || account?.thumbnail }} size="xl" showPlatform decorative />}
title={channel.title}
description={
- <span className="flex flex-wrap gap-1.5">
- {channelMeta(channel).map(item => <Badge key={item} variant="outline">{item}</Badge>)}
+ <span className="flex flex-col gap-1.5">
+ <span className="flex flex-wrap gap-1.5">
+ {channelMeta(channel).map(item => <Badge key={item} variant="outline">{item}</Badge>)}
+ </span>
+ <DataFreshness fetchedAt={fetchedAt} />
</span>
}
- actions={
- <Button variant="outline" size="sm" onClick={onRefresh}>
- <RefreshCw data-icon="inline-start" />
- Refresh
- </Button>
- }
+ actions={<RefreshButton refreshing={refreshing} onRefresh={onRefresh} />}
/>
);
}
diff --git a/frontend/src/features/analytics/channel/ChannelNoVideos.tsx b/frontend/src/features/analytics/channel/ChannelNoVideos.tsx
index 24c5260..02557aa 100644
--- a/frontend/src/features/analytics/channel/ChannelNoVideos.tsx
+++ b/frontend/src/features/analytics/channel/ChannelNoVideos.tsx
@@ -1,10 +1,12 @@
-import { Eye, Users, VideoIcon } from 'lucide-react';
import MetricBox from '@/components/MetricBox';
+import Num from '@/components/Num';
import SurfaceBox from '@/components/SurfaceBox';
import { EmptyState } from '@/components/StateViews';
-import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import type { ChannelDetails } from './channelChartData.ts';
+const { audience: Audience, views: Views, videos: Videos } = METRIC_ICONS;
+
export interface ChannelNoVideosProps {
channel: ChannelDetails;
}
@@ -13,13 +15,13 @@ export default function ChannelNoVideos({ channel }: ChannelNoVideosProps) {
return (
<>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
- <MetricBox small icon={<Users />} label="Subscribers" value={fmtNum(channel.subscriberCount)} subtitle={fmtNumFull(channel.subscriberCount)} />
- <MetricBox small icon={<Eye />} label="Total views" value={fmtNum(channel.viewCount)} subtitle={fmtNumFull(channel.viewCount)} />
- <MetricBox small icon={<VideoIcon />} label="Total videos" value={fmtNum(channel.videoCount)} subtitle="Public uploads" />
+ <MetricBox small icon={<Audience />} label="Subscribers" value={<Num value={channel.subscriberCount} />} period="Now" />
+ <MetricBox small icon={<Views />} label="Views" value={<Num value={channel.viewCount} />} period="All time" />
+ <MetricBox small icon={<Videos />} label="Videos" value={<Num value={channel.videoCount} />} subtitle="Public uploads" />
</div>
<SurfaceBox>
<EmptyState
- icon={<VideoIcon />}
+ icon={<Videos />}
title="No public videos yet"
description="Video analytics start with this channel's first public upload. After publishing, choose Refresh."
/>
diff --git a/frontend/src/features/analytics/channel/ChannelOverviewTab.tsx b/frontend/src/features/analytics/channel/ChannelOverviewTab.tsx
index 85fc89b..3abf304 100644
--- a/frontend/src/features/analytics/channel/ChannelOverviewTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelOverviewTab.tsx
@@ -1,29 +1,33 @@
-import {
- BarChart2, Calendar, Clock, Eye, Flame, MessageSquare, ThumbsUp, Timer, TrendingUp, Trophy, Users, VideoIcon, Zap,
-} from 'lucide-react';
import MetricBox from '@/components/MetricBox';
+import MetricDetails from '@/components/MetricDetails';
+import Num from '@/components/Num';
import SectionHeader from '@/components/SectionHeader';
import MediaCard, { MediaChip } from '@/components/MediaCard';
-import { fmtNum, fmtNumFull, fmtPercent } from '../../../utils/formatters';
+import { METRIC_ICONS } from '@/lib/metricIcons';
+import { fmtNum, fmtPercent } from '../../../utils/formatters';
import { bestVideosOf, likesLabel, watchUrl } from './channelChartData.ts';
-import MetricGrid from './MetricGrid';
import type { VideoAnalytics } from '@shared/types/youtube.ts';
import type { ChannelDetails } from './channelChartData.ts';
+const { views: Views, audience: Audience, videos: Videos, likes: Likes, rate: Rate } = METRIC_ICONS;
+
function BestVideos({ analytics }: { analytics: VideoAnalytics }) {
return (
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
+ <ul className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
{bestVideosOf(analytics).map(({ label, video }) => (
- <MediaCard
- key={label}
- href={watchUrl(video.videoId)}
- image={video.thumbnail}
- title={video.title}
- topLeft={<MediaChip>{label}</MediaChip>}
- meta={<span>{fmtNum(video.viewCount)} views, {likesLabel(video.likeCount)}</span>}
- />
+ <li key={label} className="flex">
+ <MediaCard
+ className="w-full"
+ href={watchUrl(video.videoId)}
+ linkLabel={`${label}: ${video.title}, ${fmtNum(video.viewCount)} views, ${likesLabel(video.likeCount)}. Opens on YouTube in a new tab.`}
+ image={video.thumbnail}
+ title={video.title}
+ topLeft={<MediaChip>{label}</MediaChip>}
+ meta={<span>{fmtNum(video.viewCount)} views, {likesLabel(video.likeCount)}</span>}
+ />
+ </li>
))}
- </div>
+ </ul>
);
}
@@ -32,43 +36,52 @@ export interface ChannelOverviewTabProps {
analytics: VideoAnalytics;
}
+// five headline numbers; the rest sit in one quiet list, and each tab owns its own figures so nothing repeats
export default function ChannelOverviewTab({ channel, analytics }: ChannelOverviewTabProps) {
+ const videosPeriod = `Last ${analytics.totalVideos} videos`;
return (
<>
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<Eye />} label="Total views" value={fmtNum(channel.viewCount)} subtitle={fmtNumFull(channel.viewCount)} highlight />
- <MetricBox small icon={<Users />} label="Subscribers" value={fmtNum(channel.subscriberCount)} subtitle={fmtNumFull(channel.subscriberCount)} />
- <MetricBox small icon={<VideoIcon />} label="Total videos" value={fmtNum(channel.videoCount)} subtitle={`${analytics.totalVideos} analyzed`} />
- <MetricBox small icon={<ThumbsUp />} label="Total likes" value={fmtNum(analytics.totalLikes)} subtitle={fmtNumFull(analytics.totalLikes)} />
- <MetricBox small icon={<MessageSquare />} label="Comments" value={fmtNum(analytics.totalComments)} subtitle={fmtNumFull(analytics.totalComments)} />
- <MetricBox small icon={<TrendingUp />} label="Engagement" value={fmtPercent(analytics.overallEngagementRate)} subtitle="Likes and comments per view" />
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-5">
+ <MetricBox small icon={<Views />} label="Views" value={<Num value={channel.viewCount} />} period="All time" highlight />
+ <MetricBox small icon={<Audience />} label="Subscribers" value={<Num value={channel.subscriberCount} />} period="Now" />
+ <MetricBox small icon={<Videos />} label="Videos" value={<Num value={channel.videoCount} />} period="All time" subtitle={`${analytics.totalVideos} analyzed`} />
+ <MetricBox small icon={<Likes />} label="Likes" value={<Num value={analytics.totalLikes} />} period={videosPeriod} />
+ <MetricBox small icon={<Rate />} label="Engagement rate" value={fmtPercent(analytics.overallEngagementRate)} period={videosPeriod} subtitle="Likes and comments per view" />
</div>
- <MetricGrid>
- <MetricBox small icon={<Zap />} label="Average views per video" value={fmtNum(analytics.avgViews)} />
- <MetricBox small icon={<ThumbsUp />} label="Average likes per video" value={fmtNum(analytics.avgLikes)} />
- <MetricBox small icon={<MessageSquare />} label="Average comments" value={fmtNum(analytics.avgComments)} />
- <MetricBox small icon={<BarChart2 />} label="Median views" value={fmtNum(analytics.medianViews)} />
- </MetricGrid>
- <MetricGrid>
- <MetricBox small icon={<Eye />} label="Views per subscriber" value={channel.viewsPerSubscriber} />
- <MetricBox small icon={<TrendingUp />} label="Subscribers per day" value={fmtNum(channel.avgSubGainPerDay)} />
- <MetricBox small icon={<Eye />} label="Views per day" value={fmtNum(channel.avgViewsPerDay)} />
- <MetricBox small icon={<Timer />} label="Average length" value={analytics.avgDurationFormatted} />
- </MetricGrid>
- <MetricGrid>
- <MetricBox small icon={<Clock />} label="Videos, last 7 days" value={analytics.videosLast7Days} />
- <MetricBox small icon={<Clock />} label="Videos, last 30 days" value={analytics.videosLast30Days} />
- <MetricBox small icon={<Clock />} label="Videos, last 90 days" value={analytics.videosLast90Days} />
- <MetricBox small icon={<Clock />} label="Videos, last 365 days" value={analytics.videosLast365Days} />
- </MetricGrid>
- <MetricGrid>
- <MetricBox small icon={<Calendar />} label="Estimated monthly views" value={fmtNum(channel.estimatedMonthlyViews)} />
- <MetricBox small icon={<Users />} label="Estimated monthly subscribers" value={fmtNum(channel.estimatedMonthlySubGain)} />
- <MetricBox small icon={<Flame />} label="Virality score" value={`${analytics.viralityScore}x`} />
- <MetricBox small icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore}/100`} />
- </MetricGrid>
- <SectionHeader title="Best performing videos" className="mt-5" />
+ <MetricDetails
+ subheader={`Worked out from the ${analytics.totalVideos} videos loaded from this channel.`}
+ groups={[
+ {
+ title: 'Per video',
+ items: [
+ { label: 'Average views', value: <Num value={analytics.avgViews} /> },
+ { label: 'Median views', value: <Num value={analytics.medianViews} />, hint: 'Half the videos have more, half have fewer' },
+ { label: 'Average likes', value: <Num value={analytics.avgLikes} /> },
+ { label: 'Average comments', value: <Num value={analytics.avgComments} /> },
+ { label: 'Average length', value: analytics.avgDurationFormatted },
+ ],
+ },
+ {
+ title: 'Recent uploads',
+ items: [
+ { label: 'Last 7 days', value: analytics.videosLast7Days },
+ { label: 'Last 30 days', value: analytics.videosLast30Days },
+ { label: 'Last 90 days', value: analytics.videosLast90Days },
+ { label: 'Last 365 days', value: analytics.videosLast365Days },
+ ],
+ },
+ {
+ title: 'Audience',
+ items: [
+ { label: 'Comments', value: <Num value={analytics.totalComments} />, hint: videosPeriod },
+ { label: 'Views per subscriber', value: channel.viewsPerSubscriber, hint: 'All-time views divided by subscribers' },
+ ],
+ },
+ ]}
+ />
+
+ <SectionHeader title="Best performing videos" className="mt-2" />
<BestVideos analytics={analytics} />
</>
);
diff --git a/frontend/src/features/analytics/channel/ChannelPublishingTab.tsx b/frontend/src/features/analytics/channel/ChannelPublishingTab.tsx
index c78912e..96a0d1e 100644
--- a/frontend/src/features/analytics/channel/ChannelPublishingTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelPublishingTab.tsx
@@ -1,49 +1,56 @@
-import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, AreaChart, Area } from 'recharts';
-import { Calendar, Clock, Trophy, Zap } from 'lucide-react';
+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip } from 'recharts';
import MetricBox from '@/components/MetricBox';
import ChartPanel from '@/components/ChartPanel';
-import { SERIES, axisProps, gridProps, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { SERIES, axisProps, gridProps, rankingSummary, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { METRIC_ICONS } from '@/lib/metricIcons';
+import { fmtNum } from '../../../utils/formatters';
import { dayDataOf, hourDataOf, peakHourLabel } from './channelChartData.ts';
import MetricGrid from './MetricGrid';
import type { VideoAnalytics } from '@shared/types/youtube.ts';
+const { period: Day, time: Hour, videos: Uploads, consistency: Consistency } = METRIC_ICONS;
+
export interface ChannelPublishingTabProps {
analytics: VideoAnalytics;
}
export default function ChannelPublishingTab({ analytics }: ChannelPublishingTabProps) {
+ const days = dayDataOf(analytics.publishDayDistribution);
+ const hours = hourDataOf(analytics.publishHourDistribution);
return (
<>
<MetricGrid>
- <MetricBox small icon={<Calendar />} label="Most common upload day" value={analytics.peakPublishDay || 'Not available'} />
- <MetricBox small icon={<Clock />} label="Most common upload hour" value={peakHourLabel(analytics.peakPublishHour)} />
- <MetricBox small icon={<Zap />} label="Uploads per week" value={analytics.uploadFrequencyPerWeek} />
- <MetricBox small icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore}/100`} />
+ <MetricBox small icon={<Day />} label="Most common upload day" value={analytics.peakPublishDay || 'Not available'} />
+ <MetricBox small icon={<Hour />} label="Most common upload hour" value={peakHourLabel(analytics.peakPublishHour)} subtitle="UTC" />
+ <MetricBox small icon={<Uploads />} label="Uploads per week" value={analytics.uploadFrequencyPerWeek} />
+ <MetricBox small icon={<Consistency />} label="Consistency" value={`${analytics.consistencyScore} of 100`} subtitle="How evenly uploads spread across active weeks" />
</MetricGrid>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <ChartPanel title="Uploads by day of week">
- <BarChart data={dayDataOf(analytics.publishDayDistribution)}>
+ <ChartPanel
+ title="Uploads by day of week"
+ summary={rankingSummary(days.map(day => ({ name: day.day, value: day.count })), fmtNum, 'videos')}
+ table={{ caption: 'Uploads by day of week', columns: [{ key: 'day', label: 'Day' }, { key: 'count', label: 'Videos', numeric: true }], rows: days }}
+ >
+ <BarChart data={days}>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="day" {...axisProps} />
- <YAxis {...axisProps} />
+ <YAxis {...axisProps} allowDecimals={false} />
<ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="count" fill={SERIES.cool} radius={[4, 4, 0, 0]} name="Videos" />
+ <Bar dataKey="count" fill={SERIES.neutral} radius={[4, 4, 0, 0]} name="Videos" />
</BarChart>
</ChartPanel>
- <ChartPanel title="Uploads by hour (UTC)">
- <AreaChart data={hourDataOf(analytics.publishHourDistribution)}>
- <defs>
- <linearGradient id="hourGrad" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor={SERIES.warm} stopOpacity={0.2} />
- <stop offset="95%" stopColor={SERIES.warm} stopOpacity={0} />
- </linearGradient>
- </defs>
+ <ChartPanel
+ title="Uploads by hour (UTC)"
+ summary={rankingSummary(hours.map(hour => ({ name: hour.hour, value: hour.count })), fmtNum, 'videos')}
+ table={{ caption: 'Uploads by hour (UTC)', columns: [{ key: 'hour', label: 'Hour' }, { key: 'count', label: 'Videos', numeric: true }], rows: hours }}
+ >
+ <BarChart data={hours}>
<CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="hour" {...axisProps} />
- <YAxis {...axisProps} />
- <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} />
- <Area type="monotone" dataKey="count" stroke={SERIES.warm} fill="url(#hourGrad)" strokeWidth={2} name="Videos" />
- </AreaChart>
+ <XAxis dataKey="hour" {...axisProps} interval={2} />
+ <YAxis {...axisProps} allowDecimals={false} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <Bar dataKey="count" fill={SERIES.warm} radius={[3, 3, 0, 0]} name="Videos" />
+ </BarChart>
</ChartPanel>
</div>
</>
diff --git a/frontend/src/features/analytics/channel/ChannelShortsTab.tsx b/frontend/src/features/analytics/channel/ChannelShortsTab.tsx
index b2785f8..e50c5bb 100644
--- a/frontend/src/features/analytics/channel/ChannelShortsTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelShortsTab.tsx
@@ -1,34 +1,48 @@
import type { TooltipValueType } from 'recharts';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, PieChart, Pie, Cell, Legend } from 'recharts';
-import { Eye, Flame, VideoIcon } from 'lucide-react';
import MetricBox from '@/components/MetricBox';
import ChartPanel from '@/components/ChartPanel';
-import { SERIES, axisProps, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import Num from '@/components/Num';
+import { SERIES, axisProps, gridProps, legendStyle, rankingSummary, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import type { NumberLike } from '../../../utils/formatters';
import { shortsComparisonOf, splitDataOf } from './channelChartData.ts';
import MetricGrid from './MetricGrid';
import type { VideoAnalytics } from '@shared/types/youtube.ts';
+const { shorts: Shorts, regularVideos: Regular, averageViews: AverageViews } = METRIC_ICONS;
+
function fullNumber(value: TooltipValueType | undefined): string {
return fmtNumFull(value as number);
}
+const full = (value: unknown) => fmtNumFull(value as NumberLike);
+
export interface ChannelShortsTabProps {
analytics: VideoAnalytics;
}
export default function ChannelShortsTab({ analytics }: ChannelShortsTabProps) {
const splitData = splitDataOf(analytics);
+ const comparison = shortsComparisonOf(analytics);
+ const viewsLead = (analytics.avgShortViews || 0) >= (analytics.avgRegularViews || 0) ? 'Shorts' : 'Regular videos';
return (
<>
<MetricGrid>
- <MetricBox small icon={<Flame />} label="Shorts" value={analytics.shortsCount} />
- <MetricBox small icon={<VideoIcon />} label="Regular videos" value={analytics.regularCount} />
- <MetricBox small icon={<Eye />} label="Average views per Short" value={fmtNum(analytics.avgShortViews)} />
- <MetricBox small icon={<Eye />} label="Average views per video" value={fmtNum(analytics.avgRegularViews)} />
+ <MetricBox small icon={<Shorts />} label="Shorts" value={<Num value={analytics.shortsCount} />} />
+ <MetricBox small icon={<Regular />} label="Regular videos" value={<Num value={analytics.regularCount} />} />
+ <MetricBox small icon={<AverageViews />} label="Average views per Short" value={<Num value={analytics.avgShortViews} />} />
+ <MetricBox small icon={<AverageViews />} label="Average views per video" value={<Num value={analytics.avgRegularViews} />} subtitle="Regular videos" />
</MetricGrid>
<div className="grid grid-cols-1 gap-4 md:grid-cols-5">
- <ChartPanel title="Content split" className="md:col-span-2" empty={splitData.length === 0}>
+ <ChartPanel
+ title="Content split"
+ className="md:col-span-2"
+ empty={splitData.length === 0}
+ summary={rankingSummary(splitData, fmtNum, 'videos')}
+ table={{ caption: 'Content split', columns: [{ key: 'name', label: 'Kind' }, { key: 'value', label: 'Videos', numeric: true, format: full }], rows: splitData }}
+ >
<PieChart>
<Pie data={splitData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={95} innerRadius={55} paddingAngle={2} strokeWidth={0}>
{splitData.map(slice => <Cell key={slice.name} fill={slice.color} />)}
@@ -37,14 +51,27 @@ export default function ChannelShortsTab({ analytics }: ChannelShortsTabProps) {
<Legend iconType="circle" iconSize={8} wrapperStyle={legendStyle} />
</PieChart>
</ChartPanel>
- <ChartPanel title="Shorts compared with regular videos" className="md:col-span-3">
- <BarChart data={shortsComparisonOf(analytics)}>
+ <ChartPanel
+ title="Shorts compared with regular videos"
+ className="md:col-span-3"
+ summary={`${viewsLead} get more views on average: ${fmtNum(analytics.avgShortViews)} per Short against ${fmtNum(analytics.avgRegularViews)} per regular video.`}
+ table={{
+ caption: 'Shorts compared with regular videos',
+ columns: [
+ { key: 'metric', label: 'Average' },
+ { key: 'Shorts', label: 'Shorts', numeric: true, format: full },
+ { key: 'Regular', label: 'Regular videos', numeric: true, format: full },
+ ],
+ rows: comparison,
+ }}
+ >
+ <BarChart data={comparison}>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="metric" {...axisProps} />
<YAxis {...axisProps} tickFormatter={fmtNum} />
<ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={fullNumber} />
<Bar dataKey="Shorts" fill={SERIES.primary} radius={[4, 4, 0, 0]} />
- <Bar dataKey="Regular" fill={SERIES.cool} radius={[4, 4, 0, 0]} />
+ <Bar dataKey="Regular" name="Regular videos" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />
<Legend wrapperStyle={legendStyle} />
</BarChart>
</ChartPanel>
diff --git a/frontend/src/features/analytics/channel/ChannelTagsTab.tsx b/frontend/src/features/analytics/channel/ChannelTagsTab.tsx
index deadabf..a096f30 100644
--- a/frontend/src/features/analytics/channel/ChannelTagsTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelTagsTab.tsx
@@ -1,13 +1,14 @@
-import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip } from 'recharts';
-import { Film, MessageSquare, Tag, VideoIcon } from 'lucide-react';
import MetricBox from '@/components/MetricBox';
-import ChartPanel from '@/components/ChartPanel';
-import { SERIES, axisProps, gridProps, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import SurfaceBox from '@/components/SurfaceBox';
+import RankingBarChart from '@/components/RankingBarChart';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { fmtPercent } from '../../../utils/formatters';
import MetricGrid from './MetricGrid';
import TagCloud from './TagCloud';
import type { VideoAnalytics } from '@shared/types/youtube.ts';
+const { tags: Tags, comments: Captions, quality: Quality, regularVideos: Embeddable } = METRIC_ICONS;
+
export interface ChannelTagsTabProps {
analytics: VideoAnalytics;
}
@@ -17,22 +18,20 @@ export default function ChannelTagsTab({ analytics }: ChannelTagsTabProps) {
return (
<>
<MetricGrid>
- <MetricBox small icon={<Tag />} label="Unique tags" value={analytics.tagFrequency?.length || 0} />
- <MetricBox small icon={<MessageSquare />} label="Caption rate" value={fmtPercent(analytics.captionPercentage)} />
- <MetricBox small icon={<Film />} label="HD rate" value={fmtPercent(analytics.hdPercentage)} />
- <MetricBox small icon={<VideoIcon />} label="Embeddable rate" value={fmtPercent(analytics.embeddablePercentage)} />
+ <MetricBox small icon={<Tags />} label="Unique tags" value={tags.length} />
+ <MetricBox small icon={<Captions />} label="Caption rate" value={fmtPercent(analytics.captionPercentage)} subtitle="Videos with captions" />
+ <MetricBox small icon={<Quality />} label="HD rate" value={fmtPercent(analytics.hdPercentage)} subtitle="Videos in HD" />
+ <MetricBox small icon={<Embeddable />} label="Embeddable rate" value={fmtPercent(analytics.embeddablePercentage)} subtitle="Videos other sites can embed" />
</MetricGrid>
<TagCloud tags={tags} />
{tags.length > 0 && (
- <ChartPanel title="Tag usage, top 20" height={400}>
- <BarChart data={tags.slice(0, 20)} layout="vertical">
- <CartesianGrid {...gridProps} horizontal={false} />
- <XAxis type="number" {...axisProps} />
- <YAxis dataKey="tag" type="category" {...axisProps} width={140} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="count" fill={SERIES.primary} radius={[0, 4, 4, 0]} name="Videos using this tag" />
- </BarChart>
- </ChartPanel>
+ <SurfaceBox title="Tag usage, top 20">
+ <RankingBarChart
+ rows={tags.slice(0, 20).map(({ tag, count }) => ({ name: tag, value: count }))}
+ label="Videos using this tag"
+ title="Tag usage, top 20"
+ />
+ </SurfaceBox>
)}
</>
);
diff --git a/frontend/src/features/analytics/channel/ChannelVideoTable.tsx b/frontend/src/features/analytics/channel/ChannelVideoTable.tsx
index a4b3293..120523a 100644
--- a/frontend/src/features/analytics/channel/ChannelVideoTable.tsx
+++ b/frontend/src/features/analytics/channel/ChannelVideoTable.tsx
@@ -3,7 +3,10 @@ import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import SurfaceBox from '@/components/SurfaceBox';
-import { fmtCount, fmtDate, fmtDuration, fmtNum, fmtPercent } from '../../../utils/formatters';
+import ColumnHint from '@/components/ColumnHint';
+import Num from '@/components/Num';
+import { fmtCount, fmtDate, fmtDuration, fmtPercent } from '../../../utils/formatters';
+import { isStrongEngagement, STRONG_ENGAGEMENT_HINT } from '@/lib/library';
import type { YouTubeVideoSummary } from '@shared/types/youtube.ts';
import { watchUrl } from './channelChartData.ts';
@@ -13,57 +16,63 @@ interface VideoRowProps {
}
export interface ChannelVideoTableProps {
+ title: string;
videos: YouTubeVideoSummary[] | null | undefined;
}
function VideoRow({ video, rank }: VideoRowProps) {
+ const strong = isStrongEngagement(video.engagementRate);
return (
<TableRow>
<TableCell className="text-right font-mono text-caption text-ink-faint">{rank}</TableCell>
- <TableCell className="max-w-[280px]">
- <a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" className="block truncate text-sm font-medium text-ink hover:underline">{video.title}</a>
+ <TableCell className="sticky left-0 z-[1] max-w-56 bg-surface-raised sm:max-w-72">
+ <a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" title={video.title} className="block truncate text-sm font-medium text-ink underline-offset-4 hover:underline">
+ {video.title}<span className="sr-only"> (opens on YouTube in a new tab)</span>
+ </a>
</TableCell>
- <TableCell className="text-right font-semibold text-ink">{fmtNum(video.viewCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtCount(video.likeCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtCount(video.commentCount)}</TableCell>
+ <TableCell className="text-right font-semibold text-ink"><Num value={video.viewCount} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell">{fmtCount(video.likeCount)}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell">{fmtCount(video.commentCount)}</TableCell>
<TableCell className="text-right">
- <Badge variant={parseFloat(video.engagementRate as string) > 5 ? 'success' : 'secondary'}>{fmtPercent(video.engagementRate)}</Badge>
+ <Badge variant={strong ? 'success' : 'secondary'}>
+ {fmtPercent(video.engagementRate)}
+ {strong && <span className="sr-only"> (strong)</span>}
+ </Badge>
</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtDuration(video.durationSeconds)}</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{fmtDate(video.publishedAt)}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted lg:table-cell">{fmtDuration(video.durationSeconds)}</TableCell>
+ <TableCell className="hidden text-right text-small text-ink-faint md:table-cell">{fmtDate(video.publishedAt)}</TableCell>
<TableCell>
- <Button variant="ghost" size="icon-xs" render={<a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" aria-label={`Watch ${video.title} on YouTube`} />}>
- <Play />
+ <Button variant="ghost" size="icon-xs" render={<a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" aria-label={`Watch ${video.title} on YouTube (opens in a new tab)`} />}>
+ <Play aria-hidden="true" />
</Button>
</TableCell>
</TableRow>
);
}
-export default function ChannelVideoTable({ videos }: ChannelVideoTableProps) {
+// the scroll box is the table's own container, so the header row can stick while the list scrolls
+export default function ChannelVideoTable({ title, videos }: ChannelVideoTableProps) {
const rows = (videos || []).filter(Boolean);
return (
- <SurfaceBox content={false} className="overflow-hidden">
- <div className="max-h-[480px] overflow-y-auto">
- <Table>
- <TableHeader className="sticky top-0 z-10 bg-surface-raised">
- <TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead>Video</TableHead>
- <TableHead className="text-right">Views</TableHead>
- <TableHead className="text-right">Likes</TableHead>
- <TableHead className="text-right">Comments</TableHead>
- <TableHead className="text-right">Engagement</TableHead>
- <TableHead className="text-right">Length</TableHead>
- <TableHead className="text-right">Published</TableHead>
- <TableHead className="w-10"><span className="sr-only">Watch</span></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {rows.map((video, i) => <VideoRow key={video.videoId} video={video} rank={i + 1} />)}
- </TableBody>
- </Table>
- </div>
+ <SurfaceBox title={title} content={false} className="overflow-hidden">
+ <Table containerClassName="max-h-[30rem] overflow-y-auto">
+ <TableHeader className="sticky top-0 z-[2] bg-surface-raised">
+ <TableRow>
+ <TableHead className="w-10 text-right">#</TableHead>
+ <TableHead className="sticky left-0 z-[1] bg-surface-raised">Video</TableHead>
+ <TableHead className="text-right">Views</TableHead>
+ <TableHead className="hidden text-right sm:table-cell">Likes</TableHead>
+ <TableHead className="hidden text-right md:table-cell">Comments</TableHead>
+ <TableHead className="text-right"><ColumnHint label="Engagement rate (%)" hint={STRONG_ENGAGEMENT_HINT} /></TableHead>
+ <TableHead className="hidden text-right lg:table-cell">Length</TableHead>
+ <TableHead className="hidden text-right md:table-cell">Published</TableHead>
+ <TableHead className="w-10"><span className="sr-only">Watch</span></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((video, i) => <VideoRow key={video.videoId} video={video} rank={i + 1} />)}
+ </TableBody>
+ </Table>
</SurfaceBox>
);
}
diff --git a/frontend/src/features/analytics/channel/ChannelVideosTab.tsx b/frontend/src/features/analytics/channel/ChannelVideosTab.tsx
index 6580708..9bf32a6 100644
--- a/frontend/src/features/analytics/channel/ChannelVideosTab.tsx
+++ b/frontend/src/features/analytics/channel/ChannelVideosTab.tsx
@@ -1,35 +1,23 @@
-import type { TooltipValueType } from 'recharts';
-import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, Legend } from 'recharts';
-import ChartPanel from '@/components/ChartPanel';
-import { SERIES, axisProps, axisTick, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
-import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import SurfaceBox from '@/components/SurfaceBox';
+import RankingBarChart from '@/components/RankingBarChart';
+import { PLATFORM_META } from '@/lib/accounts';
import { topVideoRowsOf, topVideosChartOf } from './channelChartData.ts';
import ChannelVideoTable from './ChannelVideoTable';
import type { VideoAnalytics } from '@shared/types/youtube.ts';
-function fullNumber(value: TooltipValueType | undefined): string {
- return fmtNumFull(value as number);
-}
-
export interface ChannelVideosTabProps {
analytics: VideoAnalytics;
}
+// views alone: likes are a different scale and would hide in the same bars; they are in the table below
export default function ChannelVideosTab({ analytics }: ChannelVideosTabProps) {
+ const rows = topVideosChartOf(analytics.top10ByViews).map(video => ({ name: video.name, value: video.views }));
return (
<>
- <ChartPanel title="Top 10 videos by views" height={320}>
- <BarChart data={topVideosChartOf(analytics.top10ByViews)}>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="name" tick={{ ...axisTick, fontSize: 10 }} angle={-15} textAnchor="end" height={70} />
- <YAxis {...axisProps} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={fullNumber} />
- <Bar dataKey="views" fill={SERIES.primary} radius={[4, 4, 0, 0]} name="Views" />
- <Bar dataKey="likes" fill={SERIES.neutral} radius={[4, 4, 0, 0]} name="Likes" />
- <Legend wrapperStyle={legendStyle} />
- </BarChart>
- </ChartPanel>
- <ChannelVideoTable videos={topVideoRowsOf(analytics)} />
+ <SurfaceBox title="Top 10 videos by views">
+ <RankingBarChart rows={rows} label="Views" title="Top 10 videos by views" color={PLATFORM_META.youtube.series} />
+ </SurfaceBox>
+ <ChannelVideoTable title="Top videos by views and likes" videos={topVideoRowsOf(analytics)} />
</>
);
}
diff --git a/frontend/src/features/analytics/channel/TagCloud.tsx b/frontend/src/features/analytics/channel/TagCloud.tsx
index 4b38241..53ed003 100644
--- a/frontend/src/features/analytics/channel/TagCloud.tsx
+++ b/frontend/src/features/analytics/channel/TagCloud.tsx
@@ -2,23 +2,30 @@ import { Badge } from '@/components/ui/badge';
import SurfaceBox from '@/components/SurfaceBox';
import type { YouTubeTagCount } from '@shared/types/youtube.ts';
+const HIGHLIGHTED = 5;
+
export interface TagCloudProps {
tags: YouTubeTagCount[];
}
+// the fill only repeats what the subheader says, and screen readers hear the count as words
export default function TagCloud({ tags }: TagCloudProps) {
return (
- <SurfaceBox title="Most used tags">
+ <SurfaceBox title="Most used tags" subheader={`The ${HIGHLIGHTED} most used are filled. The number is how many videos use the tag.`}>
{tags.length === 0 ? (
<p className="text-small text-ink-faint">These videos have no tags.</p>
) : (
- <div className="flex flex-wrap gap-1.5">
+ <ul className="flex flex-wrap gap-1.5">
{tags.map(({ tag, count }, i) => (
- <Badge key={tag} variant={i < 5 ? 'default' : 'outline'} className="h-6 px-2.5">
- {tag}<span className="opacity-70">{count}</span>
- </Badge>
+ <li key={tag}>
+ <Badge variant={i < HIGHLIGHTED ? 'default' : 'outline'} className="h-6 px-2.5">
+ {tag}
+ <span className="opacity-80" aria-hidden="true">{count}</span>
+ <span className="sr-only">, used in {count} videos{i < HIGHLIGHTED ? ', top 5' : ''}</span>
+ </Badge>
+ </li>
))}
- </div>
+ </ul>
)}
</SurfaceBox>
);
diff --git a/frontend/src/features/analytics/channel/TrendArea.tsx b/frontend/src/features/analytics/channel/TrendArea.tsx
index 4903c60..3d1cff8 100644
--- a/frontend/src/features/analytics/channel/TrendArea.tsx
+++ b/frontend/src/features/analytics/channel/TrendArea.tsx
@@ -11,6 +11,9 @@ export interface TrendAreaProps {
name: string;
percent?: boolean;
gradientId: string;
+ // ChartPanel passes these on to the svg so the focusable plot has a name
+ title?: string;
+ desc?: string;
}
function percentTick(value: number | string): string {
@@ -21,9 +24,13 @@ function fullNumber(value: TooltipValueType | undefined): string {
return fmtNumFull(value as number);
}
-export default function TrendArea({ data, dataKey = 'value', color, name, percent = false, gradientId }: TrendAreaProps) {
+function percentValue(value: TooltipValueType | undefined): string {
+ return `${value}%`;
+}
+
+export default function TrendArea({ data, dataKey = 'value', color, name, percent = false, gradientId, title, desc }: TrendAreaProps) {
return (
- <AreaChart data={data}>
+ <AreaChart data={data} title={title} desc={desc}>
<defs>
<linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={color} stopOpacity={0.2} />
@@ -33,7 +40,7 @@ export default function TrendArea({ data, dataKey = 'value', color, name, percen
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="month" {...axisProps} />
<YAxis {...axisProps} tickFormatter={percent ? percentTick : fmtNum} width={48} />
- <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={percent ? undefined : fullNumber} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={percent ? percentValue : fullNumber} />
<Area type="monotone" dataKey={dataKey} stroke={color} fill={`url(#${gradientId})`} strokeWidth={2} name={name} />
</AreaChart>
);
diff --git a/frontend/src/features/analytics/channel/channelChartData.ts b/frontend/src/features/analytics/channel/channelChartData.ts
index 0087263..da101e2 100644
--- a/frontend/src/features/analytics/channel/channelChartData.ts
+++ b/frontend/src/features/analytics/channel/channelChartData.ts
@@ -1,4 +1,4 @@
-import { SERIES } from '../../../lib/chart.ts';
+import { SERIES, trendSummary } from '../../../lib/chart.ts';
import { CATEGORY_MAP, fmtDate, fmtNum, fmtPercent } from '../../../utils/formatters.ts';
import type {
VideoAnalytics, YouTubeAnalyticsPayload, YouTubeDurationDistribution, YouTubeMonthlyViews, YouTubeVideoSummary,
@@ -68,9 +68,14 @@ export function shortsComparisonOf(analytics: Pick<VideoAnalytics, 'avgShortView
}
// every title gets the ellipsis, even short ones
+// an ellipsis only when the title was actually cut
+function shortTitle(title: string, max = 28): string {
+ return title.length > max ? `${title.slice(0, max)}…` : title;
+}
+
export function topVideosChartOf(videos: (YouTubeVideoSummary | null)[] | null | undefined) {
return (videos || []).map(video => ({
- name: `${(video?.title || '').slice(0, 28)}…`, views: video?.viewCount || 0, likes: video?.likeCount || 0,
+ name: shortTitle(video?.title || ''), views: video?.viewCount || 0, likes: video?.likeCount || 0,
}));
}
@@ -118,3 +123,18 @@ export function likesLabel(likeCount: number | null | undefined): string {
if (likeCount == null) return 'likes hidden';
return `${fmtNum(likeCount)} likes`;
}
+
+export interface MonthlyPoint {
+ month: string;
+ value: number | string;
+}
+
+// the takeaway in words and the numbers as rows, for a month-by-month chart
+export function monthlyChartText(data: readonly MonthlyPoint[], unit: string, percent = false) {
+ const points = data.map(point => ({ name: point.month, value: Number(point.value) || 0 }));
+ const format = percent ? (value: number) => `${value}%` : fmtNum;
+ return {
+ summary: trendSummary(points, format, unit),
+ rows: points.map(point => ({ month: point.name, value: percent ? `${point.value}%` : point.value })),
+ };
+}
diff --git a/frontend/src/features/analytics/channel/useChannelAnalytics.ts b/frontend/src/features/analytics/channel/useChannelAnalytics.ts
index d671d1a..145c4d0 100644
--- a/frontend/src/features/analytics/channel/useChannelAnalytics.ts
+++ b/frontend/src/features/analytics/channel/useChannelAnalytics.ts
@@ -3,22 +3,48 @@ import { api } from '../../../services/api';
import type { AppContextValue } from '../../../context/AppContext';
import type { YouTubeAnalyticsPayload } from '@shared/types/youtube.ts';
+// skeletons only before the first answer; a refresh keeps the page, its tab and its scroll position
export function useChannelAnalytics(id: string | undefined, showToast: AppContextValue['showToast']) {
const [data, setData] = useState<YouTubeAnalyticsPayload | null>(null);
- const [loading, setLoading] = useState(true);
+ // the channel the shown answer belongs to; skeletons show until it matches the channel in the address
+ const [loadedFor, setLoadedFor] = useState<string | null>(null);
+ const [refreshing, setRefreshing] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ // channel analytics are always fetched live, so their age is the moment they arrived
+ const [fetchedAt, setFetchedAt] = useState<string | null>(null);
- const loadAnalytics = useCallback(async () => {
- setLoading(true);
+ const fetchAnalytics = useCallback(async (): Promise<boolean> => {
+ if (!id) return false;
try {
- setData(await api.getAnalytics(id!));
+ setData(await api.getAnalytics(id));
+ setFetchedAt(new Date().toISOString());
+ setError(null);
+ return true;
} catch (err) {
- showToast(`Couldn't load channel analytics. ${(err as Error).message}`, 'error');
+ setError(`Couldn't load channel analytics. ${(err as Error).message}`);
+ return false;
} finally {
- setLoading(false);
+ setLoadedFor(id);
}
- }, [id, showToast]);
+ }, [id]);
- useEffect(() => { if (id) loadAnalytics(); }, [id, loadAnalytics]);
+ useEffect(() => {
+ fetchAnalytics();
+ }, [fetchAnalytics]);
- return { data, loading, loadAnalytics };
+ const initialLoading = loadedFor !== (id ?? null);
+
+ const retry = useCallback(() => {
+ setLoadedFor(null);
+ fetchAnalytics();
+ }, [fetchAnalytics]);
+
+ const refresh = useCallback(async () => {
+ setRefreshing(true);
+ const ok = await fetchAnalytics();
+ setRefreshing(false);
+ if (ok) showToast('Channel analytics refreshed');
+ }, [fetchAnalytics, showToast]);
+
+ return { data, initialLoading, refreshing, error, fetchedAt, retry, refresh };
}
diff --git a/frontend/src/features/analytics/instagram/InstagramAnalytics.tsx b/frontend/src/features/analytics/instagram/InstagramAnalytics.tsx
index 4386ae7..2a86279 100644
--- a/frontend/src/features/analytics/instagram/InstagramAnalytics.tsx
+++ b/frontend/src/features/analytics/instagram/InstagramAnalytics.tsx
@@ -1,13 +1,15 @@
import { useParams } from 'react-router-dom';
import { UserX } from 'lucide-react';
-import { Progress } from '@/components/ui/progress';
+import { Alert, AlertAction, AlertDescription } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
import PageHeader from '@/components/PageHeader';
import SurfaceBox from '@/components/SurfaceBox';
-import { EmptyState, PageSkeleton } from '@/components/StateViews';
+import { EmptyState, ErrorState, PageSkeleton } from '@/components/StateViews';
import { useAppContext } from '../../../context/AppContext';
import { useAccountAnalytics } from '../../../hooks/use-account-analytics';
+import { useDocumentTitle } from '@/hooks/use-document-title';
+import { accountName } from '@/lib/accounts';
import { api } from '../../../services/api';
-import { timeAgo } from '../../../utils/formatters';
import { instagramChartsOf } from './instagramAnalyticsData.ts';
import type { InstagramAnalytics as InstagramAnalyticsData } from '@shared/types/instagram.ts';
import InstagramHeader from './InstagramHeader';
@@ -26,7 +28,10 @@ export default function InstagramAnalytics() {
const { id } = useParams();
const { accounts } = useAppContext();
const account = accounts.find(item => item.id === id);
- const { loading, profile, analytics, refreshing, handleRefresh } = useAccountAnalytics(account, api.getIGAnalytics, 'Instagram');
+ const { initialLoading, error, profile, analytics, fetchedAt, refreshing, handleRefresh, retry } = useAccountAnalytics(
+ account, api.getIGAnalytics, 'Instagram', { live: true },
+ );
+ useDocumentTitle(account ? accountName(account) : null);
if (!account) {
return (
@@ -39,34 +44,51 @@ export default function InstagramAnalytics() {
);
}
- if (loading) return <PageSkeleton metrics={6} />;
+ if (initialLoading) return <PageSkeleton metrics={6} />;
const profileData = profile || account;
- const analyticsData: Partial<InstagramAnalyticsData> = analytics || {};
+
+ if (!analytics) {
+ return (
+ <div className="flex flex-col gap-6">
+ <InstagramHeader account={account} profile={profileData} back={BACK} refreshing={refreshing} onRefresh={handleRefresh} fetchedAt={null} />
+ <SurfaceBox>
+ <ErrorState title="Instagram analytics could not load" description={error ?? undefined} onRetry={retry} />
+ </SurfaceBox>
+ </div>
+ );
+ }
+
+ const analyticsData: Partial<InstagramAnalyticsData> = analytics;
const charts = instagramChartsOf(analyticsData);
const hashtags = analyticsData.hashtagAnalysis || [];
const topPosts = analyticsData.topPosts || [];
return (
<div className="flex flex-col gap-6">
- <InstagramHeader account={account} profile={profileData} back={BACK} refreshing={refreshing} onRefresh={handleRefresh} />
-
- {refreshing && <Progress value={null} aria-label="Refreshing account" />}
+ <InstagramHeader account={account} profile={profileData} back={BACK} refreshing={refreshing} onRefresh={handleRefresh} fetchedAt={fetchedAt} />
- <InstagramMetrics profile={profileData} analytics={analyticsData} />
- <InstagramInsightChips analytics={analyticsData} />
- <InstagramEngagementCharts charts={charts} />
- <InstagramPostCharts charts={charts} />
+ {error && (
+ <Alert variant="destructive" role="alert">
+ <AlertDescription>{error} The numbers below are from the last successful load.</AlertDescription>
+ <AlertAction><Button size="xs" variant="outline" onClick={retry}>Try again</Button></AlertAction>
+ </Alert>
+ )}
- {hashtags.length > 0 && <InstagramHashtags hashtags={hashtags} />}
+ <div className="flex flex-col gap-6" aria-busy={refreshing}>
+ <InstagramMetrics profile={profileData} analytics={analyticsData} />
+ <InstagramInsightChips analytics={analyticsData} />
+ <InstagramEngagementCharts charts={charts} />
+ <InstagramPostCharts charts={charts} />
- <InstagramRecentGrid posts={analyticsData.recentMedia || []} fetchedPosts={analyticsData.fetchedPosts} />
+ {hashtags.length > 0 && <InstagramHashtags hashtags={hashtags} />}
- {topPosts.length > 0 && <InstagramTopPostsTable posts={topPosts} />}
+ <InstagramRecentGrid posts={analyticsData.recentMedia || []} fetchedPosts={analyticsData.fetchedPosts} />
- {charts.typeRows.length > 0 && <InstagramTypeSummaryTable rows={charts.typeRows} />}
+ {topPosts.length > 0 && <InstagramTopPostsTable posts={topPosts} />}
- <p className="text-center text-caption text-ink-faint">Last updated {timeAgo(account.lastUpdated).toLowerCase()}</p>
+ {charts.typeRows.length > 0 && <InstagramTypeSummaryTable rows={charts.typeRows} />}
+ </div>
</div>
);
}
diff --git a/frontend/src/features/analytics/instagram/InstagramEngagementCharts.tsx b/frontend/src/features/analytics/instagram/InstagramEngagementCharts.tsx
index 9a7d7b5..a266c1f 100644
--- a/frontend/src/features/analytics/instagram/InstagramEngagementCharts.tsx
+++ b/frontend/src/features/analytics/instagram/InstagramEngagementCharts.tsx
@@ -2,25 +2,47 @@ import {
AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, PieChart, Pie, Cell, Legend,
} from 'recharts';
import ChartPanel from '@/components/ChartPanel';
-import { SERIES, axisProps, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { SERIES, axisProps, gridProps, legendStyle, rankingSummary, tooltipCursor, tooltipStyle, trendSummary } from '@/lib/chart';
import type { TooltipValueType } from 'recharts';
-import { fmtNum } from '../../../utils/formatters';
+import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import type { NumberLike } from '../../../utils/formatters';
import type { InstagramCharts } from './instagramAnalyticsData.ts';
function formatItems(value: TooltipValueType | undefined, name: string | number | undefined) {
return [`${value} items`, name];
}
+const full = (value: unknown) => fmtNumFull(value as NumberLike);
+
export interface InstagramEngagementChartsProps {
charts: InstagramCharts;
}
export default function InstagramEngagementCharts({ charts }: InstagramEngagementChartsProps) {
const { timeline, contentMix, typeRows, dayOfWeek } = charts;
+ const likesTrend = timeline.map(point => ({ name: point.name, value: point.likes }));
+ const bestDays = dayOfWeek.map(day => ({ name: day.name, value: day.avgEngagement }));
+ const biggestType = rankingSummary(contentMix, fmtNum, 'items');
return (
<>
<div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
- <ChartPanel title="Engagement over time" className="xl:col-span-2" empty={timeline.length === 0} emptyMessage="Not enough posts to chart a timeline">
+ <ChartPanel
+ title="Likes and comments by month"
+ className="xl:col-span-2"
+ empty={timeline.length === 0}
+ emptyMessage="Not enough posts to chart a timeline"
+ summary={trendSummary(likesTrend, fmtNum, 'likes')}
+ table={{
+ caption: 'Likes and comments by month',
+ columns: [
+ { key: 'name', label: 'Month' },
+ { key: 'posts', label: 'Posts', numeric: true, format: full },
+ { key: 'likes', label: 'Likes', numeric: true, format: full },
+ { key: 'comments', label: 'Comments', numeric: true, format: full },
+ ],
+ rows: timeline,
+ }}
+ >
<AreaChart data={timeline}>
<defs>
<linearGradient id="igLikesGrad" x1="0" y1="0" x2="0" y2="1">
@@ -31,13 +53,22 @@ export default function InstagramEngagementCharts({ charts }: InstagramEngagemen
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="name" {...axisProps} />
<YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={value => fmtNumFull(value as NumberLike)} />
<Area type="monotone" dataKey="likes" name="Likes" stroke={SERIES.primary} strokeWidth={2} fill="url(#igLikesGrad)" />
- <Area type="monotone" dataKey="comments" name="Comments" stroke={SERIES.cool} strokeWidth={2} fill="transparent" />
+ <Area type="monotone" dataKey="comments" name="Comments" stroke={SERIES.neutral} strokeWidth={2} strokeDasharray="5 3" fill="transparent" />
<Legend wrapperStyle={legendStyle} />
</AreaChart>
</ChartPanel>
- <ChartPanel title="Content type mix" empty={contentMix.length === 0}>
+ <ChartPanel
+ title="Content type mix"
+ empty={contentMix.length === 0}
+ summary={biggestType}
+ table={{
+ caption: 'Content type mix',
+ columns: [{ key: 'name', label: 'Type' }, { key: 'value', label: 'Items', numeric: true, format: full }],
+ rows: contentMix,
+ }}
+ >
<PieChart>
<Pie data={contentMix} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={48} paddingAngle={2} strokeWidth={0}>
{contentMix.map(entry => <Cell key={entry.name} fill={entry.color} />)}
@@ -49,26 +80,60 @@ export default function InstagramEngagementCharts({ charts }: InstagramEngagemen
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <ChartPanel title="Performance by content type" height={260} empty={typeRows.length === 0}>
+ <ChartPanel
+ title="Average likes and comments by content type"
+ height={260}
+ empty={typeRows.length === 0}
+ summary={rankingSummary(typeRows.map(row => ({ name: row.name, value: row.avgLikes })), fmtNum, 'likes per item on average')}
+ table={{
+ caption: 'Average likes and comments by content type',
+ columns: [
+ { key: 'name', label: 'Type' },
+ { key: 'avgLikes', label: 'Average likes', numeric: true, format: full },
+ { key: 'avgComments', label: 'Average comments', numeric: true, format: full },
+ ],
+ rows: typeRows,
+ }}
+ >
<BarChart data={typeRows}>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="name" {...axisProps} />
<YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={value => fmtNumFull(value as NumberLike)} />
<Bar dataKey="avgLikes" name="Average likes" fill={SERIES.primary} radius={[4, 4, 0, 0]} />
<Bar dataKey="avgComments" name="Average comments" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />
<Legend wrapperStyle={legendStyle} />
</BarChart>
</ChartPanel>
- <ChartPanel title="Best days to post" height={260} empty={dayOfWeek.length === 0}>
+ <ChartPanel
+ title="Interactions per post by day"
+ subheader="Average likes and comments a post got, by the day it went out"
+ height={260}
+ empty={dayOfWeek.length === 0}
+ summary={rankingSummary(bestDays, fmtNum, 'interactions per post')}
+ table={{
+ caption: 'Interactions per post by day',
+ columns: [
+ { key: 'name', label: 'Day' },
+ { key: 'avgEngagement', label: 'Interactions per post', numeric: true, format: full },
+ { key: 'posts', label: 'Posts', numeric: true, format: full },
+ ],
+ rows: dayOfWeek,
+ }}
+ >
<BarChart data={dayOfWeek}>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="name" {...axisProps} />
<YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="avgEngagement" name="Average engagement" fill={SERIES.warm} radius={[4, 4, 0, 0]} />
- <Bar dataKey="posts" name="Posts" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />
- <Legend wrapperStyle={legendStyle} />
+ <ReTooltip
+ contentStyle={tooltipStyle}
+ cursor={tooltipCursor}
+ formatter={(value, _name, item) => [
+ `${fmtNumFull(value as NumberLike)} (${(item.payload as { posts: number }).posts} posts)`,
+ 'Interactions per post',
+ ]}
+ />
+ <Bar dataKey="avgEngagement" name="Interactions per post" fill={SERIES.warm} radius={[4, 4, 0, 0]} />
</BarChart>
</ChartPanel>
</div>
diff --git a/frontend/src/features/analytics/instagram/InstagramHashtags.tsx b/frontend/src/features/analytics/instagram/InstagramHashtags.tsx
index b27b324..52e77ca 100644
--- a/frontend/src/features/analytics/instagram/InstagramHashtags.tsx
+++ b/frontend/src/features/analytics/instagram/InstagramHashtags.tsx
@@ -1,27 +1,36 @@
import { Hash } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import SurfaceBox from '@/components/SurfaceBox';
import { fmtNum } from '../../../utils/formatters';
import type { InstagramHashtagStats } from '@shared/types/instagram.ts';
+const HIGHLIGHTED = 5;
+
export interface InstagramHashtagsProps {
hashtags: InstagramHashtagStats[];
}
+// the use count is printed on each tag and the average spelt out for screen readers; nothing hides behind hover
export default function InstagramHashtags({ hashtags }: InstagramHashtagsProps) {
return (
- <SurfaceBox title="Top hashtags">
- <div className="flex flex-wrap gap-1.5">
+ <SurfaceBox title="Top hashtags" subheader={`The ${HIGHLIGHTED} most used are filled. The number is how many posts used the tag.`}>
+ <ul className="flex flex-wrap gap-1.5">
{hashtags.slice(0, 20).map((hashtag, i) => (
- <Tooltip key={hashtag.tag}>
- <TooltipTrigger render={<Badge variant={i < 5 ? 'default' : 'outline'} className="h-6 cursor-default px-2.5" />}>
- <Hash />{hashtag.tag}<span className="opacity-70">{hashtag.count}</span>
- </TooltipTrigger>
- <TooltipContent>Used {hashtag.count} times, {fmtNum(hashtag.avgEngagement)} average engagement</TooltipContent>
- </Tooltip>
+ <li key={hashtag.tag}>
+ <Badge
+ variant={i < HIGHLIGHTED ? 'default' : 'outline'}
+ className="h-6 px-2.5"
+ title={`Used in ${hashtag.count} posts, ${fmtNum(hashtag.avgEngagement)} interactions per post on average`}
+ >
+ <Hash aria-hidden="true" />{hashtag.tag}
+ <span className="opacity-80" aria-hidden="true">{hashtag.count}</span>
+ <span className="sr-only">
+ , used in {hashtag.count} posts, {fmtNum(hashtag.avgEngagement)} interactions per post on average{i < HIGHLIGHTED ? ', top 5' : ''}
+ </span>
+ </Badge>
+ </li>
))}
- </div>
+ </ul>
</SurfaceBox>
);
}
diff --git a/frontend/src/features/analytics/instagram/InstagramHeader.tsx b/frontend/src/features/analytics/instagram/InstagramHeader.tsx
index d5bf98e..d078fc0 100644
--- a/frontend/src/features/analytics/instagram/InstagramHeader.tsx
+++ b/frontend/src/features/analytics/instagram/InstagramHeader.tsx
@@ -1,8 +1,7 @@
-import { RefreshCw } from 'lucide-react';
-import { Button } from '@/components/ui/button';
import PageHeader from '@/components/PageHeader';
+import RefreshButton from '@/components/RefreshButton';
+import DataFreshness from '@/components/DataFreshness';
import { AccountAvatar } from '@/components/platform';
-import { cn } from '@/lib/utils';
import type { PageHeaderBack } from '@/components/PageHeader';
import type { AppAccount } from '../../../utils/formatters';
import type { InstagramProfileFields } from './instagramAnalyticsData.ts';
@@ -13,26 +12,23 @@ export interface InstagramHeaderProps {
back: PageHeaderBack;
refreshing: boolean;
onRefresh: () => void;
+ fetchedAt: string | null;
}
-export default function InstagramHeader({ account, profile, back, refreshing, onRefresh }: InstagramHeaderProps) {
+export default function InstagramHeader({ account, profile, back, refreshing, onRefresh, fetchedAt }: InstagramHeaderProps) {
return (
<PageHeader
back={back}
- media={<AccountAvatar account={{ ...account, profilePictureUrl: profile.profilePictureUrl || account.profilePictureUrl }} size="xl" showPlatform />}
+ media={<AccountAvatar account={{ ...account, profilePictureUrl: profile.profilePictureUrl || account.profilePictureUrl }} size="xl" showPlatform decorative />}
title={profile.name || profile.username}
description={
<span className="flex flex-col gap-1">
<span>@{profile.username}</span>
- {profile.biography && <span className="line-clamp-2 max-w-xl text-small text-ink-faint">{profile.biography}</span>}
+ {profile.biography && <span className="line-clamp-2 max-w-prose text-small text-ink-faint" title={profile.biography}>{profile.biography}</span>}
+ <DataFreshness fetchedAt={fetchedAt} />
</span>
}
- actions={
- <Button variant="outline" size="sm" onClick={onRefresh} disabled={refreshing}>
- <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />
- {refreshing ? 'Refreshing' : 'Refresh'}
- </Button>
- }
+ actions={<RefreshButton refreshing={refreshing} onRefresh={onRefresh} />}
/>
);
}
diff --git a/frontend/src/features/analytics/instagram/InstagramInsightChips.tsx b/frontend/src/features/analytics/instagram/InstagramInsightChips.tsx
index 19e246b..1e169d5 100644
--- a/frontend/src/features/analytics/instagram/InstagramInsightChips.tsx
+++ b/frontend/src/features/analytics/instagram/InstagramInsightChips.tsx
@@ -1,4 +1,4 @@
-import { Clock, Star, TrendingUp, Trophy } from 'lucide-react';
+import { Clock, Star, Activity } from 'lucide-react';
import type { ReactNode } from 'react';
import type { LucideIcon } from 'lucide-react';
import { fmtNum } from '../../../utils/formatters';
@@ -12,10 +12,10 @@ interface InsightChipProps {
function InsightChip({ icon, children }: InsightChipProps) {
const Icon = icon;
return (
- <span className="inline-flex h-8 items-center gap-1.5 rounded-field border border-line bg-surface px-3 text-small font-medium text-ink">
- <Icon className="size-3.5 stroke-[1.75] text-ink-faint" />
+ <li className="inline-flex h-8 items-center gap-1.5 rounded-field border border-line bg-surface px-3 text-small font-medium text-ink">
+ <Icon className="size-3.5 stroke-[1.75] text-ink-faint" aria-hidden="true" />
{children}
- </span>
+ </li>
);
}
@@ -25,11 +25,10 @@ export interface InstagramInsightChipsProps {
export default function InstagramInsightChips({ analytics }: InstagramInsightChipsProps) {
return (
- <div className="flex flex-wrap items-center gap-2">
+ <ul aria-label="Posting insights" className="flex flex-wrap items-center gap-2">
{analytics.bestPostingDay && <InsightChip icon={Star}>Best day: {analytics.bestPostingDay}</InsightChip>}
{analytics.bestPostingHour && <InsightChip icon={Clock}>Best hour: {analytics.bestPostingHour}</InsightChip>}
- <InsightChip icon={TrendingUp}>Average engagement: {fmtNum(analytics.avgEngagement || 0)} per post</InsightChip>
- <InsightChip icon={Trophy}>Consistency: {analytics.consistencyScore || 0}/100</InsightChip>
- </div>
+ <InsightChip icon={Activity}>Interactions per post: {fmtNum(analytics.avgEngagement || 0)} likes and comments</InsightChip>
+ </ul>
);
}
diff --git a/frontend/src/features/analytics/instagram/InstagramMetrics.tsx b/frontend/src/features/analytics/instagram/InstagramMetrics.tsx
index 4f73ac9..5f5d25c 100644
--- a/frontend/src/features/analytics/instagram/InstagramMetrics.tsx
+++ b/frontend/src/features/analytics/instagram/InstagramMetrics.tsx
@@ -1,73 +1,69 @@
-import {
- BarChart2, Calendar, Clapperboard, Eye, Film, Flame, Heart, Image, MessageCircle, TrendingUp, Trophy, UserPlus, Users, Zap,
-} from 'lucide-react';
-import type { LucideIcon } from 'lucide-react';
import MetricBox from '@/components/MetricBox';
-import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import MetricDetails from '@/components/MetricDetails';
+import Num from '@/components/Num';
+import { METRIC_ICONS } from '@/lib/metricIcons';
+import { fmtNum } from '../../../utils/formatters';
import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';
import { followerRatio, typeViewsSubtitle } from './instagramAnalyticsData.ts';
import type { InstagramProfileFields } from './instagramAnalyticsData.ts';
-import type {
- InstagramAnalytics, InstagramContentType, InstagramContentTypeStats, InstagramContentTypeStatsMap,
-} from '@shared/types/instagram.ts';
-
-const CONTENT_TYPE_ICONS: Record<InstagramContentType, LucideIcon> = { reel: Clapperboard, post: Image, video: Film };
-
-interface ContentTypeMetricProps {
- type: InstagramContentType;
- stats: Partial<InstagramContentTypeStats>;
-}
-
-function ContentTypeMetric({ type, stats }: ContentTypeMetricProps) {
- const Icon = CONTENT_TYPE_ICONS[type];
- return (
- <MetricBox
- small
- icon={<Icon />}
- label={IG_CONTENT_TYPE_META[type].plural}
- value={fmtNum(stats.count)}
- subtitle={typeViewsSubtitle(stats)}
- />
- );
-}
+import type { InstagramAnalytics, InstagramContentTypeStatsMap } from '@shared/types/instagram.ts';
export interface InstagramMetricsProps {
profile: InstagramProfileFields;
analytics: Partial<InstagramAnalytics>;
}
+const { audience: Audience, views: Views, instagramLikes: Likes, comments: Comments, rate: Rate } = METRIC_ICONS;
+
export default function InstagramMetrics({ profile, analytics }: InstagramMetricsProps) {
const typeStats: Partial<InstagramContentTypeStatsMap> = analytics.contentTypeStats || {};
+ const analyzed = analytics.fetchedPosts || 0;
+ const postsPeriod = `Last ${analyzed} posts`;
return (
- <div className="flex flex-col gap-3">
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<Users />} label="Followers" value={fmtNum(profile.followersCount)} subtitle={fmtNumFull(profile.followersCount)} highlight />
- <MetricBox small icon={<UserPlus />} label="Following" value={fmtNum(profile.followsCount)} subtitle={fmtNumFull(profile.followsCount)} />
- <MetricBox small icon={<Image />} label="Total posts" value={fmtNum(analytics.totalPosts || profile.mediaCount)} subtitle={`${analytics.fetchedPosts || 0} analyzed`} />
- <MetricBox small icon={<Heart />} label="Total likes" value={fmtNum(analytics.totalLikes)} subtitle={fmtNumFull(analytics.totalLikes)} />
- <MetricBox small icon={<MessageCircle />} label="Total comments" value={fmtNum(analytics.totalComments)} subtitle={fmtNumFull(analytics.totalComments)} />
- <MetricBox small icon={<TrendingUp />} label="Engagement rate" value={`${analytics.engagementRate || 0}%`} subtitle={`${fmtNum(analytics.avgLikes)} likes per post on average`} />
- </div>
- <div className="grid grid-cols-2 gap-3 xl:grid-cols-4">
- <MetricBox small icon={<Eye />} label="Total views" value={fmtNum(analytics.totalViews)} subtitle={`${analytics.mediaWithViews || 0} of ${analytics.fetchedPosts || 0} items report views`} />
- {IG_CONTENT_TYPES.map(type => <ContentTypeMetric key={type} type={type} stats={typeStats[type] || {}} />)}
- </div>
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<Zap />} label="Likes per post" value={fmtNum(analytics.avgLikes)} />
- <MetricBox small icon={<MessageCircle />} label="Comments per post" value={fmtNum(analytics.avgComments)} />
- <MetricBox small icon={<BarChart2 />} label="Median likes" value={fmtNum(analytics.medianLikes)} />
- <MetricBox small icon={<Users />} label="Follower ratio" value={followerRatio(profile)} subtitle="Followers per account followed" />
- <MetricBox small icon={<Heart />} label="Likes per follower" value={`${analytics.likesPerFollower || 0}%`} subtitle="Per post, on average" />
- <MetricBox small icon={<TrendingUp />} label="Likes per comment" value={`${analytics.likesToCommentsRatio || 0}:1`} />
- </div>
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
- <MetricBox small icon={<Calendar />} label="Posts per week" value={analytics.postFrequency?.perWeek || 0} subtitle={`${analytics.postFrequency?.perMonth || 0} per month`} />
- <MetricBox small icon={<Calendar />} label="Last 7 days" value={analytics.postsLast7Days || 0} subtitle="Posts" />
- <MetricBox small icon={<Calendar />} label="Last 30 days" value={analytics.postsLast30Days || 0} subtitle="Posts" />
- <MetricBox small icon={<Calendar />} label="Last 90 days" value={analytics.postsLast90Days || 0} subtitle="Posts" />
- <MetricBox small icon={<Flame />} label="Virality" value={`${analytics.viralityScore || 0}x`} subtitle="Best post against the average" />
- <MetricBox small icon={<Trophy />} label="Consistency" value={`${analytics.consistencyScore || 0}/100`} subtitle="Engagement stability" />
+ <div className="flex flex-col gap-4">
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-5">
+ <MetricBox small icon={<Audience />} label="Followers" value={<Num value={profile.followersCount} />} period="Now" subtitle={`Following ${fmtNum(profile.followsCount)}`} highlight />
+ <MetricBox small icon={<Views />} label="Views" value={<Num value={analytics.totalViews} />} period={postsPeriod} subtitle={`${analytics.mediaWithViews || 0} report views`} />
+ <MetricBox small icon={<Likes />} label="Likes" value={<Num value={analytics.totalLikes} />} period={postsPeriod} />
+ <MetricBox small icon={<Comments />} label="Comments" value={<Num value={analytics.totalComments} />} period={postsPeriod} />
+ <MetricBox small icon={<Rate />} label="Engagement rate" value={`${analytics.engagementRate || 0}%`} period={postsPeriod} subtitle="Likes and comments per post, per follower" />
</div>
+
+ <MetricDetails
+ subheader={`Worked out from the ${analyzed} most recent posts out of ${fmtNum(analytics.totalPosts || profile.mediaCount)}.`}
+ groups={[
+ {
+ title: 'Content',
+ items: IG_CONTENT_TYPES.map(type => ({
+ label: IG_CONTENT_TYPE_META[type].plural,
+ value: <Num value={typeStats[type]?.count} />,
+ hint: typeViewsSubtitle(typeStats[type] || {}),
+ })),
+ },
+ {
+ title: 'Per post',
+ items: [
+ { label: 'Likes per post', value: <Num value={analytics.avgLikes} /> },
+ { label: 'Comments per post', value: <Num value={analytics.avgComments} /> },
+ { label: 'Median likes', value: <Num value={analytics.medianLikes} />, hint: 'Half the posts have more, half have fewer' },
+ { label: 'Likes per follower', value: `${analytics.likesPerFollower || 0}%`, hint: 'Per post, on average' },
+ { label: 'Likes per comment', value: `${analytics.likesToCommentsRatio || 0} to 1` },
+ ],
+ },
+ {
+ title: 'Publishing and audience',
+ items: [
+ { label: 'Posts per week', value: analytics.postFrequency?.perWeek || 0, hint: `${analytics.postFrequency?.perMonth || 0} per month` },
+ { label: 'Posts in the last 7 days', value: analytics.postsLast7Days || 0 },
+ { label: 'Posts in the last 30 days', value: analytics.postsLast30Days || 0 },
+ { label: 'Posts in the last 90 days', value: analytics.postsLast90Days || 0 },
+ { label: 'Virality', value: `${analytics.viralityScore || 0}x`, hint: 'Interactions on the best post, as a multiple of the average post' },
+ { label: 'Consistency', value: `${analytics.consistencyScore || 0} of 100`, hint: 'How steady interactions are from post to post; 100 means every post does about as well' },
+ { label: 'Follower ratio', value: followerRatio(profile), hint: 'Followers per account followed' },
+ ],
+ },
+ ]}
+ />
</div>
);
}
diff --git a/frontend/src/features/analytics/instagram/InstagramPostCharts.tsx b/frontend/src/features/analytics/instagram/InstagramPostCharts.tsx
index ae3b6d6..7edbb08 100644
--- a/frontend/src/features/analytics/instagram/InstagramPostCharts.tsx
+++ b/frontend/src/features/analytics/instagram/InstagramPostCharts.tsx
@@ -1,9 +1,12 @@
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, Legend } from 'recharts';
import ChartPanel from '@/components/ChartPanel';
-import { SERIES, axisProps, gridProps, legendStyle, tooltipCursor, tooltipStyle } from '@/lib/chart';
-import { fmtNum } from '../../../utils/formatters';
+import { SERIES, axisProps, gridProps, legendStyle, rankingSummary, tooltipCursor, tooltipStyle, trendSummary } from '@/lib/chart';
+import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import type { NumberLike } from '../../../utils/formatters';
import type { InstagramCharts } from './instagramAnalyticsData.ts';
+const full = (value: unknown) => fmtNumFull(value as NumberLike);
+
export interface InstagramPostChartsProps {
charts: InstagramCharts;
}
@@ -13,36 +16,74 @@ export default function InstagramPostCharts({ charts }: InstagramPostChartsProps
return (
<>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <ChartPanel title="Top posts by engagement" height={260} empty={topPosts.length === 0}>
+ <ChartPanel
+ title="Top posts by likes and comments"
+ subheader="Numbered as in the top posts table"
+ height={260}
+ empty={topPosts.length === 0}
+ summary={rankingSummary(topPosts.map(post => ({ name: `Post ${post.name}`, value: post.likes })), fmtNum, 'likes')}
+ table={{
+ caption: 'Top posts by likes and comments',
+ columns: [
+ { key: 'name', label: 'Post' },
+ { key: 'likes', label: 'Likes', numeric: true, format: full },
+ { key: 'comments', label: 'Comments', numeric: true, format: full },
+ ],
+ rows: topPosts,
+ }}
+ >
<BarChart data={topPosts}>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="name" {...axisProps} />
<YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={value => fmtNumFull(value as NumberLike)} />
<Bar dataKey="likes" name="Likes" fill={SERIES.primary} radius={[4, 4, 0, 0]} />
<Bar dataKey="comments" name="Comments" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />
<Legend wrapperStyle={legendStyle} />
</BarChart>
</ChartPanel>
- <ChartPanel title="Caption length and engagement" height={260} empty={caption.length === 0}>
+ <ChartPanel
+ title="Interactions by caption length"
+ subheader="Average likes and comments a post got, by how long its caption is"
+ height={260}
+ empty={caption.length === 0}
+ summary={rankingSummary(caption.map(row => ({ name: row.label, value: row.avgEngagement })), fmtNum, 'interactions per post')}
+ table={{
+ caption: 'Interactions by caption length',
+ columns: [
+ { key: 'label', label: 'Caption length' },
+ { key: 'avgEngagement', label: 'Interactions per post', numeric: true, format: full },
+ ],
+ rows: caption,
+ }}
+ >
<BarChart data={caption}>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="label" {...axisProps} />
<YAxis {...axisProps} width={44} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="avgEngagement" name="Average engagement" fill={SERIES.cool} radius={[4, 4, 0, 0]} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={value => fmtNumFull(value as NumberLike)} />
+ <Bar dataKey="avgEngagement" name="Interactions per post" fill={SERIES.warm} radius={[4, 4, 0, 0]} />
</BarChart>
</ChartPanel>
</div>
{timeline.length > 1 && (
- <ChartPanel title="Posts per month" height={220}>
+ <ChartPanel
+ title="Posts per month"
+ height={220}
+ summary={trendSummary(timeline.map(point => ({ name: point.name, value: point.posts })), fmtNum, 'posts')}
+ table={{
+ caption: 'Posts per month',
+ columns: [{ key: 'name', label: 'Month' }, { key: 'posts', label: 'Posts', numeric: true, format: full }],
+ rows: timeline,
+ }}
+ >
<BarChart data={timeline}>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="name" {...axisProps} />
- <YAxis {...axisProps} width={44} />
+ <YAxis {...axisProps} width={44} allowDecimals={false} />
<ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} />
- <Bar dataKey="posts" name="Posts" fill={SERIES.warm} radius={[4, 4, 0, 0]} />
+ <Bar dataKey="posts" name="Posts" fill={SERIES.neutral} radius={[4, 4, 0, 0]} />
</BarChart>
</ChartPanel>
)}
diff --git a/frontend/src/features/analytics/instagram/InstagramRecentGrid.tsx b/frontend/src/features/analytics/instagram/InstagramRecentGrid.tsx
index a16a3a6..dda2704 100644
--- a/frontend/src/features/analytics/instagram/InstagramRecentGrid.tsx
+++ b/frontend/src/features/analytics/instagram/InstagramRecentGrid.tsx
@@ -1,12 +1,15 @@
-import { Eye, Heart, Image, MessageCircle } from 'lucide-react';
+import { Image } from 'lucide-react';
import SurfaceBox from '@/components/SurfaceBox';
import { MediaChip } from '@/components/MediaCard';
import { EmptyState } from '@/components/StateViews';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import type { SyntheticEvent } from 'react';
import { fmtNum } from '../../../utils/formatters';
import { fmtIGViews, igContentTypeMeta, igThumbnail } from '../../../utils/instagramContent';
import type { InstagramMedia } from '@shared/types/instagram.ts';
+const { views: Views, instagramLikes: Likes, comments: Comments } = METRIC_ICONS;
+
function hideBrokenImage(e: SyntheticEvent<HTMLImageElement>) {
e.currentTarget.style.display = 'none';
}
@@ -15,26 +18,32 @@ interface RecentPostProps {
post: InstagramMedia;
}
+// the figures sit under the picture at all times: hover never reaches a touch screen or a screen reader
function RecentPost({ post }: RecentPostProps) {
const thumb = igThumbnail(post);
+ const type = igContentTypeMeta(post.contentType).label;
return (
- <a
- href={post.permalink}
- target="_blank"
- rel="noopener noreferrer"
- aria-label={`Open ${igContentTypeMeta(post.contentType).label.toLowerCase()} on Instagram`}
- className="group relative aspect-square overflow-hidden rounded-control border border-line bg-surface-sunken focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
- >
- {thumb && <img src={thumb} alt="" loading="lazy" className="size-full object-cover" onError={hideBrokenImage} />}
- {post.contentType !== 'post' && (
- <span className="absolute top-1 right-1"><MediaChip className="px-1.5 text-[0.625rem]">{igContentTypeMeta(post.contentType).label}</MediaChip></span>
- )}
- <span className="absolute inset-x-0 bottom-0 flex justify-center gap-2 bg-gradient-to-t from-media-scrim/80 to-transparent pt-4 pb-1 text-[0.625rem] font-semibold text-on-media opacity-0 transition-opacity duration-(--duration-base) group-hover:opacity-100 group-focus-visible:opacity-100 [&_svg]:size-2.5">
- <span className="flex items-center gap-0.5"><Eye />{fmtIGViews(post.viewCount)}</span>
- <span className="flex items-center gap-0.5"><Heart />{fmtNum(post.likeCount)}</span>
- <span className="flex items-center gap-0.5"><MessageCircle />{fmtNum(post.commentsCount)}</span>
- </span>
- </a>
+ <li>
+ <a
+ href={post.permalink}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="group flex flex-col gap-1.5 rounded-control focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
+ >
+ <span className="relative block aspect-square overflow-hidden rounded-control border border-line bg-surface-sunken">
+ {thumb && <img src={thumb} alt="" loading="lazy" className="size-full object-cover" onError={hideBrokenImage} />}
+ {post.contentType !== 'post' && (
+ <span className="absolute top-1 right-1"><MediaChip>{type}</MediaChip></span>
+ )}
+ </span>
+ <span className="sr-only">Open {type.toLowerCase()} on Instagram (opens in a new tab):</span>
+ <span className="flex flex-wrap justify-center gap-x-2 gap-y-0.5 text-caption text-ink-muted tabular-nums [&_svg]:size-3 [&_svg]:stroke-[1.75]">
+ <span className="flex items-center gap-0.5"><Views aria-hidden="true" />{fmtIGViews(post.viewCount)}<span className="sr-only"> views,</span></span>
+ <span className="flex items-center gap-0.5"><Likes aria-hidden="true" />{fmtNum(post.likeCount)}<span className="sr-only"> likes,</span></span>
+ <span className="flex items-center gap-0.5"><Comments aria-hidden="true" />{fmtNum(post.commentsCount)}<span className="sr-only"> comments</span></span>
+ </span>
+ </a>
+ </li>
);
}
@@ -47,11 +56,11 @@ export default function InstagramRecentGrid({ posts, fetchedPosts }: InstagramRe
return (
<SurfaceBox title="Recent posts" subheader={`${fetchedPosts || 0} loaded`}>
{posts.length > 0 ? (
- <div className="grid grid-cols-3 gap-2 sm:grid-cols-4 md:grid-cols-6 xl:grid-cols-8">
+ <ul className="grid grid-cols-3 gap-x-2 gap-y-3 sm:grid-cols-4 md:grid-cols-6 xl:grid-cols-8">
{posts.map(post => <RecentPost key={post.id} post={post} />)}
- </div>
+ </ul>
) : (
- <EmptyState compact icon={<Image />} title="No posts yet" description="This account has not published anything we can read." />
+ <EmptyState compact icon={<Image />} title="No posts yet" description="This account has not published anything Instagram lets Twiligent read." />
)}
</SurfaceBox>
);
diff --git a/frontend/src/features/analytics/instagram/InstagramTopPostsTable.tsx b/frontend/src/features/analytics/instagram/InstagramTopPostsTable.tsx
index 1b46135..9aefcd7 100644
--- a/frontend/src/features/analytics/instagram/InstagramTopPostsTable.tsx
+++ b/frontend/src/features/analytics/instagram/InstagramTopPostsTable.tsx
@@ -2,7 +2,8 @@ import { ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import SurfaceBox from '@/components/SurfaceBox';
-import { fmtDate, fmtNum } from '../../../utils/formatters';
+import Num from '@/components/Num';
+import { fmtDate } from '../../../utils/formatters';
import { fmtIGViews } from '../../../utils/instagramContent';
import TypeBadge from './TypeBadge';
import type { InstagramTopPost } from '@shared/types/instagram.ts';
@@ -13,18 +14,18 @@ export interface InstagramTopPostsTableProps {
export default function InstagramTopPostsTable({ posts }: InstagramTopPostsTableProps) {
return (
- <SurfaceBox title="Top performing posts" content={false} className="overflow-hidden">
+ <SurfaceBox title="Top performing posts" subheader="Ranked by interactions: likes plus comments" content={false} className="overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-10 text-right">#</TableHead>
- <TableHead>Caption</TableHead>
- <TableHead>Type</TableHead>
- <TableHead className="text-right">Views</TableHead>
+ <TableHead className="sticky left-0 z-10 bg-surface-raised">Caption</TableHead>
+ <TableHead className="hidden sm:table-cell">Type</TableHead>
+ <TableHead className="hidden text-right md:table-cell">Views</TableHead>
<TableHead className="text-right">Likes</TableHead>
- <TableHead className="text-right">Comments</TableHead>
- <TableHead className="text-right">Engagement</TableHead>
- <TableHead>Posted</TableHead>
+ <TableHead className="hidden text-right sm:table-cell">Comments</TableHead>
+ <TableHead className="text-right">Interactions</TableHead>
+ <TableHead className="hidden text-right md:table-cell">Posted</TableHead>
<TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
</TableRow>
</TableHeader>
@@ -32,17 +33,19 @@ export default function InstagramTopPostsTable({ posts }: InstagramTopPostsTable
{posts.slice(0, 10).map((post, i) => (
<TableRow key={post.id}>
<TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>
- <TableCell className="max-w-[220px]"><p className="truncate text-sm text-ink">{post.caption || 'No caption'}</p></TableCell>
- <TableCell><TypeBadge type={post.contentType} /></TableCell>
- <TableCell className="text-right text-ink-muted">{fmtIGViews(post.viewCount)}</TableCell>
- <TableCell className="text-right font-semibold text-ink">{fmtNum(post.likeCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(post.commentsCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(post.engagement)}</TableCell>
- <TableCell className="text-small text-ink-faint">{fmtDate(post.timestamp)}</TableCell>
+ <TableCell className="sticky left-0 z-10 max-w-56 bg-surface-raised whitespace-normal">
+ <p className="line-clamp-2 text-sm text-ink" title={post.caption || undefined}>{post.caption || 'No caption'}</p>
+ </TableCell>
+ <TableCell className="hidden sm:table-cell"><TypeBadge type={post.contentType} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell">{fmtIGViews(post.viewCount)}</TableCell>
+ <TableCell className="text-right font-semibold text-ink"><Num value={post.likeCount} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={post.commentsCount} /></TableCell>
+ <TableCell className="text-right text-ink-muted"><Num value={post.engagement} /></TableCell>
+ <TableCell className="hidden text-right text-small text-ink-faint md:table-cell">{fmtDate(post.timestamp)}</TableCell>
<TableCell>
{post.permalink && (
- <Button variant="ghost" size="icon-xs" render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label="Open post on Instagram" />}>
- <ExternalLink />
+ <Button variant="ghost" size="icon-xs" render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label={`Open post ${i + 1} on Instagram (opens in a new tab)`} />}>
+ <ExternalLink aria-hidden="true" />
</Button>
)}
</TableCell>
diff --git a/frontend/src/features/analytics/instagram/InstagramTypeSummaryTable.tsx b/frontend/src/features/analytics/instagram/InstagramTypeSummaryTable.tsx
index 163af81..dc8b8ae 100644
--- a/frontend/src/features/analytics/instagram/InstagramTypeSummaryTable.tsx
+++ b/frontend/src/features/analytics/instagram/InstagramTypeSummaryTable.tsx
@@ -1,6 +1,6 @@
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import SurfaceBox from '@/components/SurfaceBox';
-import { fmtNum } from '../../../utils/formatters';
+import Num from '@/components/Num';
import { reportedViews } from './instagramAnalyticsData.ts';
import type { InstagramTypeRow } from './instagramAnalyticsData.ts';
import TypeBadge from './TypeBadge';
@@ -17,11 +17,11 @@ export default function InstagramTypeSummaryTable({ rows }: InstagramTypeSummary
<TableRow>
<TableHead>Type</TableHead>
<TableHead className="text-right">Count</TableHead>
- <TableHead className="text-right">Total views</TableHead>
+ <TableHead className="hidden text-right sm:table-cell">Total views</TableHead>
<TableHead className="text-right">Average views</TableHead>
- <TableHead className="text-right">Average likes</TableHead>
- <TableHead className="text-right">Average comments</TableHead>
- <TableHead className="text-right">Average engagement</TableHead>
+ <TableHead className="hidden text-right md:table-cell">Average likes</TableHead>
+ <TableHead className="hidden text-right md:table-cell">Average comments</TableHead>
+ <TableHead className="text-right">Average interactions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -29,11 +29,11 @@ export default function InstagramTypeSummaryTable({ rows }: InstagramTypeSummary
<TableRow key={row.type}>
<TableCell><TypeBadge type={row.type} /></TableCell>
<TableCell className="text-right text-ink">{row.count}</TableCell>
- <TableCell className="text-right text-ink-muted">{reportedViews(row, 'totalViews')}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell">{reportedViews(row, 'totalViews')}</TableCell>
<TableCell className="text-right text-ink-muted">{reportedViews(row, 'avgViews')}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(row.avgLikes)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(row.avgComments)}</TableCell>
- <TableCell className="text-right font-semibold text-ink">{fmtNum(row.avgEngagement)}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell"><Num value={row.avgLikes} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell"><Num value={row.avgComments} /></TableCell>
+ <TableCell className="text-right font-semibold text-ink"><Num value={row.avgEngagement} /></TableCell>
</TableRow>
))}
</TableBody>
diff --git a/frontend/src/features/analytics/overview/AccountCell.tsx b/frontend/src/features/analytics/overview/AccountCell.tsx
index 53596fe..154a4ab 100644
--- a/frontend/src/features/analytics/overview/AccountCell.tsx
+++ b/frontend/src/features/analytics/overview/AccountCell.tsx
@@ -13,7 +13,7 @@ export default function AccountCell({ account, name }: AccountCellProps) {
return (
<TableCell>
<div className="flex items-center gap-2.5">
- <AccountAvatar account={account} />
+ <AccountAvatar account={account} decorative />
<div>
<p className="text-sm font-medium text-ink">{name}</p>
<p className="text-caption text-ink-faint">{accountHandle(account)}</p>
diff --git a/frontend/src/features/analytics/overview/AccountRankRow.tsx b/frontend/src/features/analytics/overview/AccountRankRow.tsx
index 992ab98..53e46d9 100644
--- a/frontend/src/features/analytics/overview/AccountRankRow.tsx
+++ b/frontend/src/features/analytics/overview/AccountRankRow.tsx
@@ -16,7 +16,7 @@ export default function AccountRankRow({ account, rank, trailing }: AccountRankR
return (
<ListRow
onClick={() => navigate(accountPath(account))}
- leading={<><RankNumber rank={rank} /><AccountAvatar account={account} showPlatform /></>}
+ leading={<><RankNumber rank={rank} /><AccountAvatar account={account} showPlatform decorative /></>}
title={accountName(account)}
meta={accountHandle(account)}
trailing={trailing}
diff --git a/frontend/src/features/analytics/overview/AccountsTab.tsx b/frontend/src/features/analytics/overview/AccountsTab.tsx
index f842ef0..2a231f8 100644
--- a/frontend/src/features/analytics/overview/AccountsTab.tsx
+++ b/frontend/src/features/analytics/overview/AccountsTab.tsx
@@ -3,7 +3,7 @@ import SurfaceBox from '@/components/SurfaceBox';
import { RankNumber } from '@/components/ListRow';
import { PlatformBadge } from '@/components/platform';
import { accountName, platformOf } from '@/lib/accounts';
-import { timeAgo } from '../../../utils/formatters';
+import RelativeTime from '@/components/RelativeTime';
import type { AppAccount } from '../../../utils/formatters';
import { accountAudienceLabel, accountContentLabel } from './overviewLabels.ts';
import AccountCell from './AccountCell';
@@ -15,16 +15,16 @@ export interface AccountsTabProps {
export default function AccountsTab({ accounts }: AccountsTabProps) {
return (
- <SurfaceBox content={false} className="overflow-hidden">
+ <SurfaceBox title="All accounts" subheader="Ranked by audience" content={false} className="overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-10 text-right">#</TableHead>
<TableHead>Account</TableHead>
- <TableHead>Platform</TableHead>
+ <TableHead className="hidden sm:table-cell">Platform</TableHead>
<TableHead className="text-right">Audience</TableHead>
- <TableHead className="text-right">Content</TableHead>
- <TableHead className="text-right">Updated</TableHead>
+ <TableHead className="hidden text-right md:table-cell">Content</TableHead>
+ <TableHead className="hidden text-right md:table-cell">Updated</TableHead>
<TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
</TableRow>
</TableHeader>
@@ -33,10 +33,10 @@ export default function AccountsTab({ accounts }: AccountsTabProps) {
<TableRow key={account.id}>
<TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>
<AccountCell account={account} name={accountName(account)} />
- <TableCell><PlatformBadge platform={platformOf(account)} /></TableCell>
+ <TableCell className="hidden sm:table-cell"><PlatformBadge platform={platformOf(account)} /></TableCell>
<TableCell className="text-right text-ink">{accountAudienceLabel(account)}</TableCell>
- <TableCell className="text-right text-ink-muted">{accountContentLabel(account)}</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{timeAgo(account.lastUpdated)}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell">{accountContentLabel(account)}</TableCell>
+ <TableCell className="hidden text-right text-small text-ink-faint md:table-cell"><RelativeTime date={account.lastUpdated} /></TableCell>
<TableCell><OpenAnalytics account={account} name={accountName(account)} /></TableCell>
</TableRow>
))}
diff --git a/frontend/src/features/analytics/overview/AudienceChart.tsx b/frontend/src/features/analytics/overview/AudienceChart.tsx
index 091a7d8..13d1776 100644
--- a/frontend/src/features/analytics/overview/AudienceChart.tsx
+++ b/frontend/src/features/analytics/overview/AudienceChart.tsx
@@ -1,10 +1,5 @@
-import {
- AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip, ResponsiveContainer,
-} from 'recharts';
-import type { DotItemDotProps, TooltipPayloadEntry, TooltipValueType } from 'recharts';
-import { axisProps, gridProps, tooltipStyle } from '@/lib/chart';
-import { fmtNum, fmtNumFull } from '../../../utils/formatters';
-import { audienceDotColor } from './overviewCharts.ts';
+import RankingBarChart from '@/components/RankingBarChart';
+import { audienceRankingOf } from './overviewCharts.ts';
import type { AudienceLegendItem, AudiencePoint } from './overviewCharts.ts';
export interface AudienceChartProps {
@@ -12,58 +7,19 @@ export interface AudienceChartProps {
legend: AudienceLegendItem[];
}
-function formatAudienceTooltip(value: TooltipValueType | undefined, name: string | number | undefined, props: TooltipPayloadEntry): [string, string] {
- return [fmtNumFull(value as number), props.payload.type === 'category' ? 'Karma' : 'Audience'];
-}
-
-function renderAudienceDot({ cx, cy, payload, index }: DotItemDotProps) {
- return (
- <circle
- key={`dot-${index}`}
- cx={cx}
- cy={cy}
- r={4.5}
- fill={audienceDotColor(payload.type)}
- stroke="var(--surface-raised)"
- strokeWidth={2}
- />
- );
-}
-
+// a ranking of separate accounts, so bars rather than a line; the legend names each colour in words
export default function AudienceChart({ data, legend }: AudienceChartProps) {
return (
- <>
- <ResponsiveContainer width="100%" height={260} debounce={200}>
- <AreaChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
- <defs>
- <linearGradient id="audienceAreaGrad" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor="var(--chart-1)" stopOpacity={0.22} />
- <stop offset="95%" stopColor="var(--chart-1)" stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="name" {...axisProps} />
- <YAxis {...axisProps} tickFormatter={fmtNum} width={48} />
- <ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={formatAudienceTooltip} />
- <Area
- type="monotone"
- dataKey="value"
- stroke="var(--chart-1)"
- strokeWidth={2}
- fill="url(#audienceAreaGrad)"
- dot={renderAudienceDot}
- activeDot={{ r: 6 }}
- />
- </AreaChart>
- </ResponsiveContainer>
- <ul className="mt-3 flex flex-wrap gap-x-4 gap-y-1.5">
+ <div className="flex flex-col gap-3">
+ <RankingBarChart rows={audienceRankingOf(data)} label="Audience" title="Audience by account" kindLabel="Counts" />
+ <ul aria-label="Colour key" className="flex flex-wrap gap-x-4 gap-y-1.5 px-2">
{legend.map(({ color, label }) => (
<li key={label} className="flex items-center gap-1.5 text-caption text-ink-muted">
- <span className="size-2.5 shrink-0 rounded-full" style={{ background: color }} />
+ <span aria-hidden="true" className="size-2.5 shrink-0 rounded-full" style={{ background: color }} />
{label}
</li>
))}
</ul>
- </>
+ </div>
);
}
diff --git a/frontend/src/features/analytics/overview/CategoryRow.tsx b/frontend/src/features/analytics/overview/CategoryRow.tsx
index acf8ef7..e2e54d8 100644
--- a/frontend/src/features/analytics/overview/CategoryRow.tsx
+++ b/frontend/src/features/analytics/overview/CategoryRow.tsx
@@ -15,7 +15,7 @@ export default function CategoryRow({ stat, trailing }: CategoryRowProps) {
return (
<ListRow
onClick={() => navigate(`/tracked-content/category/${encodeURIComponent(stat.category)}`)}
- leading={<><span className="w-5 shrink-0" /><span className="flex size-8 items-center justify-center rounded-control bg-surface-sunken text-ink-muted"><Tag className="size-4 stroke-[1.75]" /></span></>}
+ leading={<><span className="w-5 shrink-0" /><span className="flex size-8 items-center justify-center rounded-control bg-surface-sunken text-ink-muted"><Tag className="size-4 stroke-[1.75]" aria-hidden="true" /></span></>}
title={stat.category}
meta={categoryMeta(stat)}
trailing={trailing}
diff --git a/frontend/src/features/analytics/overview/CommentsTab.tsx b/frontend/src/features/analytics/overview/CommentsTab.tsx
index 56ffcbc..6864800 100644
--- a/frontend/src/features/analytics/overview/CommentsTab.tsx
+++ b/frontend/src/features/analytics/overview/CommentsTab.tsx
@@ -1,15 +1,18 @@
import { Link } from 'react-router-dom';
-import { BarChart2, CirclePlay, MessageSquare, MessagesSquare } from 'lucide-react';
import { Button } from '@/components/ui/button';
import SurfaceBox from '@/components/SurfaceBox';
import MetricBox from '@/components/MetricBox';
-import MetricAreaChart from '@/components/MetricAreaChart';
+import Num from '@/components/Num';
+import RankingBarChart from '@/components/RankingBarChart';
import { EmptyState } from '@/components/StateViews';
-import { SERIES } from '@/lib/chart';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { fmtNum, fmtPercent } from '../../../utils/formatters';
+import { CATEGORY_SERIES } from './overviewCharts.ts';
import { pluralWord } from './overviewLabels.ts';
import type { OverviewStats } from './useOverviewStats';
+const { comments: Comments, videos: Videos, redditPosts: Reddit, median: PerItem } = METRIC_ICONS;
+
export interface CommentsTabProps {
stats: OverviewStats;
}
@@ -17,31 +20,33 @@ export interface CommentsTabProps {
export default function CommentsTab({ stats }: CommentsTabProps) {
const { summary, charts } = stats;
const { totalComments, totalContent } = summary;
+ const byContent = charts.commentByContent.map(point => ({ name: point.name, value: point.comments }));
+ const byCategory = charts.commentByCategory.map(point => ({ name: point.name, value: point.comments }));
return (
<>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
- <MetricBox icon={<MessageSquare />} label="Total comments" value={fmtNum(totalComments)} subtitle={totalComments > 0 ? 'Across all platforms' : 'Open an analytics page to load'} highlight />
- <MetricBox icon={<CirclePlay />} label="YouTube comments" value={fmtNum(summary.ytComments)} subtitle={`${fmtPercent(summary.commentShare.youtube)} of all comments`} />
- <MetricBox icon={<MessagesSquare />} label="Reddit comments" value={fmtNum(summary.rdComments)} subtitle={`${fmtPercent(summary.commentShare.reddit)} of all comments`} />
- <MetricBox icon={<BarChart2 />} label="Comments per item" value={fmtNum(summary.avgCommentsPerContent)} subtitle={`Average across ${fmtNum(totalContent)} ${pluralWord(totalContent, 'item')}`} />
+ <MetricBox icon={<Comments />} label="Total comments" value={<Num value={totalComments} />} period="Loaded content" subtitle={totalComments > 0 ? 'Across all platforms' : 'Open an analytics page to load'} highlight />
+ <MetricBox icon={<Videos />} label="YouTube comments" value={<Num value={summary.ytComments} />} period="Loaded videos" subtitle={`${fmtPercent(summary.commentShare.youtube)} of all comments`} />
+ <MetricBox icon={<Reddit />} label="Reddit comments" value={<Num value={summary.rdComments} />} period="Loaded posts" subtitle={`${fmtPercent(summary.commentShare.reddit)} of all comments`} />
+ <MetricBox icon={<PerItem />} label="Comments per item" value={<Num value={summary.avgCommentsPerContent} />} subtitle={`Average across ${fmtNum(totalContent)} ${pluralWord(totalContent, 'item')}`} />
</div>
{totalComments === 0 ? (
<SurfaceBox>
<EmptyState
- icon={<MessageSquare />}
+ icon={<Comments />}
title="No comment data yet"
description="Open a channel or account analytics page to load its comments, or track individual posts and videos."
- action={<Button size="sm" render={<Link to="/tracked-content" />}>Track content</Button>}
+ action={<Button size="sm" variant="outline" render={<Link to="/tracked-content" />}>Track content</Button>}
/>
</SurfaceBox>
) : (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<SurfaceBox title="Comments by tracked content" subheader="Top 12 tracked items ranked by comments">
- <MetricAreaChart data={charts.commentByContent} dataKey="comments" label="Comments" color={SERIES.cool} emptyMessage="Track content to compare comment volume" />
+ <RankingBarChart rows={byContent} label="Comments" title="Comments by tracked content" emptyMessage="Track content to compare comment volume" />
</SurfaceBox>
<SurfaceBox title="Comments by category" subheader="Total comments across every item in each category">
- <MetricAreaChart data={charts.commentByCategory} dataKey="comments" label="Comments" color={SERIES.warm} emptyMessage="Assign categories to tracked content to see this breakdown" />
+ <RankingBarChart rows={byCategory} label="Comments" title="Comments by category" color={CATEGORY_SERIES} emptyMessage="Assign categories to tracked content to see this breakdown" />
</SurfaceBox>
</div>
)}
diff --git a/frontend/src/features/analytics/overview/ContentTab.tsx b/frontend/src/features/analytics/overview/ContentTab.tsx
index 0ac2518..8b33d5f 100644
--- a/frontend/src/features/analytics/overview/ContentTab.tsx
+++ b/frontend/src/features/analytics/overview/ContentTab.tsx
@@ -1,8 +1,9 @@
import { Link } from 'react-router-dom';
-import { BookmarkCheck, CirclePlay, MessagesSquare, Tag, VideoIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import SurfaceBox from '@/components/SurfaceBox';
import MetricBox from '@/components/MetricBox';
+import Num from '@/components/Num';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { EmptyState } from '@/components/StateViews';
import { fmtNum } from '../../../utils/formatters';
import { IG_CONTENT_TYPES } from '../../../utils/instagramContent';
@@ -12,6 +13,8 @@ import CategoryRow from './CategoryRow';
import type { OverviewStats } from './useOverviewStats';
import type { CategoryStat } from './overviewTrackedStats.ts';
+const { videos: Videos, instagram: Instagram, redditPosts: Reddit, tracked: Tracked, category: Category } = METRIC_ICONS;
+
function instagramContentSubtitle(stats: OverviewStats): string {
const { igTypes } = stats.cacheTotals;
if (IG_CONTENT_TYPES.some(type => igTypes[type].count > 0)) return igTypeSummary(igTypes, 'count');
@@ -36,10 +39,10 @@ export default function ContentTab({ stats }: ContentTabProps) {
return (
<>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <MetricBox icon={<CirclePlay />} label="YouTube videos" value={fmtNum(totals.videos)} subtitle={countLabel(groups.youtube.length, 'channel')} />
- <MetricBox icon={<VideoIcon />} label="Instagram content" value={fmtNum(totals.posts)} subtitle={instagramContentSubtitle(stats)} />
- <MetricBox icon={<MessagesSquare />} label="Reddit posts" value={fmtNum(cacheTotals.rdPosts)} subtitle={cacheTotals.rdPosts > 0 ? 'From the analytics cache' : 'Open Reddit analytics to load'} />
- <MetricBox icon={<BookmarkCheck />} label="Tracked content" value={fmtNum(trackedStats.total)} subtitle={`${trackedStats.ytItems.length} YouTube, ${trackedStats.rdItems.length} Reddit`} />
+ <MetricBox icon={<Videos />} label="YouTube videos" value={<Num value={totals.videos} />} period="All time" subtitle={countLabel(groups.youtube.length, 'channel')} />
+ <MetricBox icon={<Instagram />} label="Instagram content" value={<Num value={totals.posts} />} period="All time" subtitle={instagramContentSubtitle(stats)} />
+ <MetricBox icon={<Reddit />} label="Reddit posts" value={<Num value={cacheTotals.rdPosts} />} period="Loaded posts" subtitle={cacheTotals.rdPosts > 0 ? 'From the analytics cache' : 'Open Reddit analytics to load'} />
+ <MetricBox icon={<Tracked />} label="Tracked content" value={<Num value={trackedStats.total} />} period="Now" subtitle={`${trackedStats.ytItems.length} YouTube, ${trackedStats.rdItems.length} Reddit`} />
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
@@ -60,7 +63,7 @@ export default function ContentTab({ stats }: ContentTabProps) {
{categoryStats.length === 0 ? (
<EmptyState
compact
- icon={<Tag />}
+ icon={<Category />}
title="No categories yet"
description="Assign categories to tracked content to see this breakdown."
action={<Button size="sm" variant="outline" render={<Link to="/tracked-content" />}>Open tracked content</Button>}
diff --git a/frontend/src/features/analytics/overview/GettingStarted.tsx b/frontend/src/features/analytics/overview/GettingStarted.tsx
index e208244..f2a4231 100644
--- a/frontend/src/features/analytics/overview/GettingStarted.tsx
+++ b/frontend/src/features/analytics/overview/GettingStarted.tsx
@@ -4,13 +4,13 @@ import { Button } from '@/components/ui/button';
export default function GettingStarted() {
return (
- <section className="relative overflow-hidden rounded-panel border border-line bg-surface-raised">
+ <section aria-labelledby="getting-started-title" className="relative overflow-hidden rounded-panel border border-line bg-surface-raised">
<div aria-hidden="true" className="fold-band absolute inset-y-0 right-0 hidden w-2/5 [clip-path:polygon(35%_0,100%_0,100%_100%,0_100%)] md:block" />
<div className="relative flex max-w-xl flex-col gap-4 p-8">
<p className="eyebrow text-brand-text">Getting started</p>
- <h2 className="font-heading text-page-title font-semibold text-ink">Bring your channels into one picture.</h2>
- <p className="text-sm text-ink-muted">Add a YouTube channel, connect an Instagram Business or Creator account, or add a Reddit profile. Analytics start filling in as soon as an account is added.</p>
- <div><Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add an account</Button></div>
+ <h2 id="getting-started-title" className="font-heading text-page-title font-semibold text-ink">Bring your channels into one picture.</h2>
+ <p className="max-w-prose text-ink-muted">Add a YouTube channel, connect an Instagram Business or Creator account, or add a Reddit profile. Analytics start filling in as soon as an account is added.</p>
+ <div><Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" aria-hidden="true" />Add account</Button></div>
</div>
</section>
);
diff --git a/frontend/src/features/analytics/overview/InstagramViewsTable.tsx b/frontend/src/features/analytics/overview/InstagramViewsTable.tsx
index 1e6c080..d691cdd 100644
--- a/frontend/src/features/analytics/overview/InstagramViewsTable.tsx
+++ b/frontend/src/features/analytics/overview/InstagramViewsTable.tsx
@@ -21,7 +21,8 @@ export interface InstagramViewsTableProps {
function InstagramViewsRow({ account, cache, isSyncing }: InstagramViewsRowProps) {
const warmed = cache?.cacheWarmed;
- const pendingLabel = isSyncing ? 'Syncing' : '-';
+ // a cold account says why its figures are missing; opening it loads them
+ const pendingLabel = isSyncing ? 'Loading' : 'Not loaded yet';
return (
<TableRow>
<AccountCell account={account} name={accountName(account)} />
@@ -32,11 +33,11 @@ function InstagramViewsRow({ account, cache, isSyncing }: InstagramViewsRowProps
<p className="text-sm font-medium text-ink">{fmtNum(cache.contentTypes?.[type]?.views)}</p>
<p className="text-caption text-ink-faint">{fmtNum(cache.contentTypes?.[type]?.count)} {IG_CONTENT_TYPE_META[type].plural.toLowerCase()}</p>
</>
- ) : <span className="text-ink-faint">-</span>}
+ ) : <span className="text-ink-faint"><span aria-hidden="true">-</span><span className="sr-only">Not loaded</span></span>}
</TableCell>
))}
<TableCell className="text-right font-semibold text-ink">
- {warmed ? fmtNum(cache.totalViews) : <span className="font-normal text-ink-faint">{pendingLabel}</span>}
+ {warmed ? fmtNum(cache.totalViews) : <span className="text-small font-normal text-ink-faint">{pendingLabel}</span>}
</TableCell>
<TableCell>
<OpenAnalytics account={account} name={accountName(account)} />
@@ -47,7 +48,7 @@ function InstagramViewsRow({ account, cache, isSyncing }: InstagramViewsRowProps
export default function InstagramViewsTable({ rows, isSyncing }: InstagramViewsTableProps) {
return (
- <SurfaceBox title="Instagram views by content type" content={false} className="overflow-hidden">
+ <SurfaceBox title="Instagram views by content type" subheader="Views on loaded posts. Open an account marked Not loaded yet to load it." content={false} className="overflow-hidden">
<Table>
<TableHeader>
<TableRow>
diff --git a/frontend/src/features/analytics/overview/LikesTab.tsx b/frontend/src/features/analytics/overview/LikesTab.tsx
index 11b76dd..3ac0166 100644
--- a/frontend/src/features/analytics/overview/LikesTab.tsx
+++ b/frontend/src/features/analytics/overview/LikesTab.tsx
@@ -1,15 +1,17 @@
import { Link } from 'react-router-dom';
-import { Camera, CirclePlay, MessagesSquare, ThumbsUp } from 'lucide-react';
import { Button } from '@/components/ui/button';
import SurfaceBox from '@/components/SurfaceBox';
import MetricBox from '@/components/MetricBox';
-import MetricAreaChart from '@/components/MetricAreaChart';
+import Num from '@/components/Num';
+import RankingBarChart from '@/components/RankingBarChart';
import { EmptyState } from '@/components/StateViews';
import { PLATFORM_META } from '@/lib/accounts';
-import { SERIES } from '@/lib/chart';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { fmtNum, fmtPercent } from '../../../utils/formatters';
import type { OverviewStats } from './useOverviewStats';
+const { likes: Likes, karma: Karma, videos: Videos, instagram: Instagram } = METRIC_ICONS;
+
function instagramLikesSubtitle(stats: OverviewStats): string {
if (stats.groups.instagram.length > 0) return `${fmtPercent(stats.summary.likeShare.instagram)} of all likes`;
return 'No Instagram accounts';
@@ -22,31 +24,33 @@ export interface LikesTabProps {
export default function LikesTab({ stats }: LikesTabProps) {
const { totals, cacheTotals, trackedStats, summary, charts } = stats;
const { totalLikes } = summary;
+ const karmaRows = charts.karmaByAccount.map(point => ({ name: point.name, value: point.karma }));
+ const engagementRows = charts.engagementByContent.map(point => ({ name: point.name, value: point.engagement }));
return (
<>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
- <MetricBox icon={<ThumbsUp />} label="Total likes" value={fmtNum(totalLikes)} subtitle={totalLikes > 0 ? 'YouTube likes, Instagram likes, Reddit karma' : 'Open an analytics page to load'} highlight />
- <MetricBox icon={<MessagesSquare />} label="Reddit karma" value={fmtNum(summary.redditKarma)} subtitle={`${fmtNum(totals.postKarma)} account, ${fmtNum(trackedStats.rdKarma)} tracked`} />
- <MetricBox icon={<CirclePlay />} label="YouTube likes" value={fmtNum(summary.ytLikes)} subtitle={`${fmtPercent(summary.likeShare.youtube)} of all likes`} />
- <MetricBox icon={<Camera />} label="Instagram likes" value={fmtNum(cacheTotals.igLikes)} subtitle={instagramLikesSubtitle(stats)} />
+ <MetricBox icon={<Likes />} label="Total likes" value={<Num value={totalLikes} />} period="Loaded content" subtitle={totalLikes > 0 ? 'YouTube likes, Instagram likes, Reddit karma' : 'Open an analytics page to load'} highlight />
+ <MetricBox icon={<Karma />} label="Reddit karma" value={<Num value={summary.redditKarma} />} period="All time" subtitle={`${fmtNum(totals.postKarma)} account, ${fmtNum(trackedStats.rdKarma)} tracked`} />
+ <MetricBox icon={<Videos />} label="YouTube likes" value={<Num value={summary.ytLikes} />} period="Loaded videos" subtitle={`${fmtPercent(summary.likeShare.youtube)} of all likes`} />
+ <MetricBox icon={<Instagram />} label="Instagram likes" value={<Num value={cacheTotals.igLikes} />} period="Loaded posts" subtitle={instagramLikesSubtitle(stats)} />
</div>
{totalLikes === 0 ? (
<SurfaceBox>
<EmptyState
- icon={<ThumbsUp />}
+ icon={<Likes />}
title="No engagement data yet"
description="Open a channel or account analytics page to load its likes, or track individual posts and videos."
- action={<Button size="sm" render={<Link to="/tracked-content" />}>Track content</Button>}
+ action={<Button size="sm" variant="outline" render={<Link to="/tracked-content" />}>Track content</Button>}
/>
</SurfaceBox>
) : (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<SurfaceBox title="Karma by Reddit account" subheader="Post karma earned by each connected account">
- <MetricAreaChart data={charts.karmaByAccount} dataKey="karma" label="Post karma" color={PLATFORM_META.reddit.series} emptyMessage="Connect a Reddit account to see karma" />
+ <RankingBarChart rows={karmaRows} label="Post karma" title="Karma by Reddit account" color={PLATFORM_META.reddit.series} emptyMessage="Connect a Reddit account to see karma" />
</SurfaceBox>
- <SurfaceBox title="Engagement by tracked content" subheader="YouTube likes and Reddit karma for the top 12 tracked items">
- <MetricAreaChart data={charts.engagementByContent} dataKey="engagement" label="Likes or karma" color={SERIES.primary} emptyMessage="Track content to compare engagement" />
+ <SurfaceBox title="Likes and karma by tracked content" subheader="YouTube likes and Reddit karma for the top 12 tracked items">
+ <RankingBarChart rows={engagementRows} label="Likes or karma" title="Likes and karma by tracked content" emptyMessage="Track content to compare engagement" />
</SurfaceBox>
</div>
)}
diff --git a/frontend/src/features/analytics/overview/MetricTabsList.tsx b/frontend/src/features/analytics/overview/MetricTabsList.tsx
index 90a4930..54e3ee1 100644
--- a/frontend/src/features/analytics/overview/MetricTabsList.tsx
+++ b/frontend/src/features/analytics/overview/MetricTabsList.tsx
@@ -19,8 +19,8 @@ export default function MetricTabsList({ tabs }: MetricTabsListProps) {
className="h-auto min-w-0 flex-col items-start justify-start gap-1 rounded-card border border-line bg-surface-raised p-4 text-left after:hidden hover:border-line-strong/40 data-active:border-brand data-active:bg-brand-soft/40"
>
<span className="text-small font-medium text-ink-muted">{tab.label}</span>
- <span className="font-heading text-2xl font-semibold tracking-[-0.02em] text-ink tabular-nums">{tab.figure}</span>
- <span className="w-full truncate text-caption font-normal text-ink-faint">{tab.detail}</span>
+ <span className="font-heading text-page-title font-semibold text-ink tabular-nums">{tab.figure}</span>
+ <span className="w-full truncate text-caption font-normal text-ink-faint" title={typeof tab.detail === 'string' ? tab.detail : undefined}>{tab.detail}</span>
</TabsTrigger>
))}
</TabsList>
diff --git a/frontend/src/features/analytics/overview/Overview.tsx b/frontend/src/features/analytics/overview/Overview.tsx
index ab8636d..14f9026 100644
--- a/frontend/src/features/analytics/overview/Overview.tsx
+++ b/frontend/src/features/analytics/overview/Overview.tsx
@@ -1,9 +1,13 @@
-import { useState } from 'react';
import { Progress } from '@/components/ui/progress';
+import { Alert, AlertAction, AlertDescription } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
import { Tabs, TabsContent } from '@/components/ui/tabs';
+import { useUrlChoice } from '@/hooks/use-url-state';
import { useAppContext } from '../../../context/AppContext';
import { useAuth } from '../../../context/AuthContext';
import { metricTabsOf } from './overviewLabels.ts';
+import { oldestFetchedAt } from './overviewStats.ts';
+import type { AccountCache } from './overviewStats.ts';
import { useOverviewData } from './useOverviewData';
import { useOverviewStats } from './useOverviewStats';
import OverviewHeader from './OverviewHeader';
@@ -17,26 +21,46 @@ import AccountsTab from './AccountsTab';
import CommentsTab from './CommentsTab';
import LikesTab from './LikesTab';
+const OVERVIEW_TABS = ['audience', 'views', 'content', 'accounts', 'comments', 'likes'] as const;
+
+type OverviewTab = typeof OVERVIEW_TABS[number];
+
export default function Overview() {
- const { accounts, loading: accountsLoading, refreshAll } = useAppContext();
+ const { accounts, loading: refreshingAll, refreshAll } = useAppContext();
const { user } = useAuth();
- const [activeTab, setActiveTab] = useState('audience');
- const { overviewData, overviewLoading, isSyncing } = useOverviewData(accounts);
+ const [activeTab, setActiveTab] = useUrlChoice<OverviewTab>('tab', OVERVIEW_TABS, 'audience');
+ const { overviewData, overviewLoading, loaded, error, retry, isSyncing } = useOverviewData(accounts);
const stats = useOverviewStats(accounts, overviewData);
- const loading = accountsLoading || overviewLoading;
+ const fetchedAt = oldestFetchedAt(overviewData.analyticsCache as AccountCache);
return (
<div className="flex flex-col gap-8">
- <OverviewHeader accounts={accounts} email={user?.email} isSyncing={isSyncing} loading={loading} onRefresh={refreshAll} />
+ <OverviewHeader
+ accounts={accounts}
+ email={user?.email}
+ isSyncing={isSyncing}
+ refreshing={refreshingAll}
+ onRefresh={refreshAll}
+ fetchedAt={fetchedAt}
+ />
<QuickActions />
- {loading && <Progress value={null} aria-label="Loading accounts" />}
+ {overviewLoading && <Progress value={null} aria-label="Loading the overview" />}
+
+ {error && (
+ <Alert variant="destructive" role="alert">
+ <AlertDescription>
+ {error} {loaded ? 'The figures below are from the last successful load.' : 'Figures from cached analytics are missing below until it loads.'}
+ </AlertDescription>
+ <AlertAction><Button size="xs" variant="outline" onClick={retry}>Try again</Button></AlertAction>
+ </Alert>
+ )}
{accounts.length === 0 ? (
<GettingStarted />
) : (
- <Tabs value={activeTab} onValueChange={setActiveTab} className="gap-6">
+ <Tabs value={activeTab} onValueChange={value => setActiveTab(value as OverviewTab)} className="gap-6">
<MetricTabsList tabs={metricTabsOf(accounts, stats, isSyncing)} />
<TabsContent value="audience" className="flex flex-col gap-4">
<AudienceTab stats={stats} />
diff --git a/frontend/src/features/analytics/overview/OverviewHeader.tsx b/frontend/src/features/analytics/overview/OverviewHeader.tsx
index d95cbdc..3a2afb2 100644
--- a/frontend/src/features/analytics/overview/OverviewHeader.tsx
+++ b/frontend/src/features/analytics/overview/OverviewHeader.tsx
@@ -1,7 +1,7 @@
-import { RefreshCw } from 'lucide-react';
-import { Button } from '@/components/ui/button';
import PageHeader from '@/components/PageHeader';
-import { cn } from '@/lib/utils';
+import RefreshButton from '@/components/RefreshButton';
+import DataFreshness from '@/components/DataFreshness';
+import LiveStatus from '@/components/LiveStatus';
import { greetingTitle } from './greeting.ts';
import { overviewDescription } from './overviewLabels.ts';
import type { OverviewAccountFields } from './overviewStats.ts';
@@ -10,29 +10,25 @@ export interface OverviewHeaderProps {
accounts: OverviewAccountFields[];
email: string | null | undefined;
isSyncing: boolean;
- loading: boolean;
+ refreshing: boolean;
onRefresh: () => void;
+ fetchedAt: string | null;
}
-export default function OverviewHeader({ accounts, email, isSyncing, loading, onRefresh }: OverviewHeaderProps) {
+export default function OverviewHeader({ accounts, email, isSyncing, refreshing, onRefresh, fetchedAt }: OverviewHeaderProps) {
return (
<PageHeader
size="display"
title={greetingTitle(email)}
- description={overviewDescription(accounts)}
+ description={
+ <span className="flex flex-col gap-1">
+ <span>{overviewDescription(accounts)}</span>
+ {fetchedAt && <DataFreshness fetchedAt={fetchedAt} qualifier="oldest account" />}
+ <LiveStatus message={isSyncing ? 'Loading analytics for new accounts' : ''} visible={isSyncing} className="text-small text-ink-muted" />
+ </span>
+ }
actions={
- <>
- {isSyncing && (
- <span className="flex items-center gap-1.5 text-small text-ink-muted" role="status">
- <RefreshCw className="size-3.5 animate-spin" />
- Syncing analytics
- </span>
- )}
- <Button onClick={onRefresh} disabled={loading || accounts.length === 0} variant="outline">
- <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />
- {loading ? 'Refreshing' : 'Refresh all'}
- </Button>
- </>
+ <RefreshButton refreshing={refreshing} onRefresh={onRefresh} disabled={accounts.length === 0} target="all accounts" />
}
/>
);
diff --git a/frontend/src/features/analytics/overview/QuickActions.tsx b/frontend/src/features/analytics/overview/QuickActions.tsx
index 982bca0..65366fd 100644
--- a/frontend/src/features/analytics/overview/QuickActions.tsx
+++ b/frontend/src/features/analytics/overview/QuickActions.tsx
@@ -1,34 +1,34 @@
import { Link } from 'react-router-dom';
-import { Bookmark, Clapperboard, MessagesSquare, PlaySquare, Plus, Scissors, Send } from 'lucide-react';
+import { Bookmark, Plus, Send } from 'lucide-react';
+// only actions start here; the library pages are already one click away in the sidebar
const QUICK_ACTIONS = [
- { to: '/upload', label: 'Publish', icon: Send },
- { to: '/accounts?add=1', label: 'Add account', icon: Plus },
- { to: '/tracked-content', label: 'Track content', icon: Bookmark },
- { to: '/videos', label: 'Videos', icon: PlaySquare },
- { to: '/shorts', label: 'Shorts', icon: Scissors },
- { to: '/reels', label: 'Instagram', icon: Clapperboard },
- { to: '/reddit-posts', label: 'Reddit', icon: MessagesSquare },
+ { to: '/publish', label: 'Publish', icon: Send },
+ { to: '/accounts?add=1', label: 'Add account', icon: Plus },
+ { to: '/tracked-content', label: 'Track content', icon: Bookmark },
];
export default function QuickActions() {
return (
- <nav aria-label="Quick actions" className="grid grid-cols-4 gap-x-3 gap-y-5 sm:grid-cols-7">
- {QUICK_ACTIONS.map(action => {
- const Icon = action.icon;
- return (
- <Link
- key={action.to}
- to={action.to}
- className="group flex flex-col items-center gap-2 rounded-card py-2 text-center focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
- >
- <span className="flex size-12 items-center justify-center rounded-card bg-surface-wash text-ink-muted transition-colors duration-(--duration-base) group-hover:bg-surface-selected group-hover:text-ink">
- <Icon className="size-5 stroke-[1.75]" />
- </span>
- <span className="text-small font-medium text-ink">{action.label}</span>
- </Link>
- );
- })}
+ <nav aria-label="Quick actions">
+ <ul className="flex flex-wrap gap-3">
+ {QUICK_ACTIONS.map(action => {
+ const Icon = action.icon;
+ return (
+ <li key={action.to}>
+ <Link
+ to={action.to}
+ className="group flex items-center gap-3 rounded-card border border-line bg-surface-raised py-2.5 pr-4 pl-2.5 transition-colors duration-(--duration-base) hover:bg-surface-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
+ >
+ <span className="flex size-9 items-center justify-center rounded-control bg-surface-wash text-ink-muted transition-colors duration-(--duration-base) group-hover:text-ink">
+ <Icon className="size-5 stroke-[1.75]" aria-hidden="true" />
+ </span>
+ <span className="text-sm font-medium text-ink">{action.label}</span>
+ </Link>
+ </li>
+ );
+ })}
+ </ul>
</nav>
);
}
diff --git a/frontend/src/features/analytics/overview/ViewsTab.tsx b/frontend/src/features/analytics/overview/ViewsTab.tsx
index f42bdf5..6641eeb 100644
--- a/frontend/src/features/analytics/overview/ViewsTab.tsx
+++ b/frontend/src/features/analytics/overview/ViewsTab.tsx
@@ -1,14 +1,17 @@
-import { BookmarkCheck, Camera, CirclePlay, Eye } from 'lucide-react';
import SurfaceBox from '@/components/SurfaceBox';
import MetricBox from '@/components/MetricBox';
-import MetricAreaChart from '@/components/MetricAreaChart';
-import { SERIES } from '@/lib/chart';
+import Num from '@/components/Num';
+import RankingBarChart from '@/components/RankingBarChart';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { fmtNum } from '../../../utils/formatters';
+import { CATEGORY_SERIES } from './overviewCharts.ts';
import { countLabel, igTypeSummary } from './overviewLabels.ts';
import InstagramViewsTable from './InstagramViewsTable';
import YouTubeViewsTable from './YouTubeViewsTable';
import type { OverviewStats } from './useOverviewStats';
+const { views: Views, videos: Videos, instagram: Instagram, tracked: Tracked } = METRIC_ICONS;
+
export interface ViewsTabProps {
stats: OverviewStats;
isSyncing: boolean;
@@ -21,20 +24,21 @@ function instagramViewsSubtitle(stats: OverviewStats): string {
export default function ViewsTab({ stats, isSyncing }: ViewsTabProps) {
const { groups, totals, cacheTotals, trackedStats, summary } = stats;
+ const categoryRows = stats.charts.categoryViews.map(point => ({ name: point.name, value: point.views }));
return (
<>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
- <MetricBox icon={<Eye />} label="Total views" value={fmtNum(summary.totalViews)} subtitle="YouTube, Instagram and tracked content" highlight />
- <MetricBox icon={<CirclePlay />} label="Channel views" value={fmtNum(totals.views)} subtitle={countLabel(groups.youtube.length, 'YouTube channel')} />
- <MetricBox icon={<Camera />} label="Instagram views" value={fmtNum(cacheTotals.igViews)} subtitle={instagramViewsSubtitle(stats)} />
- <MetricBox icon={<BookmarkCheck />} label="Tracked views" value={fmtNum(summary.trackedViewTotal)} subtitle={`${fmtNum(trackedStats.ytViews)} YouTube, ${fmtNum(trackedStats.rdViews)} Reddit`} />
+ <MetricBox icon={<Views />} label="Total views" value={<Num value={summary.totalViews} />} period="All sources" subtitle="YouTube, Instagram and tracked content" highlight />
+ <MetricBox icon={<Videos />} label="Channel views" value={<Num value={totals.views} />} period="All time" subtitle={countLabel(groups.youtube.length, 'YouTube channel')} />
+ <MetricBox icon={<Instagram />} label="Instagram views" value={<Num value={cacheTotals.igViews} />} period="Loaded posts" subtitle={instagramViewsSubtitle(stats)} />
+ <MetricBox icon={<Tracked />} label="Tracked views" value={<Num value={summary.trackedViewTotal} />} period="Tracked items" subtitle={`${fmtNum(trackedStats.ytViews)} YouTube, ${fmtNum(trackedStats.rdViews)} Reddit`} />
</div>
{groups.instagram.length > 0 && <InstagramViewsTable rows={stats.igAccountRows} isSyncing={isSyncing} />}
{stats.categoryStats.length > 0 && (
<SurfaceBox title="Views by category" subheader="YouTube video views plus Reddit post views entered by hand">
- <MetricAreaChart data={stats.charts.categoryViews} dataKey="views" label="Views" color={SERIES.cool} emptyMessage="No views recorded for these categories yet" />
+ <RankingBarChart rows={categoryRows} label="Views" title="Views by category" color={CATEGORY_SERIES} emptyMessage="No views recorded for these categories yet" />
</SurfaceBox>
)}
diff --git a/frontend/src/features/analytics/overview/YouTubeViewsTable.tsx b/frontend/src/features/analytics/overview/YouTubeViewsTable.tsx
index d726a3a..487abbf 100644
--- a/frontend/src/features/analytics/overview/YouTubeViewsTable.tsx
+++ b/frontend/src/features/analytics/overview/YouTubeViewsTable.tsx
@@ -1,7 +1,8 @@
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import SurfaceBox from '@/components/SurfaceBox';
import { RankNumber } from '@/components/ListRow';
-import { fmtNum, fmtNumFull, timeAgo } from '../../../utils/formatters';
+import Num from '@/components/Num';
+import RelativeTime from '@/components/RelativeTime';
import AccountCell from './AccountCell';
import OpenAnalytics from './OpenAnalytics';
import type { AppAccount } from '../../../utils/formatters';
@@ -12,16 +13,16 @@ export interface YouTubeViewsTableProps {
export default function YouTubeViewsTable({ accounts }: YouTubeViewsTableProps) {
return (
- <SurfaceBox title="YouTube views by channel" content={false} className="overflow-hidden">
+ <SurfaceBox title="YouTube views by channel" subheader="Lifetime channel views" content={false} className="overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-10 text-right">#</TableHead>
<TableHead>Channel</TableHead>
<TableHead className="text-right">Total views</TableHead>
- <TableHead className="text-right">Subscribers</TableHead>
- <TableHead className="text-right">Videos</TableHead>
- <TableHead className="text-right">Updated</TableHead>
+ <TableHead className="hidden text-right sm:table-cell">Subscribers</TableHead>
+ <TableHead className="hidden text-right md:table-cell">Videos</TableHead>
+ <TableHead className="hidden text-right md:table-cell">Updated</TableHead>
<TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
</TableRow>
</TableHeader>
@@ -30,13 +31,10 @@ export default function YouTubeViewsTable({ accounts }: YouTubeViewsTableProps)
<TableRow key={account.id}>
<TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>
<AccountCell account={account} name={account.title} />
- <TableCell className="text-right">
- <p className="font-semibold text-ink">{fmtNum(account.viewCount)}</p>
- <p className="text-caption text-ink-faint">{fmtNumFull(account.viewCount)}</p>
- </TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(account.subscriberCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(account.videoCount)}</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{timeAgo(account.lastUpdated)}</TableCell>
+ <TableCell className="text-right font-semibold text-ink"><Num value={account.viewCount} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={account.subscriberCount} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell"><Num value={account.videoCount} /></TableCell>
+ <TableCell className="hidden text-right text-small text-ink-faint md:table-cell"><RelativeTime date={account.lastUpdated} /></TableCell>
<TableCell><OpenAnalytics account={account} name={account.title} /></TableCell>
</TableRow>
))}
diff --git a/frontend/src/features/analytics/overview/overviewCharts.ts b/frontend/src/features/analytics/overview/overviewCharts.ts
index b111f0f..419206c 100644
--- a/frontend/src/features/analytics/overview/overviewCharts.ts
+++ b/frontend/src/features/analytics/overview/overviewCharts.ts
@@ -76,6 +76,25 @@ export function audienceLegendOf(groups: AccountGroups, categoryStats: CategoryC
].filter(Boolean) as AudienceLegendItem[];
}
+const AUDIENCE_KIND: Record<AudiencePointType, string> = {
+ youtube: 'YouTube subscribers',
+ instagram: 'Instagram followers',
+ reddit: 'Reddit karma',
+ category: 'Category karma',
+};
+
+export interface AudienceRankingRow {
+ name: string;
+ value: number;
+ kind: string;
+ color: string;
+}
+
+// each bar says what it counts, because subscribers, followers and karma share one axis
+export function audienceRankingOf(points: AudiencePoint[]): AudienceRankingRow[] {
+ return points.map(point => ({ name: point.name, value: point.value, kind: AUDIENCE_KIND[point.type], color: audienceDotColor(point.type) }));
+}
+
export function audienceDotColor(type: AudiencePointType): string {
if (type === 'category') return CATEGORY_SERIES;
return PLATFORM_META[type]?.series;
diff --git a/frontend/src/features/analytics/overview/overviewStats.ts b/frontend/src/features/analytics/overview/overviewStats.ts
index 13be8da..d18582e 100644
--- a/frontend/src/features/analytics/overview/overviewStats.ts
+++ b/frontend/src/features/analytics/overview/overviewStats.ts
@@ -27,10 +27,20 @@ export interface AccountCacheFields {
contentTypes?: Partial<Record<InstagramContentType, Partial<InstagramContentTypeTotals>>>;
fetchedPosts?: number;
totalScore?: number;
+ fetchedAt?: string;
}
export type AccountCache = Record<string, AccountCacheFields>;
+// the Overview is only as fresh as its oldest cached account, so that is the age it shows
+export function oldestFetchedAt(cache: AccountCache): string | null {
+ const times = Object.values(cache)
+ .map(entry => (entry.cacheWarmed ? entry.fetchedAt : undefined))
+ .filter((time): time is string => typeof time === 'string' && !Number.isNaN(Date.parse(time)));
+ if (times.length === 0) return null;
+ return times.reduce((oldest, time) => (Date.parse(time) < Date.parse(oldest) ? time : oldest));
+}
+
export interface AccountTotals {
subscribers: number;
views: number;
diff --git a/frontend/src/features/analytics/overview/useOverviewData.ts b/frontend/src/features/analytics/overview/useOverviewData.ts
index 2acc234..a26db31 100644
--- a/frontend/src/features/analytics/overview/useOverviewData.ts
+++ b/frontend/src/features/analytics/overview/useOverviewData.ts
@@ -1,32 +1,41 @@
-import { useEffect, useState } from 'react';
+import { useCallback, useEffect, useState } from 'react';
import { api } from '../../../services/api';
import type { OverviewResponse } from '@shared/types/domain.ts';
import type { AccountCacheFields, OverviewAccount } from './overviewStats.ts';
const SYNC_POLL_DELAYS = [4000, 8000, 16000];
-async function fetchOverview(): Promise<OverviewResponse | null> {
- try {
- return await api.getOverview();
- } catch {
- // a failed load keeps the previous overview; the next poll or visit tries again
- return null;
- }
-}
-
export function useOverviewData(accounts: OverviewAccount[]) {
const [overviewData, setOverviewData] = useState<OverviewResponse>({ tracked: [], analyticsCache: {} });
const [overviewLoading, setOverviewLoading] = useState(true);
+ const [loaded, setLoaded] = useState(false);
+ const [error, setError] = useState<string | null>(null);
const [syncPolls, setSyncPolls] = useState(0);
+ // a failed load keeps the previous overview and says so, instead of showing zeros as if they were real
+ const fetchOverview = useCallback(async (): Promise<void> => {
+ try {
+ setOverviewData(await api.getOverview());
+ setLoaded(true);
+ setError(null);
+ } catch (err) {
+ setError(`Couldn't load the overview. ${(err as Error).message}`);
+ }
+ }, []);
+
useEffect(() => {
const loadOverview = async () => {
- const data = await fetchOverview();
- if (data) setOverviewData(data);
+ await fetchOverview();
setOverviewLoading(false);
};
loadOverview();
- }, []);
+ }, [fetchOverview]);
+
+ const retry = useCallback(() => {
+ setOverviewLoading(true);
+ setSyncPolls(0);
+ fetchOverview().finally(() => setOverviewLoading(false));
+ }, [fetchOverview]);
// poll with backoff while syncing, then stop so the label never hangs
const isSyncing = !overviewLoading && syncPolls < SYNC_POLL_DELAYS.length && accounts.some(account => {
@@ -35,14 +44,12 @@ export function useOverviewData(accounts: OverviewAccount[]) {
useEffect(() => {
if (!isSyncing) return undefined;
- const pollOverview = async () => {
- const data = await fetchOverview();
- if (data) setOverviewData(data);
+ const timer = setTimeout(async () => {
+ await fetchOverview();
setSyncPolls(polls => polls + 1);
- };
- const timer = setTimeout(pollOverview, SYNC_POLL_DELAYS[syncPolls]);
+ }, SYNC_POLL_DELAYS[syncPolls]);
return () => clearTimeout(timer);
- }, [isSyncing, syncPolls]);
+ }, [isSyncing, syncPolls, fetchOverview]);
- return { overviewData, overviewLoading, isSyncing };
+ return { overviewData, overviewLoading, loaded, error, retry, isSyncing };
}
diff --git a/frontend/src/features/analytics/reddit/RedditAnalytics.tsx b/frontend/src/features/analytics/reddit/RedditAnalytics.tsx
index ada4e77..ee2aba3 100644
--- a/frontend/src/features/analytics/reddit/RedditAnalytics.tsx
+++ b/frontend/src/features/analytics/reddit/RedditAnalytics.tsx
@@ -1,12 +1,16 @@
import { useParams } from 'react-router-dom';
-import { Award, MessageSquare, Star, TrendingUp, UserX } from 'lucide-react';
-import { Progress } from '@/components/ui/progress';
+import { UserX } from 'lucide-react';
+import { Alert, AlertAction, AlertDescription } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
import PageHeader from '@/components/PageHeader';
import MetricBox from '@/components/MetricBox';
+import Num from '@/components/Num';
import SurfaceBox from '@/components/SurfaceBox';
-import { EmptyState, PageSkeleton } from '@/components/StateViews';
+import { EmptyState, ErrorState, PageSkeleton } from '@/components/StateViews';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { useAppContext } from '../../../context/AppContext';
import { useAccountAnalytics } from '../../../hooks/use-account-analytics';
+import { useDocumentTitle } from '@/hooks/use-document-title';
import { api } from '../../../services/api';
import { fmtNum } from '../../../utils/formatters';
import { MEDIA_TYPE_LABELS } from './redditPostUtils';
@@ -22,11 +26,16 @@ import RedditTopPostsTable from './RedditTopPostsTable';
const BACK = { to: '/', label: 'Overview' };
+const { redditPosts: Posts, karma: Karma, comments: Comments, awards: Awards } = METRIC_ICONS;
+
export default function RedditAnalytics() {
const { id } = useParams();
const { accounts } = useAppContext();
const account = accounts.find(item => item.id === id);
- const { loading, profile, analytics, refreshing, handleRefresh } = useAccountAnalytics(account, api.getRedditAnalytics, 'Reddit');
+ const { initialLoading, error, profile, analytics, fetchedAt, refreshing, handleRefresh, retry } = useAccountAnalytics(
+ account, api.getRedditAnalytics, 'Reddit',
+ );
+ useDocumentTitle(account ? `u/${account.username}` : null);
if (!account) {
return (
@@ -39,40 +48,60 @@ export default function RedditAnalytics() {
);
}
- if (loading) return <PageSkeleton metrics={4} />;
+ if (initialLoading) return <PageSkeleton metrics={4} />;
const profileData = profile || account;
- const analyticsData: Partial<RedditAnalyticsData> = analytics || {};
+
+ if (!analytics) {
+ return (
+ <div className="flex flex-col gap-6">
+ <RedditHeader account={account} profile={profileData} back={BACK} refreshing={refreshing} onRefresh={handleRefresh} fetchedAt={null} />
+ <SurfaceBox>
+ <ErrorState title="Reddit analytics could not load" description={error ?? undefined} onRetry={retry} />
+ </SurfaceBox>
+ </div>
+ );
+ }
+
+ const analyticsData: Partial<RedditAnalyticsData> = analytics;
+ const postsPeriod = `Last ${analyticsData.fetchedPosts ?? 0} posts`;
return (
<div className="flex flex-col gap-6">
- <RedditHeader account={account} profile={profileData} back={BACK} refreshing={refreshing} onRefresh={handleRefresh} />
+ <RedditHeader account={account} profile={profileData} back={BACK} refreshing={refreshing} onRefresh={handleRefresh} fetchedAt={fetchedAt} />
- {refreshing && <Progress value={null} aria-label="Refreshing account" />}
+ {error && (
+ <Alert variant="destructive" role="alert">
+ <AlertDescription>{error} The numbers below are from the last successful load.</AlertDescription>
+ <AlertAction><Button size="xs" variant="outline" onClick={retry}>Try again</Button></AlertAction>
+ </Alert>
+ )}
- <RedditKarmaSummary profile={profileData} />
+ <div className="flex flex-col gap-6" aria-busy={refreshing}>
+ <RedditKarmaSummary profile={profileData} />
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
- <MetricBox icon={<TrendingUp />} label="Posts fetched" value={fmtNum(analyticsData.fetchedPosts)} subtitle={`${analyticsData.postsLast30Days ?? 0} in the last 30 days`} />
- <MetricBox icon={<Award />} label="Karma from posts" value={fmtNum(analyticsData.totalScore)} subtitle={`${fmtNum(analyticsData.avgScore)} per post on average`} highlight />
- <MetricBox icon={<MessageSquare />} label="Comments" value={fmtNum(analyticsData.totalComments)} subtitle={`${fmtNum(analyticsData.avgComments)} per post on average`} />
- <MetricBox icon={<Star />} label="Awards received" value={fmtNum(analyticsData.totalAwards ?? 0)} subtitle={`${analyticsData.avgAwards ?? 0} per post on average`} />
- </div>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
+ <MetricBox icon={<Karma />} label="Karma from posts" value={<Num value={analyticsData.totalScore} />} period={postsPeriod} subtitle={`${fmtNum(analyticsData.avgScore)} per post on average`} highlight />
+ <MetricBox icon={<Posts />} label="Posts loaded" value={<Num value={analyticsData.fetchedPosts} />} period="Newest first" subtitle={`${analyticsData.postsLast30Days ?? 0} in the last 30 days`} />
+ <MetricBox icon={<Comments />} label="Comments" value={<Num value={analyticsData.totalComments} />} period={postsPeriod} subtitle={`${fmtNum(analyticsData.avgComments)} per post on average`} />
+ <MetricBox icon={<Awards />} label="Awards received" value={<Num value={analyticsData.totalAwards ?? 0} />} period={postsPeriod} subtitle={`${analyticsData.avgAwards ?? 0} per post on average`} />
+ </div>
- {(analyticsData.monthlyBreakdown?.length as number) > 0 && (
- <RedditKarmaCharts
- monthlyBreakdown={analyticsData.monthlyBreakdown!}
- mediaTypeData={mediaTypeDataOf(analyticsData.mediaTypeDistribution, MEDIA_TYPE_LABELS)}
- />
- )}
+ {(analyticsData.monthlyBreakdown?.length as number) > 0 && (
+ <RedditKarmaCharts
+ monthlyBreakdown={analyticsData.monthlyBreakdown!}
+ mediaTypeData={mediaTypeDataOf(analyticsData.mediaTypeDistribution, MEDIA_TYPE_LABELS)}
+ />
+ )}
- <RedditStatPanels analytics={analyticsData} />
+ <RedditStatPanels analytics={analyticsData} />
- {(analyticsData.postsByDayOfWeek?.length as number) > 0 && <RedditTimingCharts analytics={analyticsData} />}
+ {(analyticsData.postsByDayOfWeek?.length as number) > 0 && <RedditTimingCharts analytics={analyticsData} />}
- {(analyticsData.subredditBreakdown?.length as number) > 0 && <RedditSubredditTable subreddits={analyticsData.subredditBreakdown!} />}
+ {(analyticsData.subredditBreakdown?.length as number) > 0 && <RedditSubredditTable subreddits={analyticsData.subredditBreakdown!} />}
- {(analyticsData.topPosts?.length as number) > 0 && <RedditTopPostsTable posts={analyticsData.topPosts!} />}
+ {(analyticsData.topPosts?.length as number) > 0 && <RedditTopPostsTable posts={analyticsData.topPosts!} />}
+ </div>
</div>
);
}
diff --git a/frontend/src/features/analytics/reddit/RedditHeader.tsx b/frontend/src/features/analytics/reddit/RedditHeader.tsx
index d4f5752..8b3c0fe 100644
--- a/frontend/src/features/analytics/reddit/RedditHeader.tsx
+++ b/frontend/src/features/analytics/reddit/RedditHeader.tsx
@@ -1,11 +1,12 @@
import { Link } from 'react-router-dom';
-import { FileText, RefreshCw } from 'lucide-react';
+import { FileText } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import PageHeader from '@/components/PageHeader';
+import RefreshButton from '@/components/RefreshButton';
+import DataFreshness from '@/components/DataFreshness';
import { AccountAvatar } from '@/components/platform';
-import { cn } from '@/lib/utils';
-import { fmtDate, timeAgo } from '../../../utils/formatters';
+import { fmtDate } from '../../../utils/formatters';
import type { AppAccount } from '../../../utils/formatters';
import type { PageHeaderBack } from '@/components/PageHeader';
import type { RedditProfileFields } from './redditAnalyticsData.ts';
@@ -16,34 +17,34 @@ export interface RedditHeaderProps {
back: PageHeaderBack;
refreshing: boolean;
onRefresh: () => void;
+ // when the posts were fetched; Reddit numbers are cached for up to 6 hours
+ fetchedAt: string | null;
}
-export default function RedditHeader({ account, profile, back, refreshing, onRefresh }: RedditHeaderProps) {
+export default function RedditHeader({ account, profile, back, refreshing, onRefresh, fetchedAt }: RedditHeaderProps) {
return (
<PageHeader
back={back}
- media={<AccountAvatar account={{ ...account, iconUrl: profile.iconUrl || account.iconUrl }} size="xl" showPlatform />}
+ media={<AccountAvatar account={{ ...account, iconUrl: profile.iconUrl || account.iconUrl }} size="xl" showPlatform decorative />}
title={`u/${profile.username || account.username}`}
description={
- <span className="flex flex-wrap items-center gap-1.5">
- {profile.isGold && <Badge variant="warning">Gold</Badge>}
- {profile.verified && <Badge variant="info">Verified</Badge>}
- {profile.isMod && <Badge variant="outline">Moderator</Badge>}
- <span>
- {profile.createdAt ? `Joined ${fmtDate(profile.createdAt)}. ` : ''}Refreshed {timeAgo(account.lastUpdated).toLowerCase()}.
+ <span className="flex flex-col gap-1.5">
+ <span className="flex flex-wrap items-center gap-1.5">
+ {profile.isGold && <Badge variant="warning">Gold</Badge>}
+ {profile.verified && <Badge variant="info">Verified</Badge>}
+ {profile.isMod && <Badge variant="outline">Moderator</Badge>}
+ {profile.createdAt && <span>Joined {fmtDate(profile.createdAt)}</span>}
</span>
+ <DataFreshness fetchedAt={fetchedAt} />
</span>
}
actions={
<>
- <Button variant="outline" size="sm" render={<Link to={`/reddit-posts/${account.id}`} />}>
- <FileText data-icon="inline-start" />
+ <Button variant="outline" render={<Link to={`/reddit-posts/${account.id}`} />}>
+ <FileText data-icon="inline-start" aria-hidden="true" />
View posts
</Button>
- <Button variant="outline" size="sm" onClick={onRefresh} disabled={refreshing}>
- <RefreshCw data-icon="inline-start" className={cn(refreshing && 'animate-spin')} />
- {refreshing ? 'Refreshing' : 'Refresh'}
- </Button>
+ <RefreshButton refreshing={refreshing} onRefresh={onRefresh} />
</>
}
/>
diff --git a/frontend/src/features/analytics/reddit/RedditKarmaCharts.tsx b/frontend/src/features/analytics/reddit/RedditKarmaCharts.tsx
index 8b6851a..439d187 100644
--- a/frontend/src/features/analytics/reddit/RedditKarmaCharts.tsx
+++ b/frontend/src/features/analytics/reddit/RedditKarmaCharts.tsx
@@ -3,13 +3,20 @@ import {
} from 'recharts';
import type { TooltipValueType } from 'recharts';
import ChartPanel from '@/components/ChartPanel';
-import { SERIES, axisProps, gridProps, legendStyle, tooltipStyle } from '@/lib/chart';
+import { PLATFORM_META } from '@/lib/accounts';
+import { axisProps, gridProps, legendStyle, rankingSummary, tooltipStyle, trendSummary } from '@/lib/chart';
import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import type { NumberLike } from '../../../utils/formatters';
import type { RedditMonthStats } from '@shared/types/reddit.ts';
import type { RedditMediaSlice } from './redditAnalyticsData.ts';
-function formatKarmaTooltip(value: TooltipValueType | undefined, name: string | number | undefined) {
- return [fmtNumFull(value as number), name === 'score' ? 'Karma' : 'Posts'];
+// karma keeps Reddit's series colour here and on the Overview, so one colour means one thing
+const KARMA = PLATFORM_META.reddit.series;
+
+const full = (value: unknown) => fmtNumFull(value as NumberLike);
+
+function formatKarmaTooltip(value: TooltipValueType | undefined) {
+ return [fmtNumFull(value as number), 'Karma'];
}
function formatPostsTooltip(value: TooltipValueType | undefined) {
@@ -22,26 +29,51 @@ export interface RedditKarmaChartsProps {
}
export default function RedditKarmaCharts({ monthlyBreakdown, mediaTypeData }: RedditKarmaChartsProps) {
+ const karmaByMonth = monthlyBreakdown.map(month => ({ name: month.month, value: month.score }));
return (
<div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
- <ChartPanel title="Karma over time" height={240} className="xl:col-span-2">
+ <ChartPanel
+ title="Karma by month"
+ subheader="Karma earned by the posts submitted in each month"
+ height={240}
+ className="xl:col-span-2"
+ summary={trendSummary(karmaByMonth, fmtNum, 'karma')}
+ table={{
+ caption: 'Karma by month',
+ columns: [
+ { key: 'month', label: 'Month' },
+ { key: 'posts', label: 'Posts', numeric: true, format: full },
+ { key: 'score', label: 'Karma', numeric: true, format: full },
+ ],
+ rows: monthlyBreakdown,
+ }}
+ >
<AreaChart data={monthlyBreakdown} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
<defs>
<linearGradient id="redditGrad" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor={SERIES.primary} stopOpacity={0.2} />
- <stop offset="95%" stopColor={SERIES.primary} stopOpacity={0} />
+ <stop offset="5%" stopColor={KARMA} stopOpacity={0.2} />
+ <stop offset="95%" stopColor={KARMA} stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="month" {...axisProps} />
<YAxis {...axisProps} tickFormatter={fmtNum} width={48} />
<ReTooltip contentStyle={tooltipStyle} cursor={{ stroke: 'var(--line-strong)' }} formatter={formatKarmaTooltip} />
- <Area type="monotone" dataKey="score" stroke={SERIES.primary} strokeWidth={2} fill="url(#redditGrad)" dot={{ fill: SERIES.primary, r: 3, strokeWidth: 0 }} />
+ <Area type="monotone" dataKey="score" name="Karma" stroke={KARMA} strokeWidth={2} fill="url(#redditGrad)" dot={{ fill: KARMA, r: 3, strokeWidth: 0 }} />
</AreaChart>
</ChartPanel>
{mediaTypeData.length > 0 && (
- <ChartPanel title="Post types" height={240}>
+ <ChartPanel
+ title="Post types"
+ height={240}
+ summary={rankingSummary(mediaTypeData, fmtNum, 'posts')}
+ table={{
+ caption: 'Post types',
+ columns: [{ key: 'name', label: 'Type' }, { key: 'value', label: 'Posts', numeric: true, format: full }],
+ rows: mediaTypeData,
+ }}
+ >
<PieChart>
<Pie data={mediaTypeData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={48} paddingAngle={2} strokeWidth={0}>
{mediaTypeData.map(entry => <Cell key={entry.name} fill={entry.color} />)}
diff --git a/frontend/src/features/analytics/reddit/RedditKarmaSummary.tsx b/frontend/src/features/analytics/reddit/RedditKarmaSummary.tsx
index b2580e3..7d747a8 100644
--- a/frontend/src/features/analytics/reddit/RedditKarmaSummary.tsx
+++ b/frontend/src/features/analytics/reddit/RedditKarmaSummary.tsx
@@ -1,4 +1,5 @@
import SurfaceBox from '@/components/SurfaceBox';
+import Num from '@/components/Num';
import { cn } from '@/lib/utils';
import { karmaSummaryOf } from './redditAnalyticsData.ts';
import type { RedditProfileFields } from './redditAnalyticsData.ts';
@@ -9,16 +10,18 @@ export interface RedditKarmaSummaryProps {
export default function RedditKarmaSummary({ profile }: RedditKarmaSummaryProps) {
return (
- <SurfaceBox title="Karma" subheader="Earned across posts and comments">
- <div className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-4">
+ <SurfaceBox title="Karma" subheader="Earned across posts and comments, all time">
+ <dl className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-4">
{karmaSummaryOf(profile).map(item => (
<div key={item.label} className="flex flex-col gap-1">
- <span className="text-small font-medium text-ink-muted">{item.label}</span>
- <span className={cn('font-heading text-2xl font-semibold tracking-[-0.02em] tabular-nums', item.lead ? 'text-brand-text' : 'text-ink')}>{item.value}</span>
- <span className="text-caption text-ink-faint">{item.sub}</span>
+ <dt className="text-small font-medium text-ink-muted">{item.label}</dt>
+ <dd className={cn('font-heading text-page-title font-semibold tabular-nums', item.lead ? 'text-brand-text' : 'text-ink')}>
+ <Num value={item.value} />
+ </dd>
+ <dd className="text-caption text-ink-faint">{item.sub}</dd>
</div>
))}
- </div>
+ </dl>
</SurfaceBox>
);
}
diff --git a/frontend/src/features/analytics/reddit/RedditPostFilters.tsx b/frontend/src/features/analytics/reddit/RedditPostFilters.tsx
index 3c61006..6bee3f4 100644
--- a/frontend/src/features/analytics/reddit/RedditPostFilters.tsx
+++ b/frontend/src/features/analytics/reddit/RedditPostFilters.tsx
@@ -1,23 +1,21 @@
-import React from 'react';
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import SearchField from '@/components/SearchField';
+import SortSelect from '@/components/SortSelect';
import { REDDIT_SORT_OPTIONS } from './redditPostUtils';
import type { RedditFilterOption } from './redditPostUtils';
import type { AppAccount } from '../../../utils/formatters';
interface FilterSelectProps {
- value: string | undefined;
- onChange: ((value: string) => void) | undefined;
+ value: string;
+ onChange: (value: string) => void;
items: RedditFilterOption[];
label: string;
- className?: string;
}
-// the items have no null value, so the select only ever reports a string
-function FilterSelect({ value, onChange, items, label, className = 'w-full sm:w-48' }: FilterSelectProps) {
+function FilterSelect({ value, onChange, items, label }: FilterSelectProps) {
return (
- <Select value={value} onValueChange={onChange as ((value: string | null) => void) | undefined} items={items}>
- <SelectTrigger className={className} aria-label={label}><SelectValue /></SelectTrigger>
+ <Select value={value} onValueChange={next => { if (next) onChange(next as string); }} items={items}>
+ <SelectTrigger className="h-(--control-h-lg) w-full sm:w-48" aria-label={label}><SelectValue /></SelectTrigger>
<SelectContent>
<SelectGroup>
{items.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}
@@ -44,10 +42,10 @@ export default function RedditPostFilters({ query, onQuery, sort, onSort, subred
return (
<div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap">
<SearchField value={query} onChange={onQuery} placeholder="Search titles, subreddits and flair" className="min-w-56 flex-1" />
- {accounts && accounts.length > 1 && (
+ {accounts && accounts.length > 1 && onAccount && (
<FilterSelect
label="Account"
- value={accountId}
+ value={accountId ?? 'all'}
onChange={onAccount}
items={[{ value: 'all', label: 'All accounts' }, ...accounts.map(account => ({ value: account.id, label: `u/${account.username}` }))]}
/>
@@ -58,7 +56,7 @@ export default function RedditPostFilters({ query, onQuery, sort, onSort, subred
onChange={onSubreddit}
items={[{ value: 'all', label: 'All subreddits' }, ...subreddits.map(subredditName => ({ value: subredditName, label: `r/${subredditName}` }))]}
/>
- <FilterSelect label="Sort" value={sort} onChange={onSort} items={REDDIT_SORT_OPTIONS} className="w-full sm:w-44" />
+ <SortSelect options={REDDIT_SORT_OPTIONS} value={sort} onChange={onSort} />
</div>
);
}
diff --git a/frontend/src/features/analytics/reddit/RedditPostTable.tsx b/frontend/src/features/analytics/reddit/RedditPostTable.tsx
index 43d401b..06ea5fb 100644
--- a/frontend/src/features/analytics/reddit/RedditPostTable.tsx
+++ b/frontend/src/features/analytics/reddit/RedditPostTable.tsx
@@ -1,4 +1,3 @@
-import React from 'react';
import { Link } from 'react-router-dom';
import { ExternalLink, FileText, Image, Video, Link2 } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
@@ -6,64 +5,54 @@ import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import SurfaceBox from '@/components/SurfaceBox';
-import { EmptyState } from '@/components/StateViews';
+import ColumnHint from '@/components/ColumnHint';
+import Num from '@/components/Num';
import { AccountAvatar } from '@/components/platform';
import { MEDIA_TYPE_LABELS } from './redditPostUtils';
-import { fmtNum, fmtDate } from '../../../utils/formatters';
-import ColumnHint from '@/components/ColumnHint';
+import { fmtDate } from '../../../utils/formatters';
import type { RedditMediaType } from '@shared/types/reddit.ts';
import type { AppAccount } from '../../../utils/formatters';
import type { RedditPostRow } from './redditPostUtils';
const MEDIA_TYPE_ICONS: Record<RedditMediaType, LucideIcon> = { image: Image, video: Video, link: Link2, text: FileText };
-interface MediaTypeIconProps {
- type: RedditMediaType;
- className?: string;
-}
-
-function MediaTypeIcon({ type, className = 'size-3.5' }: MediaTypeIconProps) {
+function MediaTypeIcon({ type }: { type: RedditMediaType }) {
const Icon = MEDIA_TYPE_ICONS[type] || FileText;
- return <Icon className={className} />;
+ return <Icon className="size-3.5" aria-hidden="true" />;
}
export interface RedditPostTableProps {
posts: RedditPostRow[];
+ // rank of the first post on this page
+ offset?: number;
showAccount?: boolean;
accountsById?: Record<string, AppAccount>;
}
-export default function RedditPostTable({ posts, showAccount = false, accountsById = {} }: RedditPostTableProps) {
- if (posts.length === 0) {
- return (
- <SurfaceBox>
- <EmptyState compact icon={<FileText />} title="No posts match" description="Clear the search or pick a different subreddit." />
- </SurfaceBox>
- );
- }
+export default function RedditPostTable({ posts, offset = 0, showAccount = false, accountsById = {} }: RedditPostTableProps) {
return (
- <SurfaceBox content={false} className="overflow-hidden">
+ <SurfaceBox title="Posts" content={false} className="overflow-hidden">
<Table>
<TableHeader>
<TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead>Post</TableHead>
- {showAccount && <TableHead className="w-40">Account</TableHead>}
- <TableHead className="w-24">Type</TableHead>
+ <TableHead className="hidden w-10 text-right sm:table-cell">#</TableHead>
+ <TableHead className="sticky left-0 z-[1] bg-surface-raised">Post</TableHead>
+ {showAccount && <TableHead className="hidden w-40 lg:table-cell">Account</TableHead>}
+ <TableHead className="hidden w-24 md:table-cell">Type</TableHead>
<TableHead className="w-24 text-right">Karma</TableHead>
- <TableHead className="w-24 text-right">Comments</TableHead>
- <TableHead className="w-32 text-right"><ColumnHint label="Upvote rate" hint="Share of votes on the post that are upvotes. 96% means 96 of every 100 votes were up." /></TableHead>
- <TableHead className="w-28 text-right">Posted</TableHead>
+ <TableHead className="hidden w-24 text-right sm:table-cell">Comments</TableHead>
+ <TableHead className="hidden w-32 text-right md:table-cell"><ColumnHint label="Upvote rate" hint="Share of votes on the post that are upvotes. 96% means 96 of every 100 votes were up." /></TableHead>
+ <TableHead className="hidden w-28 text-right md:table-cell">Posted</TableHead>
<TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{posts.map((post, i) => (
<TableRow key={`${post.accountId || ''}-${post.id}`}>
- <TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>
- <TableCell className="whitespace-normal">
- <div className="max-w-md">
- <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{post.title}</p>
+ <TableCell className="hidden text-right font-mono text-caption text-ink-faint sm:table-cell">{offset + i + 1}</TableCell>
+ <TableCell className="sticky left-0 z-[1] bg-surface-raised whitespace-normal">
+ <div className="max-w-56 sm:max-w-md">
+ <p className="line-clamp-2 text-sm font-medium leading-snug text-ink" title={post.title}>{post.title}</p>
<div className="mt-1 flex flex-wrap items-center gap-1.5">
<span className="text-caption text-ink-faint">{post.subredditPrefixed}</span>
{post.flair && <Badge variant="outline">{post.flair}</Badge>}
@@ -72,30 +61,30 @@ export default function RedditPostTable({ posts, showAccount = false, accountsBy
</div>
</TableCell>
{showAccount && (
- <TableCell>
- <Link to={`/reddit/${post.accountId}`} className="flex items-center gap-2 text-small text-ink-muted hover:text-ink">
- <AccountAvatar account={accountsById[post.accountId!] || { platform: 'reddit', username: post.accountUsername, iconUrl: post.accountIconUrl }} size="xs" />
+ <TableCell className="hidden lg:table-cell">
+ <Link to={`/reddit/${post.accountId}`} className="flex items-center gap-2 text-small text-ink-muted underline-offset-4 hover:text-ink hover:underline">
+ <AccountAvatar account={accountsById[post.accountId!] || { platform: 'reddit', username: post.accountUsername, iconUrl: post.accountIconUrl }} size="xs" decorative />
u/{post.accountUsername}
</Link>
</TableCell>
)}
- <TableCell>
+ <TableCell className="hidden md:table-cell">
<span className="flex items-center gap-1.5 text-small text-ink-muted">
<MediaTypeIcon type={post.mediaType} />
{MEDIA_TYPE_LABELS[post.mediaType] || post.mediaType}
</span>
</TableCell>
- <TableCell className="text-right font-semibold text-ink">{fmtNum(post.score)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(post.numComments)}</TableCell>
- <TableCell className="text-right text-ink-muted">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{fmtDate(post.createdAt)}</TableCell>
+ <TableCell className="text-right font-semibold text-ink"><Num value={post.score} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={post.numComments} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>
+ <TableCell className="hidden text-right text-small text-ink-faint md:table-cell">{fmtDate(post.createdAt)}</TableCell>
<TableCell>
<Button
variant="ghost"
size="icon-xs"
- render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label={`Open "${post.title}" on Reddit`} />}
+ render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label={`Open "${post.title}" on Reddit (opens in a new tab)`} />}
>
- <ExternalLink />
+ <ExternalLink aria-hidden="true" />
</Button>
</TableCell>
</TableRow>
diff --git a/frontend/src/features/analytics/reddit/RedditPosts.tsx b/frontend/src/features/analytics/reddit/RedditPosts.tsx
index 9feba37..cf95a10 100644
--- a/frontend/src/features/analytics/reddit/RedditPosts.tsx
+++ b/frontend/src/features/analytics/reddit/RedditPosts.tsx
@@ -1,45 +1,63 @@
-import React, { useEffect, useMemo, useState } from 'react';
+import { useMemo } from 'react';
import { useParams } from 'react-router-dom';
import { UserX } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import PageHeader from '@/components/PageHeader';
import SurfaceBox from '@/components/SurfaceBox';
-import { EmptyState } from '@/components/StateViews';
+import Pager from '@/components/Pager';
+import RefreshButton from '@/components/RefreshButton';
+import DataFreshness from '@/components/DataFreshness';
+import ActiveFilters from '@/components/ActiveFilters';
+import NoResults from '@/components/NoResults';
+import { EmptyState, ErrorState } from '@/components/StateViews';
import { AccountAvatar } from '@/components/platform';
+import { accountName } from '@/lib/accounts';
+import { useDocumentTitle } from '@/hooks/use-document-title';
+import { pageSlice, resultCountLabel } from '@/lib/library';
import { useAppContext } from '../../../context/AppContext';
import { api } from '../../../services/api';
+import type { AppAccount } from '../../../utils/formatters';
+import { useLibrarySources } from '../useLibrarySources';
+import { useLibraryParams } from '../useLibraryParams';
import RedditPostFilters from './RedditPostFilters';
import RedditPostTable from './RedditPostTable';
-import { filterAndSortRedditPosts, subredditsOf } from './redditPostUtils';
-import type { RedditPost } from '@shared/types/reddit.ts';
+import { filterAndSortRedditPosts, mergeAccountPosts, redditSortOf, subredditsOf } from './redditPostUtils';
-export default function RedditPosts() {
- const { id } = useParams();
- const { accounts, showToast } = useAppContext();
- const account = accounts.find(a => a.id === id);
+const ITEMS_PER_PAGE = 25;
+const RESULTS_ID = 'account-reddit-results';
+
+const DEFAULTS = { q: '', subreddit: 'all', sort: 'score-desc' };
- const [loading, setLoading] = useState(true);
- const [posts, setPosts] = useState<RedditPost[]>([]);
- const [query, setQuery] = useState('');
- const [sort, setSort] = useState('score-desc');
- const [subFilter, setSubFilter] = useState('all');
+function fetchAccountPosts(id: string, fresh: boolean) {
+ return api.getRedditAnalytics(id, fresh);
+}
+
+function nameOf(account: AppAccount): string {
+ return accountName(account);
+}
- useEffect(() => {
- if (!account) return;
- setLoading(true);
- api.getRedditPosts(account.id)
- .then(data => setPosts(Array.isArray(data) ? data : []))
- .catch(err => showToast(`Couldn't load posts. ${err.message}`, 'error'))
- .finally(() => setLoading(false));
- // reload per route, not per account list refresh
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [id]);
+export default function RedditPosts() {
+ const { id } = useParams();
+ const { accounts } = useAppContext();
+ const account = accounts.find(item => item.id === id);
+ const sources = useMemo(() => (account ? [account] : []), [account]);
+ const library = useLibrarySources(sources, fetchAccountPosts, nameOf, 'Reddit posts');
+ const posts = useMemo(() => mergeAccountPosts(library.sources, library.results), [library.sources, library.results]);
+ const { values, page, update, clear, setPage } = useLibraryParams(DEFAULTS);
+ const sort = redditSortOf(values.sort);
+ useDocumentTitle(account ? `Posts by u/${account.username}` : null);
const subreddits = useMemo(() => subredditsOf(posts), [posts]);
const filtered = useMemo(
- () => filterAndSortRedditPosts(posts, { query, sort, subreddit: subFilter }),
- [posts, query, sort, subFilter],
+ () => filterAndSortRedditPosts(posts, { query: values.q, sort, subreddit: values.subreddit }),
+ [posts, values.q, sort, values.subreddit],
);
+ const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
+ const clearFilters = () => clear(['q', 'subreddit']);
+ const activeFilters = [
+ values.q && { key: 'q', label: `"${values.q}"`, onRemove: () => update({ q: '' }) },
+ values.subreddit !== 'all' && { key: 'subreddit', label: `r/${values.subreddit}`, onRemove: () => update({ subreddit: 'all' }) },
+ ].filter(Boolean) as { key: string; label: string; onRemove: () => void }[];
if (!account) {
return (
@@ -52,13 +70,22 @@ export default function RedditPosts() {
);
}
+ const loading = library.initialLoading;
+ const failure = library.failures[0];
+
return (
<div className="flex flex-col gap-6">
<PageHeader
back={{ to: `/reddit/${account.id}`, label: `u/${account.username} analytics` }}
- media={<AccountAvatar account={account} size="lg" />}
+ media={<AccountAvatar account={account} size="lg" decorative />}
title={`Posts by u/${account.username}`}
- description={loading ? 'Loading posts' : `${filtered.length} of ${posts.length} posts`}
+ description={
+ <span className="flex flex-col gap-1">
+ <span>{loading ? 'Loading posts' : `${posts.length} posts loaded`}</span>
+ {!loading && <DataFreshness fetchedAt={library.fetchedAt} />}
+ </span>
+ }
+ actions={<RefreshButton refreshing={library.refreshing} onRefresh={library.refresh} disabled={loading} />}
/>
{loading ? (
@@ -66,14 +93,37 @@ export default function RedditPosts() {
<Skeleton className="h-10 rounded-field" />
<Skeleton className="h-96 rounded-card" />
</div>
+ ) : failure && posts.length === 0 ? (
+ <SurfaceBox>
+ <ErrorState title="These posts could not load" description={failure.message} onRetry={library.refresh} />
+ </SurfaceBox>
) : (
<>
<RedditPostFilters
- query={query} onQuery={setQuery}
- sort={sort} onSort={setSort}
- subreddit={subFilter} onSubreddit={setSubFilter} subreddits={subreddits}
+ query={values.q} onQuery={value => update({ q: value }, { replace: true })}
+ sort={sort} onSort={value => update({ sort: value })}
+ subreddit={values.subreddit} onSubreddit={value => update({ subreddit: value })} subreddits={subreddits}
+ />
+ <ActiveFilters countLabel={resultCountLabel(filtered.length, posts.length, 'posts')} filters={activeFilters} onClearAll={clearFilters} />
+ <div id={RESULTS_ID} tabIndex={-1} className="outline-none" aria-busy={library.refreshing}>
+ {posts.length === 0 ? (
+ <SurfaceBox><EmptyState compact icon={<UserX />} title="No posts yet" description={`u/${account.username} has not submitted any posts Reddit lets Twiligent read.`} /></SurfaceBox>
+ ) : filtered.length === 0 ? (
+ <SurfaceBox><NoResults noun="posts" query={values.q} onClear={clearFilters} /></SurfaceBox>
+ ) : (
+ <RedditPostTable posts={paged.items} offset={paged.offset} />
+ )}
+ </div>
+ <Pager
+ page={paged.page}
+ pageCount={paged.pageCount}
+ onPageChange={setPage}
+ total={filtered.length}
+ shown={paged.items.length}
+ pageSize={ITEMS_PER_PAGE}
+ noun="posts"
+ resultsId={RESULTS_ID}
/>
- <RedditPostTable posts={filtered} />
</>
)}
</div>
diff --git a/frontend/src/features/analytics/reddit/RedditPostsAll.tsx b/frontend/src/features/analytics/reddit/RedditPostsAll.tsx
index 9a3b2fa..0f2fdbe 100644
--- a/frontend/src/features/analytics/reddit/RedditPostsAll.tsx
+++ b/frontend/src/features/analytics/reddit/RedditPostsAll.tsx
@@ -1,71 +1,76 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import { useMemo } from 'react';
import { Link } from 'react-router-dom';
-import { RefreshCw, TrendingUp, MessageSquare, Award, MessagesSquare, Plus } from 'lucide-react';
+import { Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import PageHeader from '@/components/PageHeader';
import MetricBox from '@/components/MetricBox';
+import Num from '@/components/Num';
import SurfaceBox from '@/components/SurfaceBox';
+import Pager from '@/components/Pager';
+import RefreshButton from '@/components/RefreshButton';
+import DataFreshness from '@/components/DataFreshness';
+import ActiveFilters from '@/components/ActiveFilters';
+import NoResults from '@/components/NoResults';
+import FailedSourcesAlert from '@/components/FailedSourcesAlert';
import { EmptyState } from '@/components/StateViews';
+import { accountName } from '@/lib/accounts';
+import { pageSlice, resultCountLabel } from '@/lib/library';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { useAppContext } from '../../../context/AppContext';
import { api } from '../../../services/api';
import { fmtNum } from '../../../utils/formatters';
+import type { AppAccount } from '../../../utils/formatters';
+import { useLibrarySources } from '../useLibrarySources';
+import { useLibraryParams } from '../useLibraryParams';
import RedditPostFilters from './RedditPostFilters';
import RedditPostTable from './RedditPostTable';
-import { filterAndSortRedditPosts, subredditsOf } from './redditPostUtils';
-import type { RedditPostRow } from './redditPostUtils';
-import { cn } from '@/lib/utils';
+import { filterAndSortRedditPosts, mergeAccountPosts, redditSortOf, subredditsOf } from './redditPostUtils';
-export default function RedditPostsAll() {
- const { accounts, showToast } = useAppContext();
- const redditAccounts = useMemo(() => accounts.filter(a => a.platform === 'reddit'), [accounts]);
- const accountsById = useMemo(() => Object.fromEntries(redditAccounts.map(a => [a.id, a])), [redditAccounts]);
-
- const [posts, setPosts] = useState<RedditPostRow[]>([]);
- const [loading, setLoading] = useState(false);
- const [query, setQuery] = useState('');
- const [sort, setSort] = useState('score-desc');
- const [accountFilter, setAccountFilter] = useState('all');
- const [subFilter, setSubFilter] = useState('all');
-
- const loadPosts = useCallback(async () => {
- if (redditAccounts.length === 0) return;
- setLoading(true);
- try {
- const results = await Promise.allSettled(
- redditAccounts.map(acc => api.getRedditPosts(acc.id).then(data => ({ acc, posts: Array.isArray(data) ? data : [] }))),
- );
- const combined: RedditPostRow[] = [];
- results.forEach(r => {
- if (r.status === 'fulfilled') {
- r.value.posts.forEach(post => combined.push({
- ...post,
- accountId: r.value.acc.id,
- accountUsername: r.value.acc.username,
- accountIconUrl: r.value.acc.iconUrl,
- }));
- } else {
- showToast(`Couldn't load posts for one account. ${r.reason?.message || ''}`.trim(), 'error');
- }
- });
- setPosts(combined);
- } finally {
- setLoading(false);
- }
- }, [redditAccounts, showToast]);
+const ITEMS_PER_PAGE = 25;
+const RESULTS_ID = 'reddit-results';
+
+const DEFAULTS = { q: '', account: 'all', subreddit: 'all', sort: 'score-desc' };
- useEffect(() => { loadPosts(); }, [loadPosts]);
+const { redditPosts: Posts, karma: Karma, comments: Comments } = METRIC_ICONS;
+
+// the analytics read carries the posts and the time they were fetched, so the page can say how old they are
+function fetchAccountPosts(id: string, fresh: boolean) {
+ return api.getRedditAnalytics(id, fresh);
+}
+
+function nameOf(account: AppAccount): string {
+ return accountName(account);
+}
+
+export default function RedditPostsAll() {
+ const { accounts } = useAppContext();
+ const redditAccounts = useMemo(() => accounts.filter(account => account.platform === 'reddit'), [accounts]);
+ const accountsById = useMemo(() => Object.fromEntries(redditAccounts.map(account => [account.id, account])), [redditAccounts]);
+ const library = useLibrarySources(redditAccounts, fetchAccountPosts, nameOf, 'Reddit posts');
+ const posts = useMemo(() => mergeAccountPosts(library.sources, library.results), [library.sources, library.results]);
+ const { values, page, update, clear, setPage } = useLibraryParams(DEFAULTS);
+ const sort = redditSortOf(values.sort);
const subreddits = useMemo(() => subredditsOf(posts), [posts]);
const filtered = useMemo(
- () => filterAndSortRedditPosts(posts, { query, sort, subreddit: subFilter, accountId: accountFilter }),
- [posts, query, sort, subFilter, accountFilter],
+ () => filterAndSortRedditPosts(posts, { query: values.q, sort, subreddit: values.subreddit, accountId: values.account }),
+ [posts, values.q, sort, values.subreddit, values.account],
);
+ const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
const totals = useMemo(() => ({
- score: filtered.reduce((s, p) => s + p.score, 0),
- comments: filtered.reduce((s, p) => s + p.numComments, 0),
+ score: filtered.reduce((sum, post) => sum + post.score, 0),
+ comments: filtered.reduce((sum, post) => sum + post.numComments, 0),
}), [filtered]);
- const avg = (n: number) => filtered.length > 0 ? `${fmtNum(Math.round(n / filtered.length))} per post on average` : '';
+ const average = (total: number) => (filtered.length > 0 ? `${fmtNum(Math.round(total / filtered.length))} per post on average` : '');
+
+ const clearFilters = () => clear(['q', 'account', 'subreddit']);
+ const activeAccount = accountsById[values.account];
+ const activeFilters = [
+ values.q && { key: 'q', label: `"${values.q}"`, onRemove: () => update({ q: '' }) },
+ activeAccount && { key: 'account', label: `u/${activeAccount.username}`, onRemove: () => update({ account: 'all' }) },
+ values.subreddit !== 'all' && { key: 'subreddit', label: `r/${values.subreddit}`, onRemove: () => update({ subreddit: 'all' }) },
+ ].filter(Boolean) as { key: string; label: string; onRemove: () => void }[];
if (redditAccounts.length === 0) {
return (
@@ -73,29 +78,30 @@ export default function RedditPostsAll() {
<PageHeader title="Reddit posts" description="Posts from every connected Reddit account" />
<SurfaceBox>
<EmptyState
- icon={<MessagesSquare />}
+ icon={<Posts />}
title="No Reddit accounts yet"
description="Connect a Reddit account to see its posts, karma and comments here."
- action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add an account</Button>}
+ action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" aria-hidden="true" />Add account</Button>}
/>
</SurfaceBox>
</div>
);
}
+ const loading = library.initialLoading;
+ const accountWord = `account${redditAccounts.length === 1 ? '' : 's'}`;
+
return (
<div className="flex flex-col gap-6">
<PageHeader
title="Reddit posts"
- description={loading
- ? `Loading posts from ${redditAccounts.length} account${redditAccounts.length === 1 ? '' : 's'}`
- : `${filtered.length} of ${posts.length} posts across ${redditAccounts.length} account${redditAccounts.length === 1 ? '' : 's'}`}
- actions={
- <Button variant="outline" size="sm" onClick={loadPosts} disabled={loading}>
- <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />
- Refresh
- </Button>
+ description={
+ <span className="flex flex-col gap-1">
+ <span>{loading ? `Loading posts from ${redditAccounts.length} ${accountWord}` : `${posts.length} posts across ${redditAccounts.length} ${accountWord}`}</span>
+ {!loading && <DataFreshness fetchedAt={library.fetchedAt} qualifier={redditAccounts.length > 1 ? 'oldest account' : undefined} />}
+ </span>
}
+ actions={<RefreshButton refreshing={library.refreshing} onRefresh={library.refresh} disabled={loading} />}
/>
{loading ? (
@@ -108,20 +114,41 @@ export default function RedditPostsAll() {
</div>
) : (
<>
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
- <MetricBox icon={<TrendingUp />} label="Posts shown" value={fmtNum(filtered.length)} subtitle={`${posts.length} fetched in total`} />
- <MetricBox icon={<Award />} label="Karma" value={fmtNum(totals.score)} subtitle={avg(totals.score)} highlight />
- <MetricBox icon={<MessageSquare />} label="Comments" value={fmtNum(totals.comments)} subtitle={avg(totals.comments)} />
+ <FailedSourcesAlert failures={library.failures} total={redditAccounts.length} noun="accounts" onRetry={library.refresh} retrying={library.refreshing} />
+
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3" aria-busy={library.refreshing}>
+ <MetricBox icon={<Posts />} label="Posts" value={<Num value={filtered.length} />} period="Matching posts" subtitle={`${posts.length} loaded in total`} />
+ <MetricBox icon={<Karma />} label="Karma" value={<Num value={totals.score} />} period="Matching posts" subtitle={average(totals.score)} highlight />
+ <MetricBox icon={<Comments />} label="Comments" value={<Num value={totals.comments} />} period="Matching posts" subtitle={average(totals.comments)} />
</div>
<RedditPostFilters
- query={query} onQuery={setQuery}
- sort={sort} onSort={setSort}
- subreddit={subFilter} onSubreddit={setSubFilter} subreddits={subreddits}
- accountId={accountFilter} onAccount={setAccountFilter} accounts={redditAccounts}
+ query={values.q} onQuery={value => update({ q: value }, { replace: true })}
+ sort={sort} onSort={value => update({ sort: value })}
+ subreddit={values.subreddit} onSubreddit={value => update({ subreddit: value })} subreddits={subreddits}
+ accountId={values.account} onAccount={value => update({ account: value })} accounts={redditAccounts}
/>
- <RedditPostTable posts={filtered} showAccount={redditAccounts.length > 1} accountsById={accountsById} />
+ <ActiveFilters countLabel={resultCountLabel(filtered.length, posts.length, 'posts')} filters={activeFilters} onClearAll={clearFilters} />
+
+ <div id={RESULTS_ID} tabIndex={-1} className="outline-none" aria-busy={library.refreshing}>
+ {filtered.length === 0 ? (
+ <SurfaceBox><NoResults noun="posts" query={values.q} onClear={clearFilters} /></SurfaceBox>
+ ) : (
+ <RedditPostTable posts={paged.items} offset={paged.offset} showAccount={redditAccounts.length > 1} accountsById={accountsById} />
+ )}
+ </div>
+
+ <Pager
+ page={paged.page}
+ pageCount={paged.pageCount}
+ onPageChange={setPage}
+ total={filtered.length}
+ shown={paged.items.length}
+ pageSize={ITEMS_PER_PAGE}
+ noun="posts"
+ resultsId={RESULTS_ID}
+ />
</>
)}
</div>
diff --git a/frontend/src/features/analytics/reddit/RedditSubredditTable.tsx b/frontend/src/features/analytics/reddit/RedditSubredditTable.tsx
index 26c50da..1ff23a4 100644
--- a/frontend/src/features/analytics/reddit/RedditSubredditTable.tsx
+++ b/frontend/src/features/analytics/reddit/RedditSubredditTable.tsx
@@ -1,7 +1,7 @@
import { ExternalLink } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import SurfaceBox from '@/components/SurfaceBox';
-import { fmtNum } from '../../../utils/formatters';
+import Num from '@/components/Num';
import type { RedditSubredditStats } from '@shared/types/reddit.ts';
export interface RedditSubredditTableProps {
@@ -18,8 +18,8 @@ export default function RedditSubredditTable({ subreddits }: RedditSubredditTabl
<TableHead>Subreddit</TableHead>
<TableHead className="text-right">Posts</TableHead>
<TableHead className="text-right">Total karma</TableHead>
- <TableHead className="text-right">Average karma</TableHead>
- <TableHead className="text-right">Average comments</TableHead>
+ <TableHead className="hidden text-right sm:table-cell">Average karma</TableHead>
+ <TableHead className="hidden text-right md:table-cell">Average comments</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -27,15 +27,16 @@ export default function RedditSubredditTable({ subreddits }: RedditSubredditTabl
<TableRow key={sub.subreddit}>
<TableCell className="text-right font-mono text-caption text-ink-faint">{i + 1}</TableCell>
<TableCell>
- <a href={`https://reddit.com/r/${sub.subreddit}`} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-sm font-medium text-ink hover:underline">
+ <a href={`https://reddit.com/r/${sub.subreddit}`} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-sm font-medium text-ink underline-offset-4 hover:underline">
r/{sub.subreddit}
- <ExternalLink className="size-3 text-ink-faint" />
+ <ExternalLink className="size-3 text-ink-faint" aria-hidden="true" />
+ <span className="sr-only"> (opens in a new tab)</span>
</a>
</TableCell>
<TableCell className="text-right text-ink-muted">{sub.posts}</TableCell>
- <TableCell className="text-right font-semibold text-ink">{fmtNum(sub.totalScore)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(sub.avgScore)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(sub.avgComments)}</TableCell>
+ <TableCell className="text-right font-semibold text-ink"><Num value={sub.totalScore} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={sub.avgScore} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell"><Num value={sub.avgComments} /></TableCell>
</TableRow>
))}
</TableBody>
diff --git a/frontend/src/features/analytics/reddit/RedditTimingCharts.tsx b/frontend/src/features/analytics/reddit/RedditTimingCharts.tsx
index 63c756f..f89e02d 100644
--- a/frontend/src/features/analytics/reddit/RedditTimingCharts.tsx
+++ b/frontend/src/features/analytics/reddit/RedditTimingCharts.tsx
@@ -1,13 +1,14 @@
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip } from 'recharts';
-import type { TooltipValueType } from 'recharts';
import ChartPanel from '@/components/ChartPanel';
-import { SERIES, axisProps, axisTick, gridProps, tooltipCursor, tooltipStyle } from '@/lib/chart';
+import { PLATFORM_META } from '@/lib/accounts';
+import { axisProps, axisTick, gridProps, rankingSummary, tooltipCursor, tooltipStyle } from '@/lib/chart';
import { fmtNum, fmtNumFull } from '../../../utils/formatters';
+import type { NumberLike } from '../../../utils/formatters';
import type { RedditAnalytics } from '@shared/types/reddit.ts';
-function formatTimingTooltip(value: TooltipValueType | undefined, name: string | number | undefined) {
- return [fmtNumFull(value as number), name === 'avgScore' ? 'Average karma' : 'Posts'];
-}
+const KARMA = PLATFORM_META.reddit.series;
+
+const full = (value: unknown) => fmtNumFull(value as NumberLike);
function formatHour(hour: number) {
return `${hour}h`;
@@ -17,31 +18,70 @@ function bestLabel(prefix: string, value: string | undefined) {
return value ? `${prefix}: ${value}` : undefined;
}
+interface TimingPayload {
+ posts?: number;
+}
+
+// one unit per chart: the bars are average karma, and the post count behind each bar is in the tooltip and table
+function formatKarmaWithPosts(value: unknown, _name: unknown, item: { payload?: unknown }) {
+ const posts = (item.payload as TimingPayload | undefined)?.posts;
+ return [`${fmtNumFull(value as NumberLike)}${posts !== undefined ? ` (${posts} posts)` : ''}`, 'Average karma'];
+}
+
export interface RedditTimingChartsProps {
analytics: Partial<RedditAnalytics>;
}
export default function RedditTimingCharts({ analytics }: RedditTimingChartsProps) {
+ const byDay = analytics.postsByDayOfWeek || [];
+ const byHour = analytics.postsByHour || [];
return (
<div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
- <ChartPanel title="Posts by day of week" subheader={bestLabel('Best day', analytics.bestPostingDay)} height={220}>
- <BarChart data={analytics.postsByDayOfWeek} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
+ <ChartPanel
+ title="Average karma by day posted"
+ subheader={bestLabel('Best day', analytics.bestPostingDay)}
+ height={220}
+ summary={rankingSummary(byDay.map(day => ({ name: day.day, value: day.avgScore })), fmtNum, 'karma per post')}
+ table={{
+ caption: 'Average karma by day posted',
+ columns: [
+ { key: 'day', label: 'Day' },
+ { key: 'posts', label: 'Posts', numeric: true, format: full },
+ { key: 'avgScore', label: 'Average karma', numeric: true, format: full },
+ ],
+ rows: byDay,
+ }}
+ >
+ <BarChart data={byDay} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="shortDay" {...axisProps} />
<YAxis {...axisProps} tickFormatter={fmtNum} width={36} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={formatTimingTooltip} />
- <Bar dataKey="posts" fill={SERIES.neutral} radius={[3, 3, 0, 0]} />
- <Bar dataKey="avgScore" fill={SERIES.primary} radius={[3, 3, 0, 0]} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={formatKarmaWithPosts} />
+ <Bar dataKey="avgScore" name="Average karma" fill={KARMA} radius={[3, 3, 0, 0]} />
</BarChart>
</ChartPanel>
- <ChartPanel title="Average karma by hour" subheader={bestLabel('Best hour', analytics.bestPostingHour)} height={220}>
- <BarChart data={analytics.postsByHour} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
+ <ChartPanel
+ title="Average karma by hour posted"
+ subheader={bestLabel('Best hour', analytics.bestPostingHour)}
+ height={220}
+ summary={rankingSummary(byHour.map(hour => ({ name: `${hour.hour}:00`, value: hour.avgScore })), fmtNum, 'karma per post')}
+ table={{
+ caption: 'Average karma by hour posted',
+ columns: [
+ { key: 'hour', label: 'Hour', format: value => `${value}:00` },
+ { key: 'posts', label: 'Posts', numeric: true, format: full },
+ { key: 'avgScore', label: 'Average karma', numeric: true, format: full },
+ ],
+ rows: byHour,
+ }}
+ >
+ <BarChart data={byHour} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
<CartesianGrid {...gridProps} vertical={false} />
<XAxis dataKey="hour" tickFormatter={formatHour} tick={{ ...axisTick, fontSize: 10 }} axisLine={false} tickLine={false} interval={3} />
<YAxis {...axisProps} tickFormatter={fmtNum} width={36} />
- <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={formatTimingTooltip} />
- <Bar dataKey="avgScore" fill={SERIES.warm} radius={[3, 3, 0, 0]} />
+ <ReTooltip contentStyle={tooltipStyle} cursor={tooltipCursor} formatter={formatKarmaWithPosts} />
+ <Bar dataKey="avgScore" name="Average karma" fill={KARMA} radius={[3, 3, 0, 0]} />
</BarChart>
</ChartPanel>
</div>
diff --git a/frontend/src/features/analytics/reddit/RedditTopPostsTable.tsx b/frontend/src/features/analytics/reddit/RedditTopPostsTable.tsx
index 773da32..45a40e6 100644
--- a/frontend/src/features/analytics/reddit/RedditTopPostsTable.tsx
+++ b/frontend/src/features/analytics/reddit/RedditTopPostsTable.tsx
@@ -4,8 +4,9 @@ import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import SurfaceBox from '@/components/SurfaceBox';
import ColumnHint from '@/components/ColumnHint';
+import Num from '@/components/Num';
import { RankNumber } from '@/components/ListRow';
-import { fmtDate, fmtNum } from '../../../utils/formatters';
+import { fmtDate } from '../../../utils/formatters';
import type { RedditPost } from '@shared/types/reddit.ts';
export interface RedditTopPostsTableProps {
@@ -21,9 +22,9 @@ export default function RedditTopPostsTable({ posts }: RedditTopPostsTableProps)
<TableHead className="w-10 text-right">#</TableHead>
<TableHead>Post</TableHead>
<TableHead className="text-right">Karma</TableHead>
- <TableHead className="text-right">Comments</TableHead>
- <TableHead className="text-right"><ColumnHint label="Upvote rate" hint="Share of votes on the post that are upvotes. 96% means 96 of every 100 votes were up." /></TableHead>
- <TableHead className="text-right">Posted</TableHead>
+ <TableHead className="hidden text-right sm:table-cell">Comments</TableHead>
+ <TableHead className="hidden text-right md:table-cell"><ColumnHint label="Upvote rate" hint="Share of votes on the post that are upvotes. 96% means 96 of every 100 votes were up." /></TableHead>
+ <TableHead className="hidden text-right md:table-cell">Posted</TableHead>
<TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
</TableRow>
</TableHeader>
@@ -33,20 +34,20 @@ export default function RedditTopPostsTable({ posts }: RedditTopPostsTableProps)
<TableCell className="text-right"><RankNumber rank={i + 1} className="w-auto" /></TableCell>
<TableCell className="whitespace-normal">
<div className="max-w-sm">
- <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{post.title}</p>
+ <p className="line-clamp-2 text-sm font-medium leading-snug text-ink" title={post.title}>{post.title}</p>
<div className="mt-1 flex items-center gap-1.5">
<span className="text-caption text-ink-faint">{post.subredditPrefixed}</span>
{post.flair && <Badge variant="outline">{post.flair}</Badge>}
</div>
</div>
</TableCell>
- <TableCell className="text-right font-semibold text-ink">{fmtNum(post.score)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(post.numComments)}</TableCell>
- <TableCell className="text-right text-ink-muted">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{fmtDate(post.createdAt)}</TableCell>
+ <TableCell className="text-right font-semibold text-ink"><Num value={post.score} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={post.numComments} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>
+ <TableCell className="hidden text-right text-small text-ink-faint md:table-cell">{fmtDate(post.createdAt)}</TableCell>
<TableCell>
- <Button variant="ghost" size="icon-xs" render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label={`Open "${post.title}" on Reddit`} />}>
- <ExternalLink />
+ <Button variant="ghost" size="icon-xs" render={<a href={post.permalink} target="_blank" rel="noopener noreferrer" aria-label={`Open "${post.title}" on Reddit (opens in a new tab)`} />}>
+ <ExternalLink aria-hidden="true" />
</Button>
</TableCell>
</TableRow>
diff --git a/frontend/src/features/analytics/reddit/redditAnalyticsData.ts b/frontend/src/features/analytics/reddit/redditAnalyticsData.ts
index faeb285..e74ec9e 100644
--- a/frontend/src/features/analytics/reddit/redditAnalyticsData.ts
+++ b/frontend/src/features/analytics/reddit/redditAnalyticsData.ts
@@ -1,5 +1,5 @@
import { seriesAt } from '../../../lib/chart.ts';
-import { fmtNum, fmtNumFull } from '../../../utils/formatters.ts';
+import { fmtNum } from '../../../utils/formatters.ts';
import type { RedditAnalytics, RedditMediaType, RedditProfile } from '../../../../../shared/types/reddit.ts';
// the page falls back to the stored account until the live profile loads, and accounts can store createdAt as a number
@@ -13,7 +13,7 @@ export interface RedditMediaSlice {
export interface RedditKarmaItem {
label: string;
- value: string;
+ value: number;
sub: string;
lead?: boolean;
}
@@ -44,10 +44,10 @@ export function mediaTypeDataOf(distribution: Partial<Record<RedditMediaType, nu
export function karmaSummaryOf(profile: RedditProfileFields): RedditKarmaItem[] {
return [
- { label: 'Total karma', value: fmtNum(profile.totalKarma), sub: fmtNumFull(profile.totalKarma), lead: true },
- { label: 'Post karma', value: fmtNum(profile.postKarma), sub: 'From submitted posts' },
- { label: 'Comment karma', value: fmtNum(profile.commentKarma), sub: 'From comments' },
- { label: 'Awardee karma', value: fmtNum(profile.awardeeKarma ?? 0), sub: 'From awards received' },
+ { label: 'Total karma', value: profile.totalKarma ?? 0, sub: 'All time', lead: true },
+ { label: 'Post karma', value: profile.postKarma ?? 0, sub: 'From submitted posts' },
+ { label: 'Comment karma', value: profile.commentKarma ?? 0, sub: 'From comments' },
+ { label: 'Awardee karma', value: profile.awardeeKarma ?? 0, sub: 'From awards received' },
];
}
diff --git a/frontend/src/features/analytics/reddit/redditPostUtils.ts b/frontend/src/features/analytics/reddit/redditPostUtils.ts
index 7d9a002..3ce404d 100644
--- a/frontend/src/features/analytics/reddit/redditPostUtils.ts
+++ b/frontend/src/features/analytics/reddit/redditPostUtils.ts
@@ -1,5 +1,5 @@
-import { matchesText } from '@/lib/library';
-import type { RedditMediaType, RedditPost } from '@shared/types/reddit.ts';
+import { matchesText } from '../../../lib/library.ts';
+import type { RedditMediaType, RedditPost } from '../../../../../shared/types/reddit.ts';
// Filtering and sorting shared by the per-account and all-accounts Reddit posts pages.
@@ -50,3 +50,24 @@ export function filterAndSortRedditPosts<T extends RedditPostRow>(posts: T[], {
export function subredditsOf(posts: Pick<RedditPost, 'subreddit'>[]): string[] {
return [...new Set(posts.map(p => p.subreddit))].sort();
}
+
+// a sort read from the address falls back to most karma when it is not one of the options
+export function redditSortOf(value: string): string {
+ return REDDIT_SORT_OPTIONS.some(option => option.value === value) ? value : 'score-desc';
+}
+
+// tags each post with the account it was fetched for, skipping accounts whose request failed
+export function mergeAccountPosts<A extends { id: string; username?: string; iconUrl?: string }>(
+ accounts: readonly A[],
+ results: readonly PromiseSettledResult<{ posts?: RedditPost[] }>[],
+): RedditPostRow[] {
+ const combined: RedditPostRow[] = [];
+ results.forEach((result, index) => {
+ if (result.status !== 'fulfilled') return;
+ const account = accounts[index];
+ for (const post of result.value.posts || []) {
+ combined.push({ ...post, accountId: account.id, accountUsername: account.username, accountIconUrl: account.iconUrl });
+ }
+ });
+ return combined;
+}
diff --git a/frontend/src/features/analytics/reels/ReelsExplorer.tsx b/frontend/src/features/analytics/reels/ReelsExplorer.tsx
index 1492993..b63cac0 100644
--- a/frontend/src/features/analytics/reels/ReelsExplorer.tsx
+++ b/frontend/src/features/analytics/reels/ReelsExplorer.tsx
@@ -1,69 +1,79 @@
-import { useMemo, useState } from 'react';
+import { useMemo } from 'react';
import { Link } from 'react-router-dom';
-import { Plus, RefreshCw } from 'lucide-react';
+import { Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import PageHeader from '@/components/PageHeader';
import SurfaceBox from '@/components/SurfaceBox';
import Pager from '@/components/Pager';
+import RefreshButton from '@/components/RefreshButton';
+import DataFreshness from '@/components/DataFreshness';
+import ActiveFilters from '@/components/ActiveFilters';
+import NoResults from '@/components/NoResults';
+import FailedSourcesAlert from '@/components/FailedSourcesAlert';
import { EmptyState } from '@/components/StateViews';
import { InstagramIcon } from '@/components/brand/platform-icons';
-import { pageSlice } from '@/lib/library';
-import { cn } from '@/lib/utils';
+import { LIKE_TIERS, pageSlice, resultCountLabel } from '@/lib/library';
+import { IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';
+import type { InstagramContentType } from '@shared/types/instagram.ts';
import { useInstagramMedia } from './useInstagramMedia';
-import { filterAndSortMedia, reelsDescription, typeTotalsOf } from './reelsLibrary.ts';
-import type { MediaSortField } from './reelsLibrary.ts';
+import { useLibraryParams } from '../useLibraryParams';
+import { filterAndSortMedia, mediaSortOf, reelsDescription, typeTotalsOf } from './reelsLibrary.ts';
import ReelsMetrics from './ReelsMetrics';
import ReelsFilters from './ReelsFilters';
import ReelsGrid from './ReelsGrid';
const ITEMS_PER_PAGE = 24;
+const RESULTS_ID = 'instagram-results';
+
+const DEFAULTS = { q: '', account: 'all', type: 'all', likes: 'all', sort: 'viewCount' };
export default function ReelsExplorer() {
- const { igAccounts, media, loading, loadAllMedia } = useInstagramMedia();
- const [search, setSearch] = useState('');
- const [accountFilter, setAccountFilter] = useState('all');
- const [typeFilter, setTypeFilter] = useState('all');
- const [tier, setTier] = useState('all');
- const [sortField, setSortField] = useState<MediaSortField>('viewCount');
- const [page, setPage] = useState(1);
+ const { igAccounts, media, failures, fetchedAt, loading, refreshing, refresh } = useInstagramMedia();
+ const { values, page, update, clear, setPage } = useLibraryParams(DEFAULTS);
+ const sortField = mediaSortOf(values.sort);
const accountMedia = useMemo(
- () => accountFilter === 'all' ? media : media.filter(item => item.accountId === accountFilter),
- [media, accountFilter],
+ () => values.account === 'all' ? media : media.filter(item => item.accountId === values.account),
+ [media, values.account],
);
const typeTotals = useMemo(() => typeTotalsOf(accountMedia), [accountMedia]);
const filtered = useMemo(
- () => filterAndSortMedia(accountMedia, { typeFilter, search, tier, sortField }),
- [accountMedia, typeFilter, search, tier, sortField],
+ () => filterAndSortMedia(accountMedia, { typeFilter: values.type, search: values.q, tier: values.likes, sortField }),
+ [accountMedia, values.type, values.q, values.likes, sortField],
);
const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
- function resetPage<T>(setter: (value: T) => void) {
- return (value: T) => {
- setter(value);
- setPage(1);
- };
- }
- const filters = { search, accountFilter, typeFilter, tier, sortField };
+ const clearFilters = () => clear(['q', 'account', 'type', 'likes']);
+ const accountLabel = igAccounts.find(account => account.id === values.account);
+ const typeLabel = IG_CONTENT_TYPE_META[values.type as InstagramContentType]?.plural;
+ const likesLabel = LIKE_TIERS.find(tier => tier.value === values.likes)?.label;
+ const activeFilters = [
+ values.q && { key: 'q', label: `"${values.q}"`, onRemove: () => update({ q: '' }) },
+ accountLabel && { key: 'account', label: accountLabel.title || accountLabel.username || 'Account', onRemove: () => update({ account: 'all' }) },
+ typeLabel && { key: 'type', label: typeLabel, onRemove: () => update({ type: 'all' }) },
+ values.likes !== 'all' && likesLabel && { key: 'likes', label: likesLabel, onRemove: () => update({ likes: 'all' }) },
+ ].filter(Boolean) as { key: string; label: string; onRemove: () => void }[];
+
+ const filters = { search: values.q, accountFilter: values.account, typeFilter: values.type, tier: values.likes, sortField };
const handlers = {
- onSearchChange: resetPage(setSearch),
- onAccountChange: resetPage(setAccountFilter),
- onTierChange: resetPage(setTier),
- onSortChange: setSortField,
- onTypeChange: resetPage(setTypeFilter),
+ onSearchChange: (value: string) => update({ q: value }, { replace: true }),
+ onAccountChange: (value: string) => update({ account: value }),
+ onTierChange: (value: string) => update({ likes: value }),
+ onSortChange: (value: string) => update({ sort: value }),
+ onTypeChange: (value: string) => update({ type: value }),
};
const header = (
<PageHeader
title="Instagram content"
- description={reelsDescription(loading, media.length, igAccounts.length)}
- actions={
- <Button variant="outline" size="sm" onClick={loadAllMedia} disabled={loading}>
- <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />
- Refresh
- </Button>
+ description={
+ <span className="flex flex-col gap-1">
+ <span>{reelsDescription(loading, media.length, igAccounts.length)}</span>
+ {!loading && <DataFreshness fetchedAt={fetchedAt} qualifier={igAccounts.length > 1 ? 'oldest account' : undefined} />}
+ </span>
}
+ actions={<RefreshButton refreshing={refreshing} onRefresh={refresh} disabled={loading || igAccounts.length === 0} />}
/>
);
@@ -76,7 +86,7 @@ export default function ReelsExplorer() {
icon={<InstagramIcon />}
title="No Instagram accounts yet"
description="Connect a Business or Creator account to browse its reels, posts and videos."
- action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add an account</Button>}
+ action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" aria-hidden="true" />Add account</Button>}
/>
</SurfaceBox>
</div>
@@ -102,19 +112,34 @@ export default function ReelsExplorer() {
<div className="flex flex-col gap-6">
{header}
- <ReelsMetrics typeTotals={typeTotals} itemCount={accountMedia.length} />
+ <FailedSourcesAlert failures={failures} total={igAccounts.length} noun="accounts" onRetry={refresh} retrying={refreshing} />
+
+ <div aria-busy={refreshing}>
+ <ReelsMetrics typeTotals={typeTotals} itemCount={accountMedia.length} />
+ </div>
<ReelsFilters igAccounts={igAccounts} itemCount={accountMedia.length} typeTotals={typeTotals} filters={filters} handlers={handlers} />
- {filtered.length === 0 ? (
- <SurfaceBox>
- <EmptyState compact icon={<InstagramIcon />} title="No content matches" description="Clear the search or choose a different type or like range." />
- </SurfaceBox>
- ) : (
- <ReelsGrid items={paged.items} />
- )}
+ <ActiveFilters countLabel={resultCountLabel(filtered.length, media.length, 'items')} filters={activeFilters} onClearAll={clearFilters} />
+
+ <div id={RESULTS_ID} tabIndex={-1} className="outline-none" aria-busy={refreshing}>
+ {filtered.length === 0 ? (
+ <SurfaceBox><NoResults noun="posts" query={values.q} onClear={clearFilters} /></SurfaceBox>
+ ) : (
+ <ReelsGrid items={paged.items} />
+ )}
+ </div>
- <Pager page={paged.page} pageCount={paged.pageCount} onPageChange={setPage} total={filtered.length} shown={paged.items.length} noun="items" />
+ <Pager
+ page={paged.page}
+ pageCount={paged.pageCount}
+ onPageChange={setPage}
+ total={filtered.length}
+ shown={paged.items.length}
+ pageSize={ITEMS_PER_PAGE}
+ noun="items"
+ resultsId={RESULTS_ID}
+ />
</div>
);
}
diff --git a/frontend/src/features/analytics/reels/ReelsFilters.tsx b/frontend/src/features/analytics/reels/ReelsFilters.tsx
index 90c6b8c..eafc43e 100644
--- a/frontend/src/features/analytics/reels/ReelsFilters.tsx
+++ b/frontend/src/features/analytics/reels/ReelsFilters.tsx
@@ -1,28 +1,17 @@
-import { Clapperboard, Film, Image } from 'lucide-react';
-import type { LucideIcon } from 'lucide-react';
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import SearchField from '@/components/SearchField';
import FilterChips from '@/components/FilterChips';
+import SortSelect from '@/components/SortSelect';
import type { FilterChipOption } from '@/components/FilterChips';
import { LIKE_TIERS } from '@/lib/library';
+import { IG_TYPE_ICONS } from '@/lib/metricIcons';
import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';
import type { AppAccount } from '../../../utils/formatters';
import type { InstagramContentType } from '@shared/types/instagram.ts';
+import type { LucideIcon } from 'lucide-react';
+import { MEDIA_SORT_OPTIONS } from './reelsLibrary.ts';
import type { MediaSortField, MediaTypeTotals } from './reelsLibrary.ts';
-interface SelectOption<V extends string> {
- value: V;
- label: string;
-}
-
-interface OptionSelectProps<V extends string> {
- value: V;
- onChange: (value: V) => void;
- options: SelectOption<V>[];
- className?: string;
- label: string;
-}
-
export interface ReelsFilterValues {
search: string;
accountFilter: string;
@@ -35,7 +24,7 @@ export interface ReelsFilterHandlers {
onSearchChange: (value: string) => void;
onAccountChange: (value: string) => void;
onTierChange: (value: string) => void;
- onSortChange: (value: MediaSortField) => void;
+ onSortChange: (value: string) => void;
onTypeChange: (value: string) => void;
}
@@ -47,15 +36,7 @@ export interface ReelsFiltersProps {
handlers: ReelsFilterHandlers;
}
-const CONTENT_TYPE_ICONS: Record<InstagramContentType, LucideIcon> = { reel: Clapperboard, post: Image, video: Film };
-
-const SORT_OPTIONS: SelectOption<MediaSortField>[] = [
- { value: 'viewCount', label: 'Most viewed' },
- { value: 'likeCount', label: 'Most liked' },
- { value: 'commentsCount', label: 'Most comments' },
- { value: 'engagementRate', label: 'Best engagement' },
- { value: 'timestamp', label: 'Newest first' },
-];
+const CONTENT_TYPE_ICONS: Record<InstagramContentType, LucideIcon> = IG_TYPE_ICONS;
function typeChipsOf(itemCount: number, typeTotals: MediaTypeTotals): FilterChipOption[] {
return [
@@ -64,19 +45,7 @@ function typeChipsOf(itemCount: number, typeTotals: MediaTypeTotals): FilterChip
];
}
-function OptionSelect<V extends string>({ value, onChange, options, className, label }: OptionSelectProps<V>) {
- return (
- <Select value={value} onValueChange={onChange as (value: V | null) => void} items={options}>
- <SelectTrigger className={className} aria-label={label}><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {options.map(option => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
- );
-}
-
+// the same controls as the other libraries: search, account, sort, then chips for type and likes
export default function ReelsFilters({ igAccounts, itemCount, typeTotals, filters, handlers }: ReelsFiltersProps) {
return (
<div className="flex flex-col gap-3">
@@ -85,10 +54,10 @@ export default function ReelsFilters({ igAccounts, itemCount, typeTotals, filter
{igAccounts.length > 1 && (
<Select
value={filters.accountFilter}
- onValueChange={handlers.onAccountChange as (value: string | null) => void}
+ onValueChange={next => { if (next) handlers.onAccountChange(next as string); }}
items={[{ value: 'all', label: 'All accounts' }, ...igAccounts.map(account => ({ value: account.id, label: account.title || account.username }))]}
>
- <SelectTrigger className="w-44" aria-label="Account"><SelectValue /></SelectTrigger>
+ <SelectTrigger className="h-(--control-h-lg) w-48" aria-label="Account"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="all">All accounts</SelectItem>
@@ -97,10 +66,10 @@ export default function ReelsFilters({ igAccounts, itemCount, typeTotals, filter
</SelectContent>
</Select>
)}
- <OptionSelect value={filters.tier} onChange={handlers.onTierChange} options={LIKE_TIERS} className="w-36" label="Likes" />
- <OptionSelect value={filters.sortField} onChange={handlers.onSortChange} options={SORT_OPTIONS} className="w-44" label="Sort" />
+ <SortSelect options={MEDIA_SORT_OPTIONS} value={filters.sortField} onChange={handlers.onSortChange} />
</div>
<FilterChips label="Content type" options={typeChipsOf(itemCount, typeTotals)} value={filters.typeFilter} onChange={handlers.onTypeChange} />
+ <FilterChips label="Likes" options={LIKE_TIERS} value={filters.tier} onChange={handlers.onTierChange} />
</div>
);
}
diff --git a/frontend/src/features/analytics/reels/ReelsGrid.tsx b/frontend/src/features/analytics/reels/ReelsGrid.tsx
index b1eeb5e..9d3d12a 100644
--- a/frontend/src/features/analytics/reels/ReelsGrid.tsx
+++ b/frontend/src/features/analytics/reels/ReelsGrid.tsx
@@ -1,34 +1,39 @@
-import { Eye, Heart, MessageCircle } from 'lucide-react';
import MediaCard, { MediaChip } from '@/components/MediaCard';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { fmtNum, timeAgo } from '../../../utils/formatters';
import { fmtIGViews, igContentTypeMeta, igThumbnail } from '../../../utils/instagramContent';
import type { LibraryMedia } from './reelsLibrary.ts';
+const { views: Views, instagramLikes: Likes, comments: Comments } = METRIC_ICONS;
+
export interface ReelsGridProps {
items: LibraryMedia[];
}
export default function ReelsGrid({ items }: ReelsGridProps) {
return (
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5">
+ <ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5">
{items.map((item, i) => (
- <MediaCard
- key={`${item.id}-${i}`}
- aspect="square"
- href={item.permalink}
- image={igThumbnail(item)}
- title={item.caption}
- topLeft={<MediaChip>{igContentTypeMeta(item.contentType).label}</MediaChip>}
- meta={
- <>
- <span className="flex items-center gap-1"><Eye />{fmtIGViews(item.viewCount)}</span>
- <span className="flex items-center gap-1"><Heart />{fmtNum(item.likeCount)}</span>
- <span className="flex items-center gap-1"><MessageCircle />{fmtNum(item.commentsCount)}</span>
- <span className="ml-auto">{timeAgo(item.timestamp)}</span>
- </>
- }
- />
+ <li key={`${item.id}-${i}`} className="flex">
+ <MediaCard
+ className="w-full"
+ aspect="square"
+ href={item.permalink}
+ image={igThumbnail(item)}
+ title={item.caption}
+ topLeft={<MediaChip>{igContentTypeMeta(item.contentType).label}</MediaChip>}
+ meta={
+ <>
+ <span className="flex items-center gap-1"><Views aria-hidden="true" />{fmtIGViews(item.viewCount)}<span className="sr-only"> views</span></span>
+ <span className="flex items-center gap-1"><Likes aria-hidden="true" />{fmtNum(item.likeCount)}<span className="sr-only"> likes</span></span>
+ <span className="flex items-center gap-1"><Comments aria-hidden="true" />{fmtNum(item.commentsCount)}<span className="sr-only"> comments</span></span>
+ <span className="ml-auto" title={item.timestamp ? new Date(item.timestamp).toLocaleString('en-US') : undefined}>{timeAgo(item.timestamp)}</span>
+ <span className="sr-only"> (opens on Instagram in a new tab)</span>
+ </>
+ }
+ />
+ </li>
))}
- </div>
+ </ul>
);
}
diff --git a/frontend/src/features/analytics/reels/ReelsMetrics.tsx b/frontend/src/features/analytics/reels/ReelsMetrics.tsx
index 75c9872..007a243 100644
--- a/frontend/src/features/analytics/reels/ReelsMetrics.tsx
+++ b/frontend/src/features/analytics/reels/ReelsMetrics.tsx
@@ -1,7 +1,6 @@
-import { Clapperboard, Eye, Film, Image } from 'lucide-react';
-import type { LucideIcon } from 'lucide-react';
import MetricBox from '@/components/MetricBox';
-import { fmtNum } from '../../../utils/formatters';
+import Num from '@/components/Num';
+import { IG_TYPE_ICONS, METRIC_ICONS } from '@/lib/metricIcons';
import { IG_CONTENT_TYPES, IG_CONTENT_TYPE_META } from '../../../utils/instagramContent';
import type { InstagramContentType } from '@shared/types/instagram.ts';
import { typeViewsSubtitle, viewTotalsOf } from './reelsLibrary.ts';
@@ -17,16 +16,17 @@ export interface ReelsMetricsProps {
itemCount: number;
}
-const CONTENT_TYPE_ICONS: Record<InstagramContentType, LucideIcon> = { reel: Clapperboard, post: Image, video: Film };
+const Views = METRIC_ICONS.views;
function TypeMetric({ type, typeTotal }: TypeMetricProps) {
- const Icon = CONTENT_TYPE_ICONS[type];
+ const Icon = IG_TYPE_ICONS[type];
return (
<MetricBox
small
icon={<Icon />}
label={IG_CONTENT_TYPE_META[type].plural}
- value={fmtNum(typeTotal.count)}
+ value={<Num value={typeTotal.count} />}
+ period="Loaded posts"
subtitle={typeViewsSubtitle(typeTotal)}
/>
);
@@ -36,7 +36,7 @@ export default function ReelsMetrics({ typeTotals, itemCount }: ReelsMetricsProp
const { totalViews, viewsReported } = viewTotalsOf(typeTotals);
return (
<div className="grid grid-cols-2 gap-3 xl:grid-cols-4">
- <MetricBox small icon={<Eye />} label="Views" value={fmtNum(totalViews)} subtitle={`${viewsReported} of ${itemCount} items report views`} highlight />
+ <MetricBox small icon={<Views />} label="Views" value={<Num value={totalViews} />} period="Loaded posts" subtitle={`${viewsReported} of ${itemCount} items report views`} highlight />
{IG_CONTENT_TYPES.map(type => <TypeMetric key={type} type={type} typeTotal={typeTotals[type]} />)}
</div>
);
diff --git a/frontend/src/features/analytics/reels/reelsLibrary.ts b/frontend/src/features/analytics/reels/reelsLibrary.ts
index 420bfef..e3d66bc 100644
--- a/frontend/src/features/analytics/reels/reelsLibrary.ts
+++ b/frontend/src/features/analytics/reels/reelsLibrary.ts
@@ -6,6 +6,7 @@ import type { InstagramMedia } from '../../../../../shared/types/instagram.ts';
// the fields mergeAccountMedia reads from each fulfilled media request
export interface AccountMediaResult {
media?: InstagramMedia[];
+ fetchedAt?: string;
}
export interface MediaAccount {
@@ -38,6 +39,19 @@ export interface MediaQuery {
sortField: MediaSortField;
}
+export const MEDIA_SORT_OPTIONS: { value: MediaSortField; label: string }[] = [
+ { value: 'viewCount', label: 'Most viewed' },
+ { value: 'likeCount', label: 'Most liked' },
+ { value: 'commentsCount', label: 'Most comments' },
+ { value: 'engagementRate', label: 'Best engagement rate' },
+ { value: 'timestamp', label: 'Newest first' },
+];
+
+// a sort read from the address falls back to most viewed when it is not one of the options
+export function mediaSortOf(value: string): MediaSortField {
+ return MEDIA_SORT_OPTIONS.find(option => option.value === value)?.value ?? 'viewCount';
+}
+
function engagementRateOf(item: Pick<InstagramMedia, 'viewCount' | 'likeCount' | 'commentsCount'>): number | null {
if (item.viewCount! > 0) return ((item.likeCount || 0) + (item.commentsCount || 0)) / item.viewCount! * 100;
return null;
diff --git a/frontend/src/features/analytics/reels/useInstagramMedia.ts b/frontend/src/features/analytics/reels/useInstagramMedia.ts
index 52c6f4f..fc03868 100644
--- a/frontend/src/features/analytics/reels/useInstagramMedia.ts
+++ b/frontend/src/features/analytics/reels/useInstagramMedia.ts
@@ -1,29 +1,28 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useMemo } from 'react';
import { useAppContext } from '../../../context/AppContext';
import { api } from '../../../services/api';
+import { accountName } from '@/lib/accounts';
+import type { AppAccount } from '../../../utils/formatters';
+import { useLibrarySources } from '../useLibrarySources';
import { mergeAccountMedia } from './reelsLibrary.ts';
-import type { LibraryMedia } from './reelsLibrary.ts';
-// one failed Instagram account does not hide media from the rest
+function nameOf(account: AppAccount): string {
+ return accountName(account) || 'Unknown account';
+}
+
+// one failed Instagram account does not hide media from the rest, and the page names it
export function useInstagramMedia() {
- const { accounts, showToast } = useAppContext();
+ const { accounts } = useAppContext();
const igAccounts = useMemo(() => accounts.filter(account => account.platform === 'instagram'), [accounts]);
- const [media, setMedia] = useState<LibraryMedia[]>([]);
- const [loading, setLoading] = useState(true);
-
- const loadAllMedia = useCallback(async () => {
- setLoading(true);
- try {
- const results = await Promise.allSettled(igAccounts.map(account => api.getIGMedia(account.id)));
- setMedia(mergeAccountMedia(igAccounts, results));
- } catch (err) {
- showToast(`Couldn't load Instagram content. ${(err as Error).message}`, 'error');
- } finally {
- setLoading(false);
- }
- }, [igAccounts, showToast]);
-
- useEffect(() => { loadAllMedia(); }, [loadAllMedia]);
-
- return { igAccounts, media, loading, loadAllMedia };
+ const library = useLibrarySources(igAccounts, api.getIGMedia, nameOf, 'Instagram content');
+ const media = useMemo(() => mergeAccountMedia(library.sources, library.results), [library.sources, library.results]);
+ return {
+ igAccounts,
+ media,
+ failures: library.failures,
+ fetchedAt: library.fetchedAt,
+ loading: library.initialLoading,
+ refreshing: library.refreshing,
+ refresh: library.refresh,
+ };
}
diff --git a/frontend/src/features/analytics/shorts/ShortsExplorer.tsx b/frontend/src/features/analytics/shorts/ShortsExplorer.tsx
index 33a1846..ccbe369 100644
--- a/frontend/src/features/analytics/shorts/ShortsExplorer.tsx
+++ b/frontend/src/features/analytics/shorts/ShortsExplorer.tsx
@@ -1,64 +1,66 @@
-import React, { useMemo, useState } from 'react';
+import { useMemo } from 'react';
import { Link } from 'react-router-dom';
-import { RefreshCw, Scissors, Plus } from 'lucide-react';
+import { Scissors, Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import PageHeader from '@/components/PageHeader';
+import MetricBox from '@/components/MetricBox';
+import Num from '@/components/Num';
import SurfaceBox from '@/components/SurfaceBox';
import Pager from '@/components/Pager';
+import RefreshButton from '@/components/RefreshButton';
+import DataFreshness from '@/components/DataFreshness';
+import ActiveFilters from '@/components/ActiveFilters';
+import NoResults from '@/components/NoResults';
+import FailedSourcesAlert from '@/components/FailedSourcesAlert';
import { EmptyState } from '@/components/StateViews';
-import { pageSlice } from '@/lib/library';
+import { VIEW_TIERS, pageSlice, resultCountLabel } from '@/lib/library';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { useChannelVideos } from '../videos/useChannelVideos';
-import { cn } from '@/lib/utils';
+import { useLibraryParams } from '../useLibraryParams';
+import { videoStatsOf } from '../videos/videoLibrary.ts';
import ShortsFilters from './ShortsFilters';
import ShortsGrid from './ShortsGrid';
-import { shortsOf, filterAndSortShorts, shortsDescription } from './shortsLibrary.ts';
-import type { ShortsSortField, ShortsSortOption } from './shortsLibrary.ts';
+import { SHORTS_SORT_OPTIONS, filterAndSortShorts, shortsDescription, shortsOf, shortsSortOf } from './shortsLibrary.ts';
const ITEMS_PER_PAGE = 24;
+const RESULTS_ID = 'shorts-results';
-const SORT_OPTIONS: ShortsSortOption[] = [
- { value: 'viewCount', label: 'Most viewed' },
- { value: 'likeCount', label: 'Most liked' },
- { value: 'commentCount', label: 'Most comments' },
- { value: 'engagementRate', label: 'Best engagement' },
- { value: 'publishedAt', label: 'Newest first' },
-];
+const DEFAULTS = { q: '', channel: 'all', views: 'all', sort: 'viewCount' };
+
+const { shorts: ShortsIcon, views: Views, likes: Likes, comments: Comments, averageViews: AverageViews } = METRIC_ICONS;
export default function ShortsExplorer() {
- const { videos, channels, loading, reload } = useChannelVideos();
- const [search, setSearch] = useState('');
- const [channelFilter, setChannelFilter] = useState('all');
- const [tier, setTier] = useState('all');
- const [sortField, setSortField] = useState<ShortsSortField>('viewCount');
- const [page, setPage] = useState(1);
+ const { videos, channels, channelCount, failures, fetchedAt, loading, refreshing, refresh } = useChannelVideos();
+ const { values, page, update, clear, setPage } = useLibraryParams(DEFAULTS);
const shorts = useMemo(() => shortsOf(videos), [videos]);
-
const filtered = useMemo(
- () => filterAndSortShorts(shorts, { channelFilter, search, tier, sortField }),
- [shorts, channelFilter, search, tier, sortField],
+ () => filterAndSortShorts(shorts, { channelFilter: values.channel, search: values.q, tier: values.views, sortField: shortsSortOf(values.sort) }),
+ [shorts, values.channel, values.q, values.views, values.sort],
);
-
const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
+ const stats = useMemo(() => videoStatsOf(filtered), [filtered]);
- function resetPage<T>(setter: (value: T) => void) {
- return (value: T) => {
- setter(value);
- setPage(1);
- };
- }
+ const clearFilters = () => clear(['q', 'channel', 'views']);
+ const channelTitle = channels.find(channel => channel.id === values.channel)?.title;
+ const tierLabel = VIEW_TIERS.find(tier => tier.value === values.views)?.label;
+ const activeFilters = [
+ values.q && { key: 'q', label: `"${values.q}"`, onRemove: () => update({ q: '' }) },
+ values.channel !== 'all' && channelTitle && { key: 'channel', label: channelTitle, onRemove: () => update({ channel: 'all' }) },
+ values.views !== 'all' && tierLabel && { key: 'views', label: tierLabel, onRemove: () => update({ views: 'all' }) },
+ ].filter(Boolean) as { key: string; label: string; onRemove: () => void }[];
const header = (
<PageHeader
title="Shorts"
- description={shortsDescription(loading, shorts.length, channels.length)}
- actions={
- <Button variant="outline" size="sm" onClick={reload} disabled={loading}>
- <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />
- Refresh
- </Button>
+ description={
+ <span className="flex flex-col gap-1">
+ <span>{shortsDescription(loading, shorts.length, channels.length)}</span>
+ {!loading && <DataFreshness fetchedAt={fetchedAt} qualifier={channels.length > 1 ? 'oldest channel' : undefined} />}
+ </span>
}
+ actions={<RefreshButton refreshing={refreshing} onRefresh={refresh} disabled={loading || channelCount === 0} />}
/>
);
@@ -74,7 +76,7 @@ export default function ShortsExplorer() {
);
}
- if (channels.length === 0) {
+ if (channelCount === 0) {
return (
<div className="flex flex-col gap-6">
{header}
@@ -83,7 +85,7 @@ export default function ShortsExplorer() {
icon={<Scissors />}
title="No YouTube channels yet"
description="Add a channel and its Shorts appear here, ranked by views."
- action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add a channel</Button>}
+ action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" aria-hidden="true" />Add a channel</Button>}
/>
</SurfaceBox>
</div>
@@ -94,33 +96,60 @@ export default function ShortsExplorer() {
<div className="flex flex-col gap-6">
{header}
+ <FailedSourcesAlert failures={failures} total={channelCount} noun="channels" onRetry={refresh} retrying={refreshing} />
+
+ {shorts.length > 0 && (
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-5" aria-busy={refreshing}>
+ <MetricBox small icon={<ShortsIcon />} label="Shorts" value={<Num value={stats.total} />} period="Matching Shorts" />
+ <MetricBox small icon={<Views />} label="Views" value={<Num value={stats.views} />} period="Matching Shorts" highlight />
+ <MetricBox small icon={<Likes />} label="Likes" value={<Num value={stats.likes} />} period="Matching Shorts" />
+ <MetricBox small icon={<Comments />} label="Comments" value={<Num value={stats.comments} />} period="Matching Shorts" />
+ <MetricBox small icon={<AverageViews />} label="Average views" value={<Num value={stats.avgViews} />} period="Per matching Short" />
+ </div>
+ )}
+
<ShortsFilters
channels={channels}
- sortOptions={SORT_OPTIONS}
- search={search}
- onSearchChange={resetPage(setSearch)}
- channelFilter={channelFilter}
- onChannelChange={resetPage(setChannelFilter)}
- sortField={sortField}
- onSortChange={setSortField}
- tier={tier}
- onTierChange={resetPage(setTier)}
+ sortOptions={SHORTS_SORT_OPTIONS}
+ search={values.q}
+ onSearchChange={value => update({ q: value }, { replace: true })}
+ channelFilter={values.channel}
+ onChannelChange={value => update({ channel: value })}
+ sortField={shortsSortOf(values.sort)}
+ onSortChange={value => update({ sort: value })}
+ tier={values.views}
+ onTierChange={value => update({ views: value })}
/>
- {filtered.length === 0 ? (
- <SurfaceBox>
- <EmptyState
- compact
- icon={<Scissors />}
- title={shorts.length === 0 ? 'No Shorts yet' : 'No Shorts match'}
- description={shorts.length === 0 ? 'Videos of 60 seconds or less appear here once your channels publish them.' : 'Clear the search or choose a different view range.'}
- />
- </SurfaceBox>
- ) : (
- <ShortsGrid shorts={paged.items} />
- )}
+ <ActiveFilters countLabel={resultCountLabel(filtered.length, shorts.length, 'Shorts')} filters={activeFilters} onClearAll={clearFilters} />
+
+ <div id={RESULTS_ID} tabIndex={-1} className="outline-none" aria-busy={refreshing}>
+ {shorts.length === 0 ? (
+ <SurfaceBox>
+ <EmptyState
+ compact
+ icon={<Scissors />}
+ title="No Shorts yet"
+ description="Videos of 60 seconds or less appear here once your channels publish them."
+ />
+ </SurfaceBox>
+ ) : filtered.length === 0 ? (
+ <SurfaceBox><NoResults noun="Shorts" query={values.q} onClear={clearFilters} /></SurfaceBox>
+ ) : (
+ <ShortsGrid shorts={paged.items} />
+ )}
+ </div>
- <Pager page={paged.page} pageCount={paged.pageCount} onPageChange={setPage} total={filtered.length} shown={paged.items.length} noun="Shorts" />
+ <Pager
+ page={paged.page}
+ pageCount={paged.pageCount}
+ onPageChange={setPage}
+ total={filtered.length}
+ shown={paged.items.length}
+ pageSize={ITEMS_PER_PAGE}
+ noun="Shorts"
+ resultsId={RESULTS_ID}
+ />
</div>
);
}
diff --git a/frontend/src/features/analytics/shorts/ShortsFilters.tsx b/frontend/src/features/analytics/shorts/ShortsFilters.tsx
index 330345a..6cf4520 100644
--- a/frontend/src/features/analytics/shorts/ShortsFilters.tsx
+++ b/frontend/src/features/analytics/shorts/ShortsFilters.tsx
@@ -1,8 +1,8 @@
-import React from 'react';
-import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import SearchField from '@/components/SearchField';
import FilterChips from '@/components/FilterChips';
+import SortSelect from '@/components/SortSelect';
import { VIEW_TIERS } from '@/lib/library';
+import { ChannelSelect } from '../videos/VideoFilters';
import type { LibraryChannel } from '../videos/videoLibrary.ts';
import type { ShortsSortField, ShortsSortOption } from './shortsLibrary.ts';
@@ -14,7 +14,7 @@ export interface ShortsFiltersProps {
channelFilter: string;
onChannelChange: (value: string) => void;
sortField: ShortsSortField;
- onSortChange: (value: ShortsSortField) => void;
+ onSortChange: (value: string) => void;
tier: string;
onTierChange: (value: string) => void;
}
@@ -26,29 +26,8 @@ export default function ShortsFilters({
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<SearchField value={search} onChange={onSearchChange} placeholder="Search Shorts" className="min-w-56 flex-1" />
- {channels.length > 1 && (
- <Select
- value={channelFilter}
- onValueChange={onChannelChange as (value: string | null) => void}
- items={[{ value: 'all', label: 'All channels' }, ...channels.map(channel => ({ value: channel.id, label: channel.title }))]}
- >
- <SelectTrigger className="w-48" aria-label="Channel"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- <SelectItem value="all">All channels</SelectItem>
- {channels.map(channel => <SelectItem key={channel.id} value={channel.id}>{channel.title}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
- )}
- <Select value={sortField} onValueChange={onSortChange as (value: ShortsSortField | null) => void} items={sortOptions}>
- <SelectTrigger className="w-44" aria-label="Sort"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {sortOptions.map(option => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
+ {channels.length > 1 && <ChannelSelect channels={channels} value={channelFilter} onChange={onChannelChange} />}
+ <SortSelect options={sortOptions} value={sortField} onChange={onSortChange} />
</div>
<FilterChips label="Views" options={VIEW_TIERS} value={tier} onChange={onTierChange} />
</div>
diff --git a/frontend/src/features/analytics/shorts/ShortsGrid.tsx b/frontend/src/features/analytics/shorts/ShortsGrid.tsx
index 4144270..e658469 100644
--- a/frontend/src/features/analytics/shorts/ShortsGrid.tsx
+++ b/frontend/src/features/analytics/shorts/ShortsGrid.tsx
@@ -1,33 +1,37 @@
-import React from 'react';
-import { Eye, MessageSquare, ThumbsUp } from 'lucide-react';
import MediaCard, { MediaChip } from '@/components/MediaCard';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { fmtNum, fmtDuration, fmtCount } from '../../../utils/formatters';
import type { LibraryVideo } from '../videos/videoLibrary.ts';
+const { views: Views, likes: Likes, comments: Comments } = METRIC_ICONS;
+
export interface ShortsGridProps {
shorts: LibraryVideo[];
}
export default function ShortsGrid({ shorts }: ShortsGridProps) {
return (
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6">
+ <ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6">
{shorts.map((video, i) => (
- <MediaCard
- key={`${video.videoId}-${i}`}
- aspect="vertical"
- href={`https://www.youtube.com/shorts/${video.videoId}`}
- image={video.thumbnail}
- title={video.title}
- topRight={<MediaChip><Eye />{fmtNum(video.viewCount)}</MediaChip>}
- bottomRight={<MediaChip>{fmtDuration(video.durationSeconds)}</MediaChip>}
- meta={
- <>
- <span className="flex items-center gap-1"><ThumbsUp />{fmtCount(video.likeCount)}</span>
- <span className="flex items-center gap-1"><MessageSquare />{fmtCount(video.commentCount)}</span>
- </>
- }
- />
+ <li key={`${video.videoId}-${i}`} className="flex">
+ <MediaCard
+ className="w-full"
+ aspect="vertical"
+ href={`https://www.youtube.com/shorts/${video.videoId}`}
+ image={video.thumbnail}
+ title={video.title}
+ topRight={<MediaChip><Views aria-hidden="true" />{fmtNum(video.viewCount)}<span className="sr-only"> views</span></MediaChip>}
+ bottomRight={<MediaChip><span className="sr-only">Length </span>{fmtDuration(video.durationSeconds)}</MediaChip>}
+ meta={
+ <>
+ <span className="flex items-center gap-1"><Likes aria-hidden="true" />{fmtCount(video.likeCount)}<span className="sr-only"> likes</span></span>
+ <span className="flex items-center gap-1"><Comments aria-hidden="true" />{fmtCount(video.commentCount)}<span className="sr-only"> comments</span></span>
+ <span className="sr-only"> (opens on YouTube in a new tab)</span>
+ </>
+ }
+ />
+ </li>
))}
- </div>
+ </ul>
);
}
diff --git a/frontend/src/features/analytics/shorts/shortsLibrary.ts b/frontend/src/features/analytics/shorts/shortsLibrary.ts
index 29a107e..95c7911 100644
--- a/frontend/src/features/analytics/shorts/shortsLibrary.ts
+++ b/frontend/src/features/analytics/shorts/shortsLibrary.ts
@@ -18,6 +18,19 @@ export interface ShortsQuery {
const SHORT_MAX_SECONDS = 60;
+export const SHORTS_SORT_OPTIONS: ShortsSortOption[] = [
+ { value: 'viewCount', label: 'Most viewed' },
+ { value: 'likeCount', label: 'Most liked' },
+ { value: 'commentCount', label: 'Most comments' },
+ { value: 'engagementRate', label: 'Best engagement rate' },
+ { value: 'publishedAt', label: 'Newest first' },
+];
+
+// a sort read from the address falls back to most viewed when it is not one of the options
+export function shortsSortOf(value: string): ShortsSortField {
+ return SHORTS_SORT_OPTIONS.find(option => option.value === value)?.value ?? 'viewCount';
+}
+
export function shortsOf(videos: LibraryVideo[]): LibraryVideo[] {
return videos.filter(video => video.durationSeconds > 0 && video.durationSeconds <= SHORT_MAX_SECONDS);
}
diff --git a/frontend/src/features/analytics/tracked/CategoryRedditSection.tsx b/frontend/src/features/analytics/tracked/CategoryRedditSection.tsx
index 649ccdd..c40bf52 100644
--- a/frontend/src/features/analytics/tracked/CategoryRedditSection.tsx
+++ b/frontend/src/features/analytics/tracked/CategoryRedditSection.tsx
@@ -1,16 +1,18 @@
import { useMemo } from 'react';
-import { Eye, MessageSquare, MessagesSquare, TrendingUp } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import MetricBox from '@/components/MetricBox';
import SurfaceBox from '@/components/SurfaceBox';
import SectionHeader from '@/components/SectionHeader';
-import MetricAreaChart from '@/components/MetricAreaChart';
+import RankingBarChart from '@/components/RankingBarChart';
+import RelativeTime from '@/components/RelativeTime';
+import Num from '@/components/Num';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import ImageLightbox from '@/components/ImageLightbox';
import ColumnHint from '@/components/ColumnHint';
import { RankNumber } from '@/components/ListRow';
import { PlatformIcon } from '@/components/platform';
import { PLATFORM_META } from '@/lib/accounts';
-import { fmtDate, fmtNum } from '../../../utils/formatters';
+import { fmtNum } from '../../../utils/formatters';
import { hasTrackedViews, trackedViews } from '../../../utils/trackedContent';
import NumberCell from './NumberCell';
import OpenLink from './OpenLink';
@@ -31,7 +33,7 @@ function PostRow({ item, rank }: PostRowProps) {
<div className="flex items-start gap-3">
{item.imageUrl && <ImageLightbox src={item.imageUrl} alt={item.title || 'Reddit post'} className="mt-0.5" />}
<div className="min-w-0">
- <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{item.title || item.url}</p>
+ <p className="line-clamp-2 text-sm font-medium leading-snug text-ink" title={item.title || item.url}>{item.title || item.url}</p>
<div className="mt-1 flex flex-wrap items-center gap-1.5">
{item.subredditPrefixed && <span className="text-caption text-ink-faint">{item.subredditPrefixed}</span>}
{item.label && <span className="text-caption text-ink-faint italic">{item.label}</span>}
@@ -40,10 +42,10 @@ function PostRow({ item, rank }: PostRowProps) {
</div>
</TableCell>
<NumberCell value={item.score} />
- <TableCell className="text-right text-ink-muted">{hasTrackedViews(item) ? fmtNum(trackedViews(item)) : '-'}</TableCell>
- <TableCell className="text-right text-ink-muted">{item.upvoteRatio != null && (item.score ?? 0) >= 10 ? `${Math.round(item.upvoteRatio * 100)}%` : '-'}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(item.numComments ?? 0)}</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{item.lastFetchedAt ? fmtDate(item.lastFetchedAt) : '-'}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell">{hasTrackedViews(item) ? <Num value={trackedViews(item)} /> : '-'}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell">{item.upvoteRatio != null && (item.score ?? 0) >= 10 ? `${Math.round(item.upvoteRatio * 100)}%` : '-'}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={item.numComments ?? 0} /></TableCell>
+ <TableCell className="hidden text-right text-small text-ink-faint md:table-cell">{item.lastFetchedAt ? <RelativeTime date={item.lastFetchedAt} /> : '-'}</TableCell>
<TableCell><OpenLink href={item.permalink || item.url} label={`Open "${item.title || 'post'}" on Reddit`} /></TableCell>
</TableRow>
);
@@ -66,27 +68,27 @@ export default function CategoryRedditSection({ items, stats }: CategoryRedditSe
actions={<span className="text-small text-ink-faint">{items.length} post{items.length !== 1 ? 's' : ''}</span>}
/>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <MetricBox small icon={<MessagesSquare />} label="Post karma" value={fmtNum(stats.karma)} subtitle={`${fmtNum(stats.avgKarma)} per post on average`} />
- <MetricBox small icon={<Eye />} label="Post views" value={views.value} subtitle={views.subtitle} />
- <MetricBox small icon={<MessageSquare />} label="Post comments" value={fmtNum(stats.comments)} subtitle={`${fmtNum(stats.avgComments)} per post on average`} />
- <MetricBox small icon={<TrendingUp />} label="Average upvote ratio" value={upvoteRatioLabel(stats.avgRatio)} subtitle="Upvotes as a share of all votes" />
+ <MetricBox small icon={<METRIC_ICONS.karma />} label="Post karma" value={<Num value={stats.karma} />} subtitle={`${fmtNum(stats.avgKarma)} per post on average`} />
+ <MetricBox small icon={<METRIC_ICONS.views />} label="Post views" value={views.value} subtitle={views.subtitle} />
+ <MetricBox small icon={<METRIC_ICONS.comments />} label="Post comments" value={<Num value={stats.comments} />} subtitle={`${fmtNum(stats.avgComments)} per post on average`} />
+ <MetricBox small icon={<METRIC_ICONS.upvoteRate />} label="Average upvote ratio" value={upvoteRatioLabel(stats.avgRatio)} subtitle="Upvotes as a share of all votes" />
</div>
{chartData.length > 1 && (
- <SurfaceBox title="Post karma" subheader={`Top ${chartData.length} posts in this category ranked by karma`}>
- <MetricAreaChart data={chartData} dataKey="karma" label="Karma" color={PLATFORM_META.reddit.series} height={260} />
+ <SurfaceBox title="Post karma" headingLevel="h3" subheader={`Top ${chartData.length} posts in this category ranked by karma`}>
+ <RankingBarChart rows={chartData.map(point => ({ name: point.name, value: Number(point.karma) || 0 }))} label="Karma" title="Karma by post" color={PLATFORM_META.reddit.series} />
</SurfaceBox>
)}
- <SurfaceBox content={false} className="overflow-hidden">
+ <SurfaceBox title="All posts in this category" headingLevel="h3" content={false} className="overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-10 text-right">#</TableHead>
<TableHead>Post</TableHead>
<TableHead className="w-28 text-right">Karma</TableHead>
- <TableHead className="w-24 text-right">Views</TableHead>
- <TableHead className="w-32 text-right"><ColumnHint label="Upvote rate" hint="Share of votes on a Reddit post that are upvotes. Shows a dash for YouTube videos and for posts under 10 karma, where the ratio is not meaningful." /></TableHead>
- <TableHead className="w-24 text-right">Comments</TableHead>
- <TableHead className="w-28 text-right">Fetched</TableHead>
+ <TableHead className="hidden w-24 text-right sm:table-cell">Views</TableHead>
+ <TableHead className="hidden w-32 text-right md:table-cell"><ColumnHint label="Upvote rate" hint="Share of votes on a Reddit post that are upvotes. Shows a dash for YouTube videos and for posts under 10 karma, where the ratio is not meaningful." /></TableHead>
+ <TableHead className="hidden w-24 text-right sm:table-cell">Comments</TableHead>
+ <TableHead className="hidden w-28 text-right md:table-cell">Fetched</TableHead>
<TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
</TableRow>
</TableHeader>
diff --git a/frontend/src/features/analytics/tracked/CategoryYouTubeSection.tsx b/frontend/src/features/analytics/tracked/CategoryYouTubeSection.tsx
index 63beb2d..e9d5470 100644
--- a/frontend/src/features/analytics/tracked/CategoryYouTubeSection.tsx
+++ b/frontend/src/features/analytics/tracked/CategoryYouTubeSection.tsx
@@ -1,15 +1,18 @@
import { useMemo } from 'react';
-import { CirclePlay, Eye, MessageSquare, ThumbsUp, TrendingUp } from 'lucide-react';
+import { CirclePlay } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import MetricBox from '@/components/MetricBox';
import SurfaceBox from '@/components/SurfaceBox';
import SectionHeader from '@/components/SectionHeader';
-import MetricAreaChart from '@/components/MetricAreaChart';
+import RankingBarChart from '@/components/RankingBarChart';
+import RelativeTime from '@/components/RelativeTime';
+import Num from '@/components/Num';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { RankNumber } from '@/components/ListRow';
import { PlatformIcon } from '@/components/platform';
import { PLATFORM_META } from '@/lib/accounts';
-import { fmtDate, fmtNum } from '../../../utils/formatters';
+import { fmtNum } from '../../../utils/formatters';
import NumberCell from './NumberCell';
import OpenLink from './OpenLink';
import { chartDataOf, sortedByViews } from './trackedCategoryStats.ts';
@@ -30,10 +33,10 @@ function VideoRow({ item, rank }: VideoRowProps) {
{item.thumbnail ? (
<img src={item.thumbnail} alt="" loading="lazy" className="mt-0.5 h-10 w-16 shrink-0 rounded-sm object-cover" />
) : (
- <span className="mt-0.5 flex h-10 w-16 shrink-0 items-center justify-center rounded-sm bg-surface-sunken text-ink-faint"><CirclePlay className="size-4" /></span>
+ <span className="mt-0.5 flex h-10 w-16 shrink-0 items-center justify-center rounded-sm bg-surface-sunken text-ink-faint"><CirclePlay className="size-4" aria-hidden="true" /></span>
)}
<div className="min-w-0">
- <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{item.title || item.url}</p>
+ <p className="line-clamp-2 text-sm font-medium leading-snug text-ink" title={item.title || item.url}>{item.title || item.url}</p>
<div className="mt-1 flex flex-wrap items-center gap-1.5">
{item.channelTitle && <span className="text-caption text-ink-faint">{item.channelTitle}</span>}
{item.isShort && <Badge variant="outline">Short</Badge>}
@@ -43,9 +46,9 @@ function VideoRow({ item, rank }: VideoRowProps) {
</div>
</TableCell>
<NumberCell value={item.viewCount} />
- <TableCell className="text-right text-ink-muted">{fmtNum(item.likeCount ?? 0)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtNum(item.commentCount ?? 0)}</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{item.lastFetchedAt ? fmtDate(item.lastFetchedAt) : '-'}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={item.likeCount ?? 0} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell"><Num value={item.commentCount ?? 0} /></TableCell>
+ <TableCell className="hidden text-right text-small text-ink-faint md:table-cell">{item.lastFetchedAt ? <RelativeTime date={item.lastFetchedAt} /> : '-'}</TableCell>
<TableCell><OpenLink href={item.url} label={`Open "${item.title || 'video'}" on YouTube`} /></TableCell>
</TableRow>
);
@@ -67,26 +70,26 @@ export default function CategoryYouTubeSection({ items, stats }: CategoryYouTube
actions={<span className="text-small text-ink-faint">{items.length} video{items.length !== 1 ? 's' : ''}</span>}
/>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <MetricBox small icon={<Eye />} label="Video views" value={fmtNum(stats.views)} subtitle={`${fmtNum(stats.avgViews)} per video on average`} />
- <MetricBox small icon={<ThumbsUp />} label="Video likes" value={fmtNum(stats.likes)} subtitle={`${fmtNum(stats.avgLikes)} per video on average`} />
- <MetricBox small icon={<MessageSquare />} label="Video comments" value={fmtNum(stats.comments)} subtitle={`${fmtNum(stats.avgComments)} per video on average`} />
- <MetricBox small icon={<TrendingUp />} label="Likes per view" value={`${stats.likeRatio}%`} subtitle="Likes as a share of views" />
+ <MetricBox small icon={<METRIC_ICONS.views />} label="Video views" value={<Num value={stats.views} />} subtitle={`${fmtNum(stats.avgViews)} per video on average`} />
+ <MetricBox small icon={<METRIC_ICONS.likes />} label="Video likes" value={<Num value={stats.likes} />} subtitle={`${fmtNum(stats.avgLikes)} per video on average`} />
+ <MetricBox small icon={<METRIC_ICONS.comments />} label="Video comments" value={<Num value={stats.comments} />} subtitle={`${fmtNum(stats.avgComments)} per video on average`} />
+ <MetricBox small icon={<METRIC_ICONS.rate />} label="Likes per view" value={`${stats.likeRatio}%`} subtitle="Likes as a share of views" />
</div>
{chartData.length > 1 && (
- <SurfaceBox title="Video views" subheader={`Top ${chartData.length} videos in this category ranked by views`}>
- <MetricAreaChart data={chartData} dataKey="views" label="Views" color={PLATFORM_META.youtube.series} height={260} />
+ <SurfaceBox title="Video views" headingLevel="h3" subheader={`Top ${chartData.length} videos in this category ranked by views`}>
+ <RankingBarChart rows={chartData.map(point => ({ name: point.name, value: Number(point.views) || 0 }))} label="Views" title="Views by video" color={PLATFORM_META.youtube.series} />
</SurfaceBox>
)}
- <SurfaceBox content={false} className="overflow-hidden">
+ <SurfaceBox title="All videos in this category" headingLevel="h3" content={false} className="overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-10 text-right">#</TableHead>
<TableHead>Video</TableHead>
<TableHead className="w-32 text-right">Views</TableHead>
- <TableHead className="w-24 text-right">Likes</TableHead>
- <TableHead className="w-24 text-right">Comments</TableHead>
- <TableHead className="w-28 text-right">Fetched</TableHead>
+ <TableHead className="hidden w-24 text-right sm:table-cell">Likes</TableHead>
+ <TableHead className="hidden w-24 text-right sm:table-cell">Comments</TableHead>
+ <TableHead className="hidden w-28 text-right md:table-cell">Fetched</TableHead>
<TableHead className="w-10"><span className="sr-only">Open</span></TableHead>
</TableRow>
</TableHeader>
diff --git a/frontend/src/features/analytics/tracked/NumberCell.tsx b/frontend/src/features/analytics/tracked/NumberCell.tsx
index 8733456..6192750 100644
--- a/frontend/src/features/analytics/tracked/NumberCell.tsx
+++ b/frontend/src/features/analytics/tracked/NumberCell.tsx
@@ -1,20 +1,11 @@
import { TableCell } from '@/components/ui/table';
-import { fmtNum, fmtNumFull } from '../../../utils/formatters';
-
-// fmtNum abbreviates only at 1000 and above, so the full value is redundant below that
-function showsFullValue(value: number | null | undefined): boolean {
- return Math.abs(Number(value) || 0) >= 1000;
-}
+import Num from '@/components/Num';
export interface NumberCellProps {
value: number | null | undefined;
+ className?: string;
}
-export default function NumberCell({ value }: NumberCellProps) {
- return (
- <TableCell className="text-right">
- <p className="font-semibold text-ink">{fmtNum(value ?? 0)}</p>
- {showsFullValue(value) && <p className="text-caption text-ink-faint">{fmtNumFull(value)}</p>}
- </TableCell>
- );
+export default function NumberCell({ value, className = 'text-right font-semibold text-ink' }: NumberCellProps) {
+ return <TableCell className={className}><Num value={value ?? 0} /></TableCell>;
}
diff --git a/frontend/src/features/analytics/tracked/OpenLink.tsx b/frontend/src/features/analytics/tracked/OpenLink.tsx
index c8bd45e..098fe58 100644
--- a/frontend/src/features/analytics/tracked/OpenLink.tsx
+++ b/frontend/src/features/analytics/tracked/OpenLink.tsx
@@ -8,8 +8,8 @@ export interface OpenLinkProps {
export default function OpenLink({ href, label }: OpenLinkProps) {
return (
- <Button variant="ghost" size="icon-xs" render={<a href={href} target="_blank" rel="noopener noreferrer" aria-label={label} />}>
- <ExternalLink />
+ <Button variant="ghost" size="icon-xs" render={<a href={href} target="_blank" rel="noopener noreferrer" aria-label={`${label} (opens in a new tab)`} />}>
+ <ExternalLink aria-hidden="true" />
</Button>
);
}
diff --git a/frontend/src/features/analytics/tracked/TrackedCategory.tsx b/frontend/src/features/analytics/tracked/TrackedCategory.tsx
index 9d8bb19..a05581f 100644
--- a/frontend/src/features/analytics/tracked/TrackedCategory.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedCategory.tsx
@@ -1,14 +1,14 @@
-import { useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
-import { Eye, MessageSquare, MessagesSquare, Tag } from 'lucide-react';
import { Button } from '@/components/ui/button';
import PageHeader from '@/components/PageHeader';
import MetricBox from '@/components/MetricBox';
+import Num from '@/components/Num';
import SurfaceBox from '@/components/SurfaceBox';
-import { EmptyState, PageSkeleton } from '@/components/StateViews';
-import { useAppContext } from '../../../context/AppContext';
+import { EmptyState, ErrorState, PageSkeleton } from '@/components/StateViews';
+import { METRIC_ICONS } from '@/lib/metricIcons';
+import { useDocumentTitle } from '@/hooks/use-document-title';
import { api } from '../../../services/api';
-import { fmtNum } from '../../../utils/formatters';
import { isRedditItem } from '../../../utils/trackedContent';
import CategoryRedditSection from './CategoryRedditSection';
import CategoryYouTubeSection from './CategoryYouTubeSection';
@@ -19,20 +19,31 @@ import type { TrackedContentItem } from '@shared/types/domain.ts';
const BACK_LINK = { to: '/tracked-content', label: 'Tracked content' };
+const { tracked: Items, views: Views, karma: Karma, comments: Comments, category: Category } = METRIC_ICONS;
+
export default function TrackedCategory() {
const { name } = useParams();
- const { showToast } = useAppContext();
const categoryName = decodeURIComponent(name || '');
+ useDocumentTitle(categoryName ? `${categoryName} category` : null);
const [items, setItems] = useState<TrackedContentItem[]>([]);
const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const data = await api.getTrackedContent();
+ setItems((Array.isArray(data) ? data : []).filter(item => item.category === categoryName));
+ setError(null);
+ } catch (err) {
+ setError(`Couldn't load this category. ${(err as Error).message}`);
+ } finally {
+ setLoading(false);
+ }
+ }, [categoryName]);
- useEffect(() => {
- api.getTrackedContent()
- .then(data => setItems((Array.isArray(data) ? data : []).filter(item => item.category === categoryName)))
- .catch(err => showToast(`Couldn't load this category. ${err.message}`, 'error'))
- .finally(() => setLoading(false));
- }, [categoryName, showToast]);
+ useEffect(() => { load(); }, [load]);
const ytItems = useMemo(() => items.filter(item => item.contentType === 'youtube'), [items]);
const rdItems = useMemo(() => items.filter(isRedditItem), [items]);
@@ -41,13 +52,22 @@ export default function TrackedCategory() {
if (loading) return <PageSkeleton metrics={4} />;
+ if (error) {
+ return (
+ <div className="flex flex-col gap-6">
+ <PageHeader back={BACK_LINK} eyebrow="Category" title={categoryName} />
+ <SurfaceBox><ErrorState title="This category could not load" description={error} onRetry={load} /></SurfaceBox>
+ </div>
+ );
+ }
+
if (items.length === 0) {
return (
<div className="flex flex-col gap-6">
<PageHeader back={BACK_LINK} eyebrow="Category" title={categoryName} description="No items in this category" />
<SurfaceBox>
<EmptyState
- icon={<Tag />}
+ icon={<Category />}
title={`Nothing tracked in ${categoryName}`}
description="Assign this category to a Reddit post or YouTube video in Tracked content and its analytics appear here."
action={<Button size="sm" render={<Link to="/tracked-content" />}>Open tracked content</Button>}
@@ -71,10 +91,10 @@ export default function TrackedCategory() {
/>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <MetricBox icon={<Tag />} label="Items" value={items.length} subtitle={itemsSubtitle(ytStats, rdStats)} />
- <MetricBox icon={<Eye />} label="Views" value={views.value} subtitle={views.subtitle} highlight />
- <MetricBox icon={<MessagesSquare />} label="Reddit karma" value={karma.value} subtitle={karma.subtitle} />
- <MetricBox icon={<MessageSquare />} label="Comments" value={fmtNum(ytStats.comments + rdStats.comments)} subtitle={commentsSubtitle(ytStats, rdStats)} />
+ <MetricBox icon={<Items />} label="Items" value={items.length} subtitle={itemsSubtitle(ytStats, rdStats)} />
+ <MetricBox icon={<Views />} label="Views" value={views.value} subtitle={views.subtitle} highlight />
+ <MetricBox icon={<Karma />} label="Reddit karma" value={karma.value} subtitle={karma.subtitle} />
+ <MetricBox icon={<Comments />} label="Comments" value={<Num value={ytStats.comments + rdStats.comments} />} subtitle={commentsSubtitle(ytStats, rdStats)} />
</div>
{ytItems.length > 0 && <CategoryYouTubeSection items={ytItems} stats={ytStats} />}
diff --git a/frontend/src/features/analytics/tracked/TrackedContent.tsx b/frontend/src/features/analytics/tracked/TrackedContent.tsx
index 6683315..75990e6 100644
--- a/frontend/src/features/analytics/tracked/TrackedContent.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedContent.tsx
@@ -3,8 +3,10 @@ import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import PageHeader from '@/components/PageHeader';
import SurfaceBox from '@/components/SurfaceBox';
-import ConfirmDialog from '@/components/ConfirmDialog';
-import { EmptyState } from '@/components/StateViews';
+import ActiveFilters from '@/components/ActiveFilters';
+import NoResults from '@/components/NoResults';
+import { EmptyState, ErrorState } from '@/components/StateViews';
+import { resultCountLabel } from '@/lib/library';
import { useAppContext } from '../../../context/AppContext';
import { useCloudinaryConfig } from '../../../hooks/use-cloudinary-config';
import AddTrackedDialog from './AddTrackedDialog';
@@ -13,6 +15,7 @@ import EditTrackedDialog from './EditTrackedDialog';
import TrackedFilters from './TrackedFilters';
import TrackedMetrics from './TrackedMetrics';
import TrackedTable from './TrackedTable';
+import { typeChipsOf } from './trackedList.ts';
import { useAddTracked } from './useAddTracked';
import { useBulkCategory } from './useBulkCategory';
import { useTrackedDelete } from './useTrackedDelete';
@@ -20,12 +23,8 @@ import { useTrackedEditor } from './useTrackedEditor';
import { useTrackedFilters } from './useTrackedFilters';
import { useTrackedItems } from './useTrackedItems';
import { useTrackedSelection } from './useTrackedSelection';
-import type { TrackedContentItem } from '@shared/types/domain.ts';
-function deleteDescription(item: TrackedContentItem | null): string {
- if (!item) return '';
- return `"${item.title || item.label || item.url}" and its saved views, image and category are removed from Twiligent. The original post or video is not affected.`;
-}
+const RESULTS_ID = 'tracked-results';
export default function TrackedContent() {
const { accounts, showToast } = useAppContext();
@@ -39,17 +38,26 @@ export default function TrackedContent() {
const removal = useTrackedDelete({ setItems, dropSelection: selection.drop, showToast });
const add = useAddTracked({ redditAccounts, setItems, showToast });
const editor = useTrackedEditor({ cloudConfig, replaceItem, showToast });
+ const isEmpty = !tracked.loading && !tracked.error && tracked.items.length === 0;
+
+ const typeLabel = typeChipsOf(filters.stats).find(chip => chip.value === filters.typeFilter && chip.value !== 'all')?.label;
+ const activeFilters = [
+ filters.query && { key: 'q', label: `"${filters.query}"`, onRemove: () => filters.setQuery('') },
+ typeLabel && { key: 'type', label: typeLabel, onRemove: () => filters.setTypeFilter('all') },
+ filters.categoryFilter !== 'all' && { key: 'category', label: filters.categoryFilter, onRemove: () => filters.setCategoryFilter('all') },
+ ].filter(Boolean) as { key: string; label: string; onRemove: () => void }[];
+ // the empty state carries the one primary action, so the header does not repeat it
const header = (
<PageHeader
title="Tracked content"
description="Reddit posts and YouTube videos you follow, with karma, likes and comments."
- actions={
+ actions={!isEmpty && (
<Button onClick={() => add.setOpen(true)}>
- <Plus data-icon="inline-start" />
+ <Plus data-icon="inline-start" aria-hidden="true" />
Track content
</Button>
- }
+ )}
/>
);
@@ -66,49 +74,55 @@ export default function TrackedContent() {
);
}
+ if (tracked.error) {
+ return (
+ <div className="flex flex-col gap-6">
+ {header}
+ <SurfaceBox>
+ <ErrorState title="Tracked content could not load" description={tracked.error} onRetry={tracked.retry} />
+ </SurfaceBox>
+ </div>
+ );
+ }
+
return (
<div className="flex flex-col gap-6">
{header}
- <TrackedMetrics stats={filters.stats} />
-
- {tracked.items.length === 0 ? (
+ {isEmpty ? (
<SurfaceBox>
<EmptyState
icon={<Bookmark />}
title="Nothing tracked yet"
description="Paste a Reddit post or YouTube video link to follow its karma, likes and comments."
- action={<Button onClick={() => add.setOpen(true)}><Plus data-icon="inline-start" />Track your first item</Button>}
+ action={<Button onClick={() => add.setOpen(true)}><Plus data-icon="inline-start" aria-hidden="true" />Track content</Button>}
/>
</SurfaceBox>
) : (
<>
+ <TrackedMetrics stats={filters.stats} />
<TrackedFilters filters={filters} />
+ <ActiveFilters countLabel={resultCountLabel(filters.filtered.length, tracked.items.length, 'items')} filters={activeFilters} onClearAll={filters.clearFilters} />
{selection.someSelected && <BulkCategoryBar selectedCount={selection.selected.size} bulk={bulk} onClear={selection.clear} />}
- <TrackedTable
- filtered={filters.filtered}
- selection={selection}
- refreshingIds={tracked.refreshingIds}
- onRefresh={tracked.handleRefresh}
- onEdit={editor.openEdit}
- onDelete={removal.setDeleteItem}
- />
+ <div id={RESULTS_ID} tabIndex={-1} className="outline-none">
+ {filters.filtered.length === 0 ? (
+ <SurfaceBox><NoResults noun="items" query={filters.query} onClear={filters.clearFilters} /></SurfaceBox>
+ ) : (
+ <TrackedTable
+ filtered={filters.filtered}
+ selection={selection}
+ refreshingIds={tracked.refreshingIds}
+ onRefresh={tracked.handleRefresh}
+ onEdit={editor.openEdit}
+ onDelete={removal.remove}
+ />
+ )}
+ </div>
</>
)}
<AddTrackedDialog add={add} redditAccounts={redditAccounts} categories={filters.categories} />
<EditTrackedDialog editor={editor} categories={filters.categories} />
-
- <ConfirmDialog
- open={Boolean(removal.deleteItem)}
- onOpenChange={open => { if (!open) removal.setDeleteItem(null); }}
- title="Stop tracking this content?"
- description={deleteDescription(removal.deleteItem)}
- confirmLabel="Stop tracking"
- onConfirm={removal.handleDelete}
- busy={removal.deleting}
- hold
- />
</div>
);
}
diff --git a/frontend/src/features/analytics/tracked/TrackedFilters.tsx b/frontend/src/features/analytics/tracked/TrackedFilters.tsx
index 81e99bf..03b1c2e 100644
--- a/frontend/src/features/analytics/tracked/TrackedFilters.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedFilters.tsx
@@ -1,6 +1,7 @@
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import SearchField from '@/components/SearchField';
import FilterChips from '@/components/FilterChips';
+import SortSelect from '@/components/SortSelect';
import { SORT_OPTIONS, typeChipsOf } from './trackedList.ts';
import type { TrackedFilters as TrackedFiltersState } from './useTrackedFilters';
@@ -17,10 +18,10 @@ export default function TrackedFilters({ filters }: TrackedFiltersProps) {
{categories.length > 0 && (
<Select
value={filters.categoryFilter}
- onValueChange={filters.setCategoryFilter as (value: string | null) => void}
+ onValueChange={next => { if (next) filters.setCategoryFilter(next as string); }}
items={[{ value: 'all', label: 'All categories' }, ...categories.map(category => ({ value: category, label: category }))]}
>
- <SelectTrigger className="w-44" aria-label="Category"><SelectValue /></SelectTrigger>
+ <SelectTrigger className="h-(--control-h-lg) w-48" aria-label="Category"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="all">All categories</SelectItem>
@@ -29,14 +30,7 @@ export default function TrackedFilters({ filters }: TrackedFiltersProps) {
</SelectContent>
</Select>
)}
- <Select value={filters.sort} onValueChange={filters.setSort as (value: string | null) => void} items={SORT_OPTIONS}>
- <SelectTrigger className="w-48" aria-label="Sort"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {SORT_OPTIONS.map(option => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}
- </SelectGroup>
- </SelectContent>
- </Select>
+ <SortSelect options={SORT_OPTIONS} value={filters.sort} onChange={filters.setSort} />
</div>
<FilterChips label="Content type" options={typeChipsOf(filters.stats)} value={filters.typeFilter} onChange={filters.setTypeFilter} />
</div>
diff --git a/frontend/src/features/analytics/tracked/TrackedMetrics.tsx b/frontend/src/features/analytics/tracked/TrackedMetrics.tsx
index ff9fdd3..ba31127 100644
--- a/frontend/src/features/analytics/tracked/TrackedMetrics.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedMetrics.tsx
@@ -1,8 +1,10 @@
-import { BookmarkCheck, CirclePlay, MessagesSquare, Tag } from 'lucide-react';
import MetricBox from '@/components/MetricBox';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { countLabel, pluralize } from './trackedList.ts';
import type { TrackedStats } from './trackedList.ts';
+const { tracked: Tracked, category: Category, videos: Videos, redditPosts: Posts } = METRIC_ICONS;
+
function categoriesSubtitle(count: number): string {
if (count === 0) return 'None assigned yet';
return countLabel(count, 'group');
@@ -20,10 +22,10 @@ export interface TrackedMetricsProps {
export default function TrackedMetrics({ stats }: TrackedMetricsProps) {
return (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
- <MetricBox icon={<BookmarkCheck />} label="Tracked items" value={stats.total} subtitle="Across all categories" highlight />
- <MetricBox icon={<Tag />} label="Categories" value={stats.categories} subtitle={categoriesSubtitle(stats.categories)} />
- <MetricBox icon={<CirclePlay />} label="YouTube" value={stats.youtube} subtitle={trackedSubtitle(stats.youtube, 'No videos tracked', 'Video')} />
- <MetricBox icon={<MessagesSquare />} label="Reddit" value={stats.reddit} subtitle={trackedSubtitle(stats.reddit, 'No posts tracked', 'Post')} />
+ <MetricBox icon={<Tracked />} label="Tracked items" value={stats.total} subtitle="Across all categories" highlight />
+ <MetricBox icon={<Category />} label="Categories" value={stats.categories} subtitle={categoriesSubtitle(stats.categories)} />
+ <MetricBox icon={<Videos />} label="YouTube" value={stats.youtube} subtitle={trackedSubtitle(stats.youtube, 'No videos tracked', 'Video')} />
+ <MetricBox icon={<Posts />} label="Reddit" value={stats.reddit} subtitle={trackedSubtitle(stats.reddit, 'No posts tracked', 'Post')} />
</div>
);
}
diff --git a/frontend/src/features/analytics/tracked/TrackedRow.tsx b/frontend/src/features/analytics/tracked/TrackedRow.tsx
index 03cfdb3..a3389b2 100644
--- a/frontend/src/features/analytics/tracked/TrackedRow.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedRow.tsx
@@ -1,33 +1,36 @@
-import { ExternalLink, Eye, Pencil, RefreshCw, Trash2 } from 'lucide-react';
+import { ExternalLink, Pencil, RefreshCw, Trash2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { TableCell, TableRow } from '@/components/ui/table';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { PlatformBadge } from '@/components/platform';
+import Num from '@/components/Num';
+import RelativeTime from '@/components/RelativeTime';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { cn } from '@/lib/utils';
-import { fmtDate, fmtNum } from '../../../utils/formatters';
import { hasTrackedViews, trackedViews } from '../../../utils/trackedContent';
import RowAction from '@/components/RowAction';
import TrackedThumbnail from './TrackedThumbnail';
import type { TrackedContentItem } from '@shared/types/domain.ts';
+const Views = METRIC_ICONS.views;
+
interface ViewsCellProps {
item: TrackedContentItem;
+ title: string;
isYT: boolean;
onEdit: (item: TrackedContentItem) => void;
}
-function ViewsCell({ item, isYT, onEdit }: ViewsCellProps) {
- if (hasTrackedViews(item)) return <span className="text-ink">{fmtNum(trackedViews(item))}</span>;
+// the reason views are missing is part of the button's name, so it reaches touch and screen reader users too
+function ViewsCell({ item, title, isYT, onEdit }: ViewsCellProps) {
+ if (hasTrackedViews(item)) return <span className="text-ink"><Num value={trackedViews(item)} /></span>;
if (isYT) return <span className="text-ink-faint">-</span>;
return (
- <Tooltip>
- <TooltipTrigger render={<Button variant="ghost" size="xs" onClick={() => onEdit(item)} />}>
- <Eye />Add
- </TooltipTrigger>
- <TooltipContent>Reddit does not report views. Enter them by hand.</TooltipContent>
- </Tooltip>
+ <Button variant="ghost" size="xs" onClick={() => onEdit(item)} title="Reddit does not report views. Enter them by hand.">
+ <Views aria-hidden="true" />Add
+ <span className="sr-only"> views for {title}. Reddit does not report views, so they are entered by hand.</span>
+ </Button>
);
}
@@ -51,40 +54,43 @@ export default function TrackedRow({ item, isSelected, isRefreshing, onToggle, o
<TableCell>
<Checkbox checked={isSelected} onCheckedChange={() => onToggle(item.id)} aria-label={`Select ${title}`} />
</TableCell>
- <TableCell className="whitespace-normal">
- <div className="flex max-w-sm items-start gap-3">
+ <TableCell className="sticky left-0 z-[1] bg-surface-raised whitespace-normal">
+ <div className="flex max-w-56 items-start gap-3 sm:max-w-sm">
<TrackedThumbnail item={item} title={title} isYT={isYT} />
<div className="min-w-0">
- <p className="line-clamp-2 text-sm font-medium leading-snug text-ink">{title}</p>
+ <p className="line-clamp-2 text-sm font-medium leading-snug text-ink" title={title}>{title}</p>
<div className="mt-1 flex flex-wrap items-center gap-1.5">
<PlatformBadge platform={item.contentType || 'reddit'} className="h-5" />
<span className="text-caption text-ink-faint">{isYT ? item.channelTitle : item.subredditPrefixed}</span>
{item.label && <span className="text-caption text-ink-faint italic">{item.label}</span>}
{isYT && item.isShort && <Badge variant="outline">Short</Badge>}
+ {item.category && <Badge variant="secondary" className="lg:hidden">{item.category}</Badge>}
</div>
</div>
</div>
</TableCell>
- <TableCell>
+ <TableCell className="hidden lg:table-cell">
{item.category ? <Badge variant="secondary">{item.category}</Badge> : <span className="text-ink-faint">-</span>}
</TableCell>
- <TableCell className="text-right">
- <ViewsCell item={item} isYT={isYT} onEdit={onEdit} />
+ <TableCell className="hidden text-right sm:table-cell">
+ <ViewsCell item={item} title={title} isYT={isYT} onEdit={onEdit} />
</TableCell>
- <TableCell className="text-right font-semibold text-ink">{engagement !== undefined ? fmtNum(engagement) : '-'}</TableCell>
- <TableCell className="text-right text-ink-muted">{comments !== undefined ? fmtNum(comments) : '-'}</TableCell>
- <TableCell className="text-right text-ink-muted">
+ <TableCell className="text-right font-semibold text-ink">{engagement !== undefined ? <Num value={engagement} /> : '-'}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell">{comments !== undefined ? <Num value={comments} /> : '-'}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted lg:table-cell">
{!isYT && item.upvoteRatio !== undefined && (item.score ?? 0) >= 10 ? `${Math.round(item.upvoteRatio * 100)}%` : '-'}
</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{item.lastFetchedAt ? fmtDate(item.lastFetchedAt) : '-'}</TableCell>
+ <TableCell className="hidden text-right text-small text-ink-faint md:table-cell">
+ {item.lastFetchedAt ? <RelativeTime date={item.lastFetchedAt} /> : '-'}
+ </TableCell>
<TableCell>
<div className="flex items-center justify-end gap-0.5">
- <RowAction label="Refresh live data" onClick={() => onRefresh(item.id)} disabled={isRefreshing}>
- <RefreshCw className={cn(isRefreshing && 'animate-spin')} />
+ <RowAction label="Refresh live data" target={title} onClick={() => onRefresh(item.id)} disabled={isRefreshing}>
+ <RefreshCw className={cn(isRefreshing && 'animate-spin')} aria-hidden="true" />
</RowAction>
- <RowAction label="Edit" onClick={() => onEdit(item)}><Pencil /></RowAction>
- <RowAction label="Open original" href={item.permalink || item.url}><ExternalLink /></RowAction>
- <RowAction label="Stop tracking" onClick={() => onDelete(item)} danger><Trash2 /></RowAction>
+ <RowAction label="Edit" target={title} onClick={() => onEdit(item)}><Pencil aria-hidden="true" /></RowAction>
+ <RowAction label="Open original" target={title} href={item.permalink || item.url}><ExternalLink aria-hidden="true" /></RowAction>
+ <RowAction label="Stop tracking" target={title} onClick={() => onDelete(item)} danger><Trash2 aria-hidden="true" /></RowAction>
</div>
</TableCell>
</TableRow>
diff --git a/frontend/src/features/analytics/tracked/TrackedTable.tsx b/frontend/src/features/analytics/tracked/TrackedTable.tsx
index efe3e1f..3f76b7f 100644
--- a/frontend/src/features/analytics/tracked/TrackedTable.tsx
+++ b/frontend/src/features/analytics/tracked/TrackedTable.tsx
@@ -1,9 +1,7 @@
-import { Bookmark } from 'lucide-react';
import { Checkbox } from '@/components/ui/checkbox';
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import { Table, TableBody, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import SurfaceBox from '@/components/SurfaceBox';
import ColumnHint from '@/components/ColumnHint';
-import { EmptyState } from '@/components/StateViews';
import TrackedRow from './TrackedRow';
import type { TrackedContentItem } from '@shared/types/domain.ts';
import type { TrackedSelection } from './useTrackedSelection';
@@ -19,31 +17,24 @@ export interface TrackedTableProps {
export default function TrackedTable({ filtered, selection, refreshingIds, onRefresh, onEdit, onDelete }: TrackedTableProps) {
return (
- <SurfaceBox content={false} className="overflow-hidden">
+ <SurfaceBox title="Tracked items" content={false} className="overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-10">
<Checkbox checked={selection.allSelected} onCheckedChange={selection.toggleAll} aria-label="Select all shown items" />
</TableHead>
- <TableHead>Content</TableHead>
- <TableHead className="w-32">Category</TableHead>
- <TableHead className="w-24 text-right">Views</TableHead>
+ <TableHead className="sticky left-0 z-[1] bg-surface-raised">Content</TableHead>
+ <TableHead className="hidden w-32 lg:table-cell">Category</TableHead>
+ <TableHead className="hidden w-24 text-right sm:table-cell">Views</TableHead>
<TableHead className="w-28 text-right">Likes or karma</TableHead>
- <TableHead className="w-24 text-right">Comments</TableHead>
- <TableHead className="w-32 text-right"><ColumnHint label="Upvote rate" hint="Share of votes on a Reddit post that are upvotes. Shows a dash for YouTube videos and for posts under 10 karma, where the ratio is not meaningful." /></TableHead>
- <TableHead className="w-28 text-right">Fetched</TableHead>
+ <TableHead className="hidden w-24 text-right md:table-cell">Comments</TableHead>
+ <TableHead className="hidden w-32 text-right lg:table-cell"><ColumnHint label="Upvote rate" hint="Share of votes on a Reddit post that are upvotes. Shows a dash for YouTube videos and for posts under 10 karma, where the ratio is not meaningful." /></TableHead>
+ <TableHead className="hidden w-28 text-right md:table-cell">Fetched</TableHead>
<TableHead className="w-32"><span className="sr-only">Actions</span></TableHead>
</TableRow>
</TableHeader>
<TableBody>
- {filtered.length === 0 && (
- <TableRow className="hover:bg-transparent">
- <TableCell colSpan={9}>
- <EmptyState compact icon={<Bookmark />} title="No items match" description="Clear the search or choose a different type or category." />
- </TableCell>
- </TableRow>
- )}
{filtered.map(item => (
<TrackedRow
key={item.id}
diff --git a/frontend/src/features/analytics/tracked/trackedList.ts b/frontend/src/features/analytics/tracked/trackedList.ts
index cf57fdf..07b3156 100644
--- a/frontend/src/features/analytics/tracked/trackedList.ts
+++ b/frontend/src/features/analytics/tracked/trackedList.ts
@@ -46,6 +46,11 @@ export const SORT_OPTIONS: TrackedSortOption[] = [
{ value: 'views-desc', label: 'Most views' },
];
+// a sort read from the address falls back to newest first when it is not one of the options
+export function trackedSortOf(value: string): string {
+ return SORT_OPTIONS.some(option => option.value === value) ? value : 'date-desc';
+}
+
function compareTracked(sort: string, first: TrackedContentItem, second: TrackedContentItem): number {
if (sort === 'engagement-desc') return trackedEngagement(second) - trackedEngagement(first);
if (sort === 'comments-desc') return trackedComments(second) - trackedComments(first);
@@ -97,13 +102,21 @@ export function bulkCategoryMessage(succeeded: number, failed: number): BulkCate
return { message: done, severity: 'success' };
}
-// an empty field clears the views; otherwise a whole number of 0 or more
+const VIEW_SUFFIXES: Record<string, number> = { k: 1e3, m: 1e6 };
+
+export const MANUAL_VIEWS_ERROR = 'Enter views as a whole number, such as 1200, 1,200 or 1.2K.';
+
+// an empty field clears the views; otherwise the number as Reddit's insights show it: separators and a K or M
+// suffix are accepted, so a copied "12.5K" works without retyping
export function parseManualViews(raw: string): ManualViewsResult {
- const trimmed = raw.trim();
- if (trimmed === '') return { value: null };
- const views = Number(trimmed);
- if (!Number.isInteger(views) || views < 0) return { error: 'Views must be a whole number of 0 or more.' };
- return { value: views };
+ const compact = raw.trim().replace(/[\s,_]/g, '');
+ if (compact === '') return { value: null };
+ const match = /^(\d+(?:\.\d+)?)([km])?$/i.exec(compact);
+ if (!match) return { error: MANUAL_VIEWS_ERROR };
+ const [, digits, suffix] = match;
+ const number = Number(digits);
+ if (!suffix) return Number.isInteger(number) ? { value: number } : { error: MANUAL_VIEWS_ERROR };
+ return { value: Math.round(number * VIEW_SUFFIXES[suffix.toLowerCase()]) };
}
export function imageFileError(file: Pick<File, 'type' | 'size'>, hasCloudConfig: boolean): string {
diff --git a/frontend/src/features/analytics/tracked/useTrackedDelete.ts b/frontend/src/features/analytics/tracked/useTrackedDelete.ts
index dfb1769..bd1af78 100644
--- a/frontend/src/features/analytics/tracked/useTrackedDelete.ts
+++ b/frontend/src/features/analytics/tracked/useTrackedDelete.ts
@@ -1,5 +1,6 @@
-import { useState } from 'react';
+import { useCallback } from 'react';
import { api } from '../../../services/api';
+import { deleteWithUndo } from '@/lib/undoToast';
import type { TrackedContentItem } from '@shared/types/domain.ts';
import type { SetTrackedItems, ShowToast } from './useTrackedItems';
@@ -9,26 +10,37 @@ export interface UseTrackedDeleteOptions {
showToast: ShowToast;
}
-export function useTrackedDelete({ setItems, dropSelection, showToast }: UseTrackedDeleteOptions) {
- const [deleteItem, setDeleteItem] = useState<TrackedContentItem | null>(null);
- const [deleting, setDeleting] = useState(false);
+function titleOf(item: TrackedContentItem): string {
+ return item.title || item.label || item.url;
+}
- const handleDelete = async () => {
- if (!deleteItem) return;
- const id = deleteItem.id;
- setDeleting(true);
- try {
- await api.deleteTrackedContent(id);
- setItems(prev => prev.filter(item => item.id !== id));
- dropSelection(id);
- setDeleteItem(null);
- showToast('Stopped tracking this content');
- } catch (err) {
- showToast(`Couldn't stop tracking. ${(err as Error).message}`, 'error');
- } finally {
- setDeleting(false);
- }
- };
+// stopping tracking is frequent and only removes Twiligent's copy, so it happens at once with Undo instead of a
+// confirmation; the server delete waits until the Undo window closes
+export function useTrackedDelete({ setItems, dropSelection, showToast }: UseTrackedDeleteOptions) {
+ const remove = useCallback((item: TrackedContentItem) => {
+ let position = -1;
+ setItems(prev => {
+ position = prev.findIndex(candidate => candidate.id === item.id);
+ return prev.filter(candidate => candidate.id !== item.id);
+ });
+ dropSelection(item.id);
+ const restore = () => setItems(prev => {
+ if (prev.some(candidate => candidate.id === item.id)) return prev;
+ const next = [...prev];
+ next.splice(position < 0 ? next.length : Math.min(position, next.length), 0, item);
+ return next;
+ });
+ deleteWithUndo({
+ id: `tracked:${item.id}`,
+ message: `Stopped tracking "${titleOf(item)}"`,
+ commit: () => api.deleteTrackedContent(item.id).then(() => undefined),
+ onUndo: restore,
+ onFailure: err => {
+ restore();
+ showToast(`Couldn't stop tracking "${titleOf(item)}". ${err.message}`, 'error');
+ },
+ });
+ }, [setItems, dropSelection, showToast]);
- return { deleteItem, setDeleteItem, deleting, handleDelete };
+ return { remove };
}
diff --git a/frontend/src/features/analytics/tracked/useTrackedFilters.ts b/frontend/src/features/analytics/tracked/useTrackedFilters.ts
index 2d9de0c..26135c8 100644
--- a/frontend/src/features/analytics/tracked/useTrackedFilters.ts
+++ b/frontend/src/features/analytics/tracked/useTrackedFilters.ts
@@ -1,22 +1,32 @@
-import { useMemo, useState } from 'react';
-import { categoriesOf, filterAndSortTracked, trackedStatsOf } from './trackedList.ts';
+import { useMemo } from 'react';
+import { categoriesOf, filterAndSortTracked, trackedSortOf, trackedStatsOf } from './trackedList.ts';
+import { useLibraryParams } from '../useLibraryParams';
import type { TrackedContentItem } from '@shared/types/domain.ts';
+const DEFAULTS = { q: '', type: 'all', category: 'all', sort: 'date-desc' };
+
+// the search, type, category and sort live in the address, so Back, refresh and a shared link keep the view
export function useTrackedFilters(items: TrackedContentItem[]) {
- const [query, setQuery] = useState('');
- const [typeFilter, setTypeFilter] = useState('all');
- const [categoryFilter, setCategoryFilter] = useState('all');
- const [sort, setSort] = useState('date-desc');
+ const { values, update, clear } = useLibraryParams(DEFAULTS);
+ const sort = trackedSortOf(values.sort);
const categories = useMemo(() => categoriesOf(items), [items]);
const filtered = useMemo(
- () => filterAndSortTracked(items, { typeFilter, categoryFilter, query, sort }),
- [items, query, typeFilter, categoryFilter, sort],
+ () => filterAndSortTracked(items, { typeFilter: values.type, categoryFilter: values.category, query: values.q, sort }),
+ [items, values.q, values.type, values.category, sort],
);
const stats = useMemo(() => trackedStatsOf(items, categories), [items, categories]);
return {
- query, setQuery, typeFilter, setTypeFilter, categoryFilter, setCategoryFilter, sort, setSort,
+ query: values.q,
+ setQuery: (value: string) => update({ q: value }, { replace: true }),
+ typeFilter: values.type,
+ setTypeFilter: (value: string) => update({ type: value }),
+ categoryFilter: values.category,
+ setCategoryFilter: (value: string) => update({ category: value }),
+ sort,
+ setSort: (value: string) => update({ sort: value }),
+ clearFilters: () => clear(['q', 'type', 'category']),
categories, filtered, stats,
};
}
diff --git a/frontend/src/features/analytics/tracked/useTrackedItems.ts b/frontend/src/features/analytics/tracked/useTrackedItems.ts
index bb4135f..e46d296 100644
--- a/frontend/src/features/analytics/tracked/useTrackedItems.ts
+++ b/frontend/src/features/analytics/tracked/useTrackedItems.ts
@@ -10,21 +10,29 @@ export type SetTrackedItems = Dispatch<SetStateAction<TrackedContentItem[]>>;
export function useTrackedItems(showToast: ShowToast) {
const [items, setItems] = useState<TrackedContentItem[]>([]);
const [loading, setLoading] = useState(true);
+ // a failed load is shown as a failure, never as "nothing tracked yet"
+ const [error, setError] = useState<string | null>(null);
const [refreshingIds, setRefreshingIds] = useState(() => new Set<string>());
const load = useCallback(async () => {
try {
const data = await api.getTrackedContent();
setItems(Array.isArray(data) ? data : []);
+ setError(null);
} catch (err) {
- showToast(`Couldn't load tracked content. ${(err as Error).message}`, 'error');
+ setError(`Couldn't load tracked content. ${(err as Error).message}`);
} finally {
setLoading(false);
}
- }, [showToast]);
+ }, []);
useEffect(() => { load(); }, [load]);
+ const retry = useCallback(() => {
+ setLoading(true);
+ load();
+ }, [load]);
+
const replaceItem = (id: string, updated: TrackedContentItem) => setItems(prev => prev.map(item => (item.id === id ? updated : item)));
const handleRefresh = async (id: string) => {
@@ -32,8 +40,9 @@ export function useTrackedItems(showToast: ShowToast) {
try {
const updated = await api.refreshTrackedContent(id);
replaceItem(id, updated);
+ showToast(`Refreshed "${updated.title || updated.label || 'this item'}"`);
} catch (err) {
- showToast(`Refresh failed. ${(err as Error).message}`, 'error');
+ showToast(`Couldn't refresh this item. ${(err as Error).message}`, 'error');
} finally {
setRefreshingIds(prev => {
const next = new Set(prev);
@@ -43,5 +52,5 @@ export function useTrackedItems(showToast: ShowToast) {
}
};
- return { items, setItems, loading, refreshingIds, replaceItem, handleRefresh };
+ return { items, setItems, loading, error, retry, refreshingIds, replaceItem, handleRefresh };
}
diff --git a/frontend/src/features/analytics/useLibraryParams.ts b/frontend/src/features/analytics/useLibraryParams.ts
new file mode 100644
index 0000000..8ff57fa
--- /dev/null
+++ b/frontend/src/features/analytics/useLibraryParams.ts
@@ -0,0 +1,42 @@
+import { useCallback } from 'react';
+import { useSearchParams } from 'react-router-dom';
+import { readParam, readPositiveInt, withParam } from '@/lib/urlState';
+
+export type ParamDefaults = Record<string, string>;
+
+export interface UpdateOptions {
+ // typing replaces the history entry instead of adding one per keystroke
+ replace?: boolean;
+}
+
+// a library page's search, filters, sort, layout and page live in the address, so Back, refresh and a shared
+// link show the same results; changing a filter goes back to page 1 in the same history step
+export function useLibraryParams<K extends string>(defaults: Record<K, string>) {
+ const [params, setParams] = useSearchParams();
+
+ const values = {} as Record<K, string>;
+ for (const key of Object.keys(defaults) as K[]) values[key] = readParam(params, key, defaults[key]);
+ const page = readPositiveInt(params, 'page', 1);
+
+ const update = useCallback((changes: Partial<Record<K | 'page', string>>, { replace = false }: UpdateOptions = {}) => {
+ setParams(current => {
+ let next = current;
+ for (const [key, value] of Object.entries(changes) as [K | 'page', string | undefined][]) {
+ const fallback = key === 'page' ? '1' : defaults[key as K];
+ next = withParam(next, key, value ?? '', fallback);
+ }
+ if (!('page' in changes)) next = withParam(next, 'page', '1', '1');
+ return next;
+ }, { replace });
+ }, [setParams, defaults]);
+
+ const clear = useCallback((keys: K[]) => {
+ const changes: Partial<Record<K | 'page', string>> = {};
+ for (const key of keys) changes[key] = defaults[key];
+ update(changes);
+ }, [update, defaults]);
+
+ const setPage = useCallback((next: number) => update({ page: String(next) } as Partial<Record<K | 'page', string>>), [update]);
+
+ return { values, page, update, clear, setPage };
+}
diff --git a/frontend/src/features/analytics/useLibrarySources.ts b/frontend/src/features/analytics/useLibrarySources.ts
new file mode 100644
index 0000000..3b18c45
--- /dev/null
+++ b/frontend/src/features/analytics/useLibrarySources.ts
@@ -0,0 +1,67 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useAppContext } from '../../context/AppContext';
+import { failedSources, oldestTime } from '@/lib/library';
+import type { SourceFailure } from '@/lib/library';
+
+export interface LibrarySource {
+ id: string;
+}
+
+export interface LibrarySourcesState<A, R> {
+ sources: A[];
+ results: PromiseSettledResult<R>[];
+ failures: SourceFailure[];
+ fetchedAt: string | null;
+ initialLoading: boolean;
+ refreshing: boolean;
+ refresh: () => Promise<void>;
+}
+
+// loads one list per account for a library page: skeletons only before the first answer, a refresh keeps the
+// page, and an account that fails is named instead of silently missing from the totals
+export function useLibrarySources<A extends LibrarySource, R extends { fetchedAt?: string }>(
+ sources: A[],
+ fetchOne: (id: string, fresh: boolean) => Promise<R>,
+ nameOf: (source: A) => string,
+ label: string,
+): LibrarySourcesState<A, R> {
+ const { showToast } = useAppContext();
+ // keyed on the account ids: a background change to an account's fields must not reload every list
+ const idsKey = sources.map(source => source.id).join(',');
+ const sourcesRef = useRef(sources);
+ useEffect(() => { sourcesRef.current = sources; });
+ const [loaded, setLoaded] = useState<{ sources: A[]; results: PromiseSettledResult<R>[] }>({ sources: [], results: [] });
+ // the ids the shown lists were loaded for; skeletons show until they match the current accounts
+ const [loadedKey, setLoadedKey] = useState<string | null>(null);
+ const [refreshing, setRefreshing] = useState(false);
+
+ const load = useCallback(async (fresh: boolean) => {
+ const current = sourcesRef.current;
+ const results = await Promise.allSettled(current.map(source => fetchOne(source.id, fresh)));
+ setLoaded({ sources: current, results });
+ setLoadedKey(current.map(source => source.id).join(','));
+ return results;
+ }, [fetchOne]);
+
+ useEffect(() => {
+ load(false);
+ }, [load, idsKey]);
+
+ const initialLoading = loadedKey !== idsKey;
+
+ const refresh = useCallback(async () => {
+ setRefreshing(true);
+ const results = await load(true);
+ setRefreshing(false);
+ const failed = results.filter(result => result.status === 'rejected').length;
+ if (failed === 0) showToast(`${label} refreshed`);
+ }, [load, label, showToast]);
+
+ const failures = useMemo(() => failedSources(loaded.sources, loaded.results, nameOf), [loaded, nameOf]);
+ const fetchedAt = useMemo(
+ () => oldestTime(loaded.results.map(result => (result.status === 'fulfilled' ? result.value.fetchedAt : undefined))),
+ [loaded],
+ );
+
+ return { sources: loaded.sources, results: loaded.results, failures, fetchedAt, initialLoading, refreshing, refresh };
+}
diff --git a/frontend/src/features/analytics/videos/LayoutToggle.tsx b/frontend/src/features/analytics/videos/LayoutToggle.tsx
index dc09b7f..80446e3 100644
--- a/frontend/src/features/analytics/videos/LayoutToggle.tsx
+++ b/frontend/src/features/analytics/videos/LayoutToggle.tsx
@@ -1,9 +1,12 @@
import { LayoutGrid, List } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
+import { useRovingRadio } from '@/components/useRovingRadio';
export type LayoutMode = 'table' | 'grid';
+const LAYOUT_MODES: readonly LayoutMode[] = ['table', 'grid'];
+
interface LayoutOption {
value: LayoutMode;
label: string;
@@ -18,8 +21,9 @@ export interface LayoutToggleProps {
const LAYOUTS: LayoutOption[] = [{ value: 'table', label: 'List', Icon: List }, { value: 'grid', label: 'Grid', Icon: LayoutGrid }];
export default function LayoutToggle({ value, onChange }: LayoutToggleProps) {
+ const { onKeyDown, tabIndexOf } = useRovingRadio(LAYOUT_MODES, value, onChange);
return (
- <div role="radiogroup" aria-label="Layout" className="flex h-(--control-h-lg) items-center gap-0.5 rounded-field border border-line-control p-1">
+ <div role="radiogroup" aria-label="Layout" className="flex h-(--control-h-lg) items-center gap-0.5 rounded-field border border-input p-1">
{LAYOUTS.map(layout => {
const { Icon } = layout;
return (
@@ -29,13 +33,15 @@ export default function LayoutToggle({ value, onChange }: LayoutToggleProps) {
role="radio"
aria-checked={value === layout.value}
aria-label={`${layout.label} layout`}
+ tabIndex={tabIndexOf(layout.value)}
onClick={() => onChange(layout.value)}
+ onKeyDown={onKeyDown}
className={cn(
- 'flex size-8 items-center justify-center rounded-[8px] transition-colors',
+ 'flex size-8 items-center justify-center rounded-control transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
value === layout.value ? 'bg-surface-selected text-ink' : 'text-ink-muted hover:text-ink',
)}
>
- <Icon className="size-4 stroke-[1.75]" />
+ <Icon className="size-4 stroke-[1.75]" aria-hidden="true" />
</button>
);
})}
diff --git a/frontend/src/features/analytics/videos/VideoExplorer.tsx b/frontend/src/features/analytics/videos/VideoExplorer.tsx
index 1daaea7..4cca480 100644
--- a/frontend/src/features/analytics/videos/VideoExplorer.tsx
+++ b/frontend/src/features/analytics/videos/VideoExplorer.tsx
@@ -1,90 +1,70 @@
-import { useMemo, useState } from 'react';
+import { useMemo } from 'react';
import { Link } from 'react-router-dom';
-import { Eye, MessageSquare, Play, PlaySquare, Plus, RefreshCw, ThumbsUp } from 'lucide-react';
+import { PlaySquare, Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import PageHeader from '@/components/PageHeader';
import MetricBox from '@/components/MetricBox';
+import Num from '@/components/Num';
import SurfaceBox from '@/components/SurfaceBox';
import Pager from '@/components/Pager';
+import RefreshButton from '@/components/RefreshButton';
+import DataFreshness from '@/components/DataFreshness';
+import ActiveFilters from '@/components/ActiveFilters';
+import NoResults from '@/components/NoResults';
+import FailedSourcesAlert from '@/components/FailedSourcesAlert';
import { EmptyState } from '@/components/StateViews';
-import { pageSlice } from '@/lib/library';
-import type { PageSlice } from '@/lib/library';
-import { cn } from '@/lib/utils';
-import { fmtNum } from '../../../utils/formatters';
+import { VIEW_TIERS, pageSlice, resultCountLabel } from '@/lib/library';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { useChannelVideos } from './useChannelVideos';
-import { filterAndSortVideos, nextSort, videoStatsOf, videosDescription } from './videoLibrary.ts';
-import type { LibraryVideo, VideoSort, VideoSortField } from './videoLibrary.ts';
+import { useLibraryParams } from '../useLibraryParams';
+import { VIDEO_SORT_OPTIONS, filterAndSortVideos, nextSort, sortFromKey, sortKeyOf, videoStatsOf, videosDescription } from './videoLibrary.ts';
+import type { VideoSortField } from './videoLibrary.ts';
import VideoFilters from './VideoFilters';
import VideoListTable from './VideoListTable';
import VideoGrid from './VideoGrid';
import type { LayoutMode } from './LayoutToggle';
const ITEMS_PER_PAGE = 25;
+const RESULTS_ID = 'video-results';
-interface VideoResultsProps {
- filtered: LibraryVideo[];
- paged: PageSlice<LibraryVideo>;
- viewMode: LayoutMode;
- sort: VideoSort;
- onSort: (field: VideoSortField) => void;
- showChannel: boolean;
- onClearFilters: () => void;
-}
+const DEFAULTS = { q: '', channel: 'all', views: 'all', sort: 'viewCount:desc', view: 'table' };
-function VideoResults({ filtered, paged, viewMode, sort, onSort, showChannel, onClearFilters }: VideoResultsProps) {
- if (filtered.length === 0) {
- return (
- <SurfaceBox>
- <EmptyState
- compact
- icon={<PlaySquare />}
- title="No videos match"
- description="Clear the search or choose a different view range."
- action={<Button variant="outline" size="sm" onClick={onClearFilters}>Clear filters</Button>}
- />
- </SurfaceBox>
- );
- }
- if (viewMode === 'table') return <VideoListTable paged={paged} sort={sort} onSort={onSort} showChannel={showChannel} />;
- return <VideoGrid items={paged.items} showChannel={showChannel} />;
-}
+const { videos: Videos, views: Views, likes: Likes, comments: Comments, averageViews: AverageViews } = METRIC_ICONS;
export default function VideoExplorer() {
- const { videos, channels, loading, reload } = useChannelVideos();
- const [search, setSearch] = useState('');
- const [channelFilter, setChannelFilter] = useState('all');
- const [tier, setTier] = useState('all');
- const [sort, setSort] = useState<VideoSort>({ field: 'viewCount', order: 'desc' });
- const [viewMode, setViewMode] = useState<LayoutMode>('table');
- const [page, setPage] = useState(1);
+ const { videos, channels, channelCount, failures, fetchedAt, loading, refreshing, refresh } = useChannelVideos();
+ const { values, page, update, clear, setPage } = useLibraryParams(DEFAULTS);
+ const sort = sortFromKey(values.sort);
+ const viewMode: LayoutMode = values.view === 'grid' ? 'grid' : 'table';
const filtered = useMemo(
- () => filterAndSortVideos(videos, { channelFilter, search, tier, sort }),
- [videos, channelFilter, search, tier, sort],
+ () => filterAndSortVideos(videos, { channelFilter: values.channel, search: values.q, tier: values.views, sort: sortFromKey(values.sort) }),
+ [videos, values.channel, values.q, values.views, values.sort],
);
const paged = pageSlice(filtered, page, ITEMS_PER_PAGE);
const stats = useMemo(() => videoStatsOf(filtered), [filtered]);
- function resetPage<T>(setter: (value: T) => void) {
- return (value: T) => {
- setter(value);
- setPage(1);
- };
- }
- const handleSort = (field: VideoSortField) => setSort(prev => nextSort(prev, field));
- const clearFilters = () => { setSearch(''); setTier('all'); setChannelFilter('all'); setPage(1); };
+ const handleSort = (field: VideoSortField) => update({ sort: sortKeyOf(nextSort(sort, field)) });
+ const clearFilters = () => clear(['q', 'channel', 'views']);
+ const channelTitle = channels.find(channel => channel.id === values.channel)?.title;
+ const tierLabel = VIEW_TIERS.find(tier => tier.value === values.views)?.label;
+ const activeFilters = [
+ values.q && { key: 'q', label: `"${values.q}"`, onRemove: () => update({ q: '' }) },
+ values.channel !== 'all' && channelTitle && { key: 'channel', label: channelTitle, onRemove: () => update({ channel: 'all' }) },
+ values.views !== 'all' && tierLabel && { key: 'views', label: tierLabel, onRemove: () => update({ views: 'all' }) },
+ ].filter(Boolean) as { key: string; label: string; onRemove: () => void }[];
const header = (
<PageHeader
title="Videos"
- description={videosDescription(loading, videos.length, channels.length)}
- actions={
- <Button variant="outline" size="sm" onClick={reload} disabled={loading}>
- <RefreshCw data-icon="inline-start" className={cn(loading && 'animate-spin')} />
- Refresh
- </Button>
+ description={
+ <span className="flex flex-col gap-1">
+ <span>{videosDescription(loading, videos.length, channels.length)}</span>
+ {!loading && <DataFreshness fetchedAt={fetchedAt} qualifier={channels.length > 1 ? 'oldest channel' : undefined} />}
+ </span>
}
+ actions={<RefreshButton refreshing={refreshing} onRefresh={refresh} disabled={loading || channelCount === 0} />}
/>
);
@@ -101,7 +81,7 @@ export default function VideoExplorer() {
);
}
- if (channels.length === 0) {
+ if (channelCount === 0) {
return (
<div className="flex flex-col gap-6">
{header}
@@ -110,7 +90,7 @@ export default function VideoExplorer() {
icon={<PlaySquare />}
title="No YouTube channels yet"
description="Add a channel to browse and compare its videos here."
- action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" />Add a channel</Button>}
+ action={<Button render={<Link to="/accounts?add=1" />}><Plus data-icon="inline-start" aria-hidden="true" />Add a channel</Button>}
/>
</SurfaceBox>
</div>
@@ -121,37 +101,53 @@ export default function VideoExplorer() {
<div className="flex flex-col gap-6">
{header}
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-5">
- <MetricBox small icon={<Play />} label="Videos" value={fmtNum(stats.total)} />
- <MetricBox small icon={<Eye />} label="Views" value={fmtNum(stats.views)} highlight />
- <MetricBox small icon={<ThumbsUp />} label="Likes" value={fmtNum(stats.likes)} />
- <MetricBox small icon={<MessageSquare />} label="Comments" value={fmtNum(stats.comments)} />
- <MetricBox small icon={<Eye />} label="Average views" value={fmtNum(stats.avgViews)} />
+ <FailedSourcesAlert failures={failures} total={channelCount} noun="channels" onRetry={refresh} retrying={refreshing} />
+
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-5" aria-busy={refreshing}>
+ <MetricBox small icon={<Videos />} label="Videos" value={<Num value={stats.total} />} period="Matching videos" />
+ <MetricBox small icon={<Views />} label="Views" value={<Num value={stats.views} />} period="Matching videos" highlight />
+ <MetricBox small icon={<Likes />} label="Likes" value={<Num value={stats.likes} />} period="Matching videos" />
+ <MetricBox small icon={<Comments />} label="Comments" value={<Num value={stats.comments} />} period="Matching videos" />
+ <MetricBox small icon={<AverageViews />} label="Average views" value={<Num value={stats.avgViews} />} period="Per matching video" />
</div>
<VideoFilters
channels={channels}
- search={search}
- onSearchChange={resetPage(setSearch)}
- channelFilter={channelFilter}
- onChannelChange={resetPage(setChannelFilter)}
+ search={values.q}
+ onSearchChange={value => update({ q: value }, { replace: true })}
+ channelFilter={values.channel}
+ onChannelChange={value => update({ channel: value })}
+ sortOptions={VIDEO_SORT_OPTIONS}
+ sortKey={sortKeyOf(sort)}
+ onSortChange={value => update({ sort: value })}
viewMode={viewMode}
- onViewModeChange={setViewMode}
- tier={tier}
- onTierChange={resetPage(setTier)}
+ onViewModeChange={value => update({ view: value, page: String(page) })}
+ tier={values.views}
+ onTierChange={value => update({ views: value })}
/>
- <VideoResults
- filtered={filtered}
- paged={paged}
- viewMode={viewMode}
- sort={sort}
- onSort={handleSort}
- showChannel={channels.length > 1}
- onClearFilters={clearFilters}
- />
+ <ActiveFilters countLabel={resultCountLabel(filtered.length, videos.length, 'videos')} filters={activeFilters} onClearAll={clearFilters} />
- <Pager page={paged.page} pageCount={paged.pageCount} onPageChange={setPage} total={filtered.length} shown={paged.items.length} noun="videos" />
+ <div id={RESULTS_ID} tabIndex={-1} className="outline-none" aria-busy={refreshing}>
+ {filtered.length === 0 ? (
+ <SurfaceBox><NoResults noun="videos" query={values.q} onClear={clearFilters} /></SurfaceBox>
+ ) : viewMode === 'table' ? (
+ <VideoListTable paged={paged} sort={sort} onSort={handleSort} showChannel={channels.length > 1} />
+ ) : (
+ <VideoGrid items={paged.items} showChannel={channels.length > 1} />
+ )}
+ </div>
+
+ <Pager
+ page={paged.page}
+ pageCount={paged.pageCount}
+ onPageChange={setPage}
+ total={filtered.length}
+ shown={paged.items.length}
+ pageSize={ITEMS_PER_PAGE}
+ noun="videos"
+ resultsId={RESULTS_ID}
+ />
</div>
);
}
diff --git a/frontend/src/features/analytics/videos/VideoFilters.tsx b/frontend/src/features/analytics/videos/VideoFilters.tsx
index e2b8ff1..6306378 100644
--- a/frontend/src/features/analytics/videos/VideoFilters.tsx
+++ b/frontend/src/features/analytics/videos/VideoFilters.tsx
@@ -1,37 +1,27 @@
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import SearchField from '@/components/SearchField';
import FilterChips from '@/components/FilterChips';
+import SortSelect from '@/components/SortSelect';
+import type { SortOption } from '@/components/SortSelect';
import { VIEW_TIERS } from '@/lib/library';
import LayoutToggle from './LayoutToggle';
import type { LayoutMode } from './LayoutToggle';
import type { LibraryChannel } from './videoLibrary.ts';
-interface ChannelSelectProps {
+export interface ChannelSelectProps {
channels: LibraryChannel[];
value: string;
onChange: (value: string) => void;
}
-export interface VideoFiltersProps {
- channels: LibraryChannel[];
- search: string;
- onSearchChange: (value: string) => void;
- channelFilter: string;
- onChannelChange: (value: string) => void;
- viewMode: LayoutMode;
- onViewModeChange: (value: LayoutMode) => void;
- tier: string;
- onTierChange: (value: string) => void;
-}
-
-function ChannelSelect({ channels, value, onChange }: ChannelSelectProps) {
+export function ChannelSelect({ channels, value, onChange }: ChannelSelectProps) {
return (
<Select
value={value}
- onValueChange={onChange as (value: string | null) => void}
+ onValueChange={next => { if (next) onChange(next as string); }}
items={[{ value: 'all', label: 'All channels' }, ...channels.map(channel => ({ value: channel.id, label: channel.title }))]}
>
- <SelectTrigger className="w-48" aria-label="Channel"><SelectValue /></SelectTrigger>
+ <SelectTrigger className="h-(--control-h-lg) w-48" aria-label="Channel"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="all">All channels</SelectItem>
@@ -42,8 +32,23 @@ function ChannelSelect({ channels, value, onChange }: ChannelSelectProps) {
);
}
+export interface VideoFiltersProps {
+ channels: LibraryChannel[];
+ search: string;
+ onSearchChange: (value: string) => void;
+ channelFilter: string;
+ onChannelChange: (value: string) => void;
+ sortOptions: readonly SortOption[];
+ sortKey: string;
+ onSortChange: (value: string) => void;
+ viewMode: LayoutMode;
+ onViewModeChange: (value: LayoutMode) => void;
+ tier: string;
+ onTierChange: (value: string) => void;
+}
+
export default function VideoFilters({
- channels, search, onSearchChange, channelFilter, onChannelChange, viewMode, onViewModeChange, tier, onTierChange,
+ channels, search, onSearchChange, channelFilter, onChannelChange, sortOptions, sortKey, onSortChange, viewMode, onViewModeChange, tier, onTierChange,
}: VideoFiltersProps) {
return (
<div className="flex flex-col gap-3">
@@ -55,6 +60,7 @@ export default function VideoFilters({
className="min-w-56 flex-1"
/>
{channels.length > 1 && <ChannelSelect channels={channels} value={channelFilter} onChange={onChannelChange} />}
+ <SortSelect options={sortOptions} value={sortKey} onChange={onSortChange} />
<LayoutToggle value={viewMode} onChange={onViewModeChange} />
</div>
<FilterChips label="Views" options={VIEW_TIERS} value={tier} onChange={onTierChange} />
diff --git a/frontend/src/features/analytics/videos/VideoGrid.tsx b/frontend/src/features/analytics/videos/VideoGrid.tsx
index 0e07a2e..623ba9a 100644
--- a/frontend/src/features/analytics/videos/VideoGrid.tsx
+++ b/frontend/src/features/analytics/videos/VideoGrid.tsx
@@ -1,9 +1,11 @@
-import { Eye, MessageSquare, ThumbsUp } from 'lucide-react';
import MediaCard, { MediaChip } from '@/components/MediaCard';
+import { METRIC_ICONS } from '@/lib/metricIcons';
import { fmtCount, fmtDuration, fmtNum, timeAgo } from '../../../utils/formatters';
import { watchUrl } from './videoLibrary.ts';
import type { LibraryVideo } from './videoLibrary.ts';
+const { views: Views, likes: Likes, comments: Comments } = METRIC_ICONS;
+
export interface VideoGridProps {
items: LibraryVideo[];
showChannel: boolean;
@@ -11,24 +13,27 @@ export interface VideoGridProps {
export default function VideoGrid({ items, showChannel }: VideoGridProps) {
return (
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4">
+ <ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4">
{items.map((video, i) => (
- <MediaCard
- key={`${video.videoId}-${i}`}
- href={watchUrl(video.videoId)}
- image={video.thumbnail}
- title={video.title}
- topRight={<MediaChip><Eye />{fmtNum(video.viewCount)}</MediaChip>}
- bottomRight={video.durationSeconds > 0 && <MediaChip>{fmtDuration(video.durationSeconds)}</MediaChip>}
- meta={
- <>
- <span className="flex items-center gap-1"><ThumbsUp />{fmtCount(video.likeCount)}</span>
- <span className="flex items-center gap-1"><MessageSquare />{fmtCount(video.commentCount)}</span>
- <span className="ml-auto">{showChannel ? video.channelTitle : timeAgo(video.publishedAt)}</span>
- </>
- }
- />
+ <li key={`${video.videoId}-${i}`} className="flex">
+ <MediaCard
+ className="w-full"
+ href={watchUrl(video.videoId)}
+ image={video.thumbnail}
+ title={video.title}
+ topRight={<MediaChip><Views aria-hidden="true" />{fmtNum(video.viewCount)}<span className="sr-only"> views</span></MediaChip>}
+ bottomRight={video.durationSeconds > 0 && <MediaChip><span className="sr-only">Length </span>{fmtDuration(video.durationSeconds)}</MediaChip>}
+ meta={
+ <>
+ <span className="flex items-center gap-1"><Likes aria-hidden="true" />{fmtCount(video.likeCount)}<span className="sr-only"> likes</span></span>
+ <span className="flex items-center gap-1"><Comments aria-hidden="true" />{fmtCount(video.commentCount)}<span className="sr-only"> comments</span></span>
+ <span className="ml-auto truncate">{showChannel ? video.channelTitle : timeAgo(video.publishedAt)}</span>
+ <span className="sr-only"> (opens on YouTube in a new tab)</span>
+ </>
+ }
+ />
+ </li>
))}
- </div>
+ </ul>
);
}
diff --git a/frontend/src/features/analytics/videos/VideoListTable.tsx b/frontend/src/features/analytics/videos/VideoListTable.tsx
index 47d3270..703b513 100644
--- a/frontend/src/features/analytics/videos/VideoListTable.tsx
+++ b/frontend/src/features/analytics/videos/VideoListTable.tsx
@@ -1,10 +1,11 @@
import { Play } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import SurfaceBox from '@/components/SurfaceBox';
-import { fmtCount, fmtDate, fmtDuration, fmtNum, fmtPercent } from '../../../utils/formatters';
+import Num from '@/components/Num';
+import { fmtCount, fmtDate, fmtDuration, fmtPercent } from '../../../utils/formatters';
+import { isStrongEngagement, STRONG_ENGAGEMENT_HINT } from '@/lib/library';
import type { PageSlice } from '@/lib/library';
import { watchUrl } from './videoLibrary.ts';
import type { LibraryVideo, VideoSort, VideoSortField } from './videoLibrary.ts';
@@ -24,35 +25,36 @@ export interface VideoListTableProps {
}
function VideoRow({ video, rank, showChannel }: VideoRowProps) {
+ const strong = isStrongEngagement(video.engagementRate);
return (
<TableRow>
- <TableCell className="text-right font-mono text-caption text-ink-faint">{rank}</TableCell>
- <TableCell>
+ <TableCell className="hidden text-right font-mono text-caption text-ink-faint sm:table-cell">{rank}</TableCell>
+ <TableCell className="sticky left-0 z-[1] bg-surface-raised">
<div className="flex items-center gap-3">
{video.thumbnail
- ? <img src={video.thumbnail} alt="" loading="lazy" className="h-9 w-16 shrink-0 rounded-sm object-cover" />
- : <span className="h-9 w-16 shrink-0 rounded-sm bg-surface-sunken" />}
- <a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" className="max-w-[18rem] truncate text-sm font-medium text-ink hover:underline">
- {video.title}
+ ? <img src={video.thumbnail} alt="" loading="lazy" className="hidden h-9 w-16 shrink-0 rounded-sm object-cover sm:block" />
+ : <span className="hidden h-9 w-16 shrink-0 rounded-sm bg-surface-sunken sm:block" />}
+ <a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" title={video.title} className="max-w-44 truncate text-sm font-medium text-ink underline-offset-4 hover:underline sm:max-w-72">
+ {video.title}<span className="sr-only"> (opens on YouTube in a new tab)</span>
</a>
</div>
</TableCell>
- {showChannel && <TableCell className="max-w-36 truncate text-small text-ink-muted">{video.channelTitle}</TableCell>}
- <TableCell className="text-right font-semibold text-ink">{fmtNum(video.viewCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtCount(video.likeCount)}</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtCount(video.commentCount)}</TableCell>
+ {showChannel && <TableCell className="hidden max-w-36 truncate text-small text-ink-muted lg:table-cell" title={video.channelTitle}>{video.channelTitle}</TableCell>}
+ <TableCell className="text-right font-semibold text-ink"><Num value={video.viewCount} /></TableCell>
+ <TableCell className="hidden text-right text-ink-muted sm:table-cell">{fmtCount(video.likeCount)}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted md:table-cell">{fmtCount(video.commentCount)}</TableCell>
<TableCell className="text-right">
- <Badge variant={parseFloat(video.engagementRate) > 5 ? 'success' : 'secondary'}>{fmtPercent(video.engagementRate)}</Badge>
+ <Badge variant={strong ? 'success' : 'secondary'}>
+ {fmtPercent(video.engagementRate)}
+ {strong && <span className="sr-only"> (strong)</span>}
+ </Badge>
</TableCell>
- <TableCell className="text-right text-ink-muted">{fmtDuration(video.durationSeconds)}</TableCell>
- <TableCell className="text-right text-small text-ink-faint">{fmtDate(video.publishedAt)}</TableCell>
+ <TableCell className="hidden text-right text-ink-muted lg:table-cell">{fmtDuration(video.durationSeconds)}</TableCell>
+ <TableCell className="hidden text-right text-small text-ink-faint md:table-cell">{fmtDate(video.publishedAt)}</TableCell>
<TableCell>
- <Tooltip>
- <TooltipTrigger render={<Button variant="ghost" size="icon-xs" render={<a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" aria-label={`Watch ${video.title} on YouTube`} />} />}>
- <Play />
- </TooltipTrigger>
- <TooltipContent>Watch on YouTube</TooltipContent>
- </Tooltip>
+ <Button variant="ghost" size="icon-xs" render={<a href={watchUrl(video.videoId)} target="_blank" rel="noopener noreferrer" aria-label={`Watch ${video.title} on YouTube (opens in a new tab)`} />}>
+ <Play aria-hidden="true" />
+ </Button>
</TableCell>
</TableRow>
);
@@ -60,19 +62,19 @@ function VideoRow({ video, rank, showChannel }: VideoRowProps) {
export default function VideoListTable({ paged, sort, onSort, showChannel }: VideoListTableProps) {
return (
- <SurfaceBox content={false} className="overflow-hidden">
+ <SurfaceBox title="Videos" headingLevel="h2" content={false} className="overflow-hidden">
<Table>
<TableHeader>
<TableRow>
- <TableHead className="w-10 text-right">#</TableHead>
- <TableHead><VideoSortHeader field="title" label="Video" sort={sort} onSort={onSort} /></TableHead>
- {showChannel && <TableHead>Channel</TableHead>}
- <TableHead className="text-right"><VideoSortHeader field="viewCount" label="Views" sort={sort} onSort={onSort} align="right" /></TableHead>
- <TableHead className="text-right"><VideoSortHeader field="likeCount" label="Likes" sort={sort} onSort={onSort} align="right" /></TableHead>
- <TableHead className="text-right"><VideoSortHeader field="commentCount" label="Comments" sort={sort} onSort={onSort} align="right" /></TableHead>
- <TableHead className="text-right"><VideoSortHeader field="engagementRate" label="Engagement" sort={sort} onSort={onSort} align="right" /></TableHead>
- <TableHead className="text-right"><VideoSortHeader field="durationSeconds" label="Length" sort={sort} onSort={onSort} align="right" /></TableHead>
- <TableHead className="text-right"><VideoSortHeader field="publishedAt" label="Published" sort={sort} onSort={onSort} align="right" /></TableHead>
+ <TableHead className="hidden w-10 text-right sm:table-cell">#</TableHead>
+ <VideoSortHeader field="title" label="Video" sort={sort} onSort={onSort} className="sticky left-0 z-[1] bg-surface-raised" />
+ {showChannel && <TableHead className="hidden lg:table-cell">Channel</TableHead>}
+ <VideoSortHeader field="viewCount" label="Views" sort={sort} onSort={onSort} align="right" />
+ <VideoSortHeader field="likeCount" label="Likes" sort={sort} onSort={onSort} align="right" className="hidden sm:table-cell" />
+ <VideoSortHeader field="commentCount" label="Comments" sort={sort} onSort={onSort} align="right" className="hidden md:table-cell" />
+ <VideoSortHeader field="engagementRate" label="Engagement rate (%)" sort={sort} onSort={onSort} align="right" />
+ <VideoSortHeader field="durationSeconds" label="Length" sort={sort} onSort={onSort} align="right" className="hidden lg:table-cell" />
+ <VideoSortHeader field="publishedAt" label="Published" sort={sort} onSort={onSort} align="right" className="hidden md:table-cell" />
<TableHead className="w-10"><span className="sr-only">Watch</span></TableHead>
</TableRow>
</TableHeader>
@@ -82,6 +84,7 @@ export default function VideoListTable({ paged, sort, onSort, showChannel }: Vid
))}
</TableBody>
</Table>
+ <p className="border-t border-divider px-5 py-3 text-caption text-ink-faint">{STRONG_ENGAGEMENT_HINT}</p>
</SurfaceBox>
);
}
diff --git a/frontend/src/features/analytics/videos/VideoSortHeader.tsx b/frontend/src/features/analytics/videos/VideoSortHeader.tsx
index 6acfe1c..a1a8c1e 100644
--- a/frontend/src/features/analytics/videos/VideoSortHeader.tsx
+++ b/frontend/src/features/analytics/videos/VideoSortHeader.tsx
@@ -1,33 +1,38 @@
-import { ArrowDown, ArrowUp } from 'lucide-react';
+import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react';
+import { TableHead } from '@/components/ui/table';
import { cn } from '@/lib/utils';
-import type { ReactNode } from 'react';
import { ariaSortOf } from './videoLibrary.ts';
import type { VideoSort, VideoSortField } from './videoLibrary.ts';
export interface VideoSortHeaderProps {
field: VideoSortField;
- label: ReactNode;
+ label: string;
sort: VideoSort;
onSort: (field: VideoSortField) => void;
align?: 'left' | 'right';
+ className?: string;
}
-export default function VideoSortHeader({ field, label, sort, onSort, align = 'left' }: VideoSortHeaderProps) {
+// aria-sort belongs on the column header, so the header cell is part of this component, not just the button
+export default function VideoSortHeader({ field, label, sort, onSort, align = 'left', className }: VideoSortHeaderProps) {
const active = sort.field === field;
- const Arrow = sort.order === 'asc' ? ArrowUp : ArrowDown;
+ const Arrow = !active ? ArrowUpDown : sort.order === 'asc' ? ArrowUp : ArrowDown;
+ const state = active ? `, sorted ${sort.order === 'asc' ? 'ascending' : 'descending'}` : '';
return (
- <button
- type="button"
- onClick={() => onSort(field)}
- aria-sort={ariaSortOf(sort, field)}
- className={cn(
- 'inline-flex items-center gap-1 rounded-sm transition-colors hover:text-ink',
- align === 'right' && 'flex-row-reverse',
- active ? 'text-ink' : 'text-ink-muted',
- )}
- >
- {label}
- <Arrow className={cn('size-3', !active && 'invisible')} />
- </button>
+ <TableHead aria-sort={ariaSortOf(sort, field) ?? 'none'} className={cn(align === 'right' && 'text-right', className)}>
+ <button
+ type="button"
+ onClick={() => onSort(field)}
+ aria-label={`${label}${state}. Sort by ${label.toLowerCase()}`}
+ className={cn(
+ 'inline-flex items-center gap-1 rounded-sm transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-ring',
+ align === 'right' && 'flex-row-reverse',
+ active ? 'text-ink' : 'text-ink-muted',
+ )}
+ >
+ {label}
+ <Arrow className={cn('size-3', !active && 'opacity-50')} aria-hidden="true" />
+ </button>
+ </TableHead>
);
}
diff --git a/frontend/src/features/analytics/videos/useChannelVideos.ts b/frontend/src/features/analytics/videos/useChannelVideos.ts
index b917b4f..83c9a11 100644
--- a/frontend/src/features/analytics/videos/useChannelVideos.ts
+++ b/frontend/src/features/analytics/videos/useChannelVideos.ts
@@ -1,34 +1,30 @@
-import { useCallback, useEffect, useState } from 'react';
+import { useMemo } from 'react';
import { api } from '../../../services/api';
import { useAppContext } from '../../../context/AppContext';
import { platformOf } from '@/lib/accounts';
import type { AppAccount } from '../../../utils/formatters';
+import { useLibrarySources } from '../useLibrarySources';
import { mergeChannelVideos } from './videoLibrary';
-import type { LibraryChannel, LibraryVideo } from './videoLibrary';
+
+function channelName(account: AppAccount): string {
+ return account.title || 'Unknown channel';
+}
// Loads every video from every YouTube channel. Shared by the Videos and Shorts pages.
export function useChannelVideos() {
- const { accounts, showToast } = useAppContext();
- const [videos, setVideos] = useState<LibraryVideo[]>([]);
- const [channels, setChannels] = useState<LibraryChannel<AppAccount>[]>([]);
- const [loading, setLoading] = useState(true);
-
- const load = useCallback(async () => {
- setLoading(true);
- try {
- const channelAccounts = (accounts || []).filter(a => platformOf(a) === 'youtube');
- const results = await Promise.allSettled(channelAccounts.map(a => api.getVideos(a.id)));
- const merged = mergeChannelVideos(channelAccounts, results);
- setVideos(merged.videos);
- setChannels(merged.channels);
- } catch (err) {
- showToast(`Couldn't load videos. ${(err as Error).message}`, 'error');
- } finally {
- setLoading(false);
- }
- }, [accounts, showToast]);
-
- useEffect(() => { load(); }, [load]);
-
- return { videos, channels, loading, reload: load };
+ const { accounts } = useAppContext();
+ const channelAccounts = useMemo(() => (accounts || []).filter(account => platformOf(account) === 'youtube'), [accounts]);
+ const library = useLibrarySources(channelAccounts, api.getVideos, channelName, 'Videos');
+ const merged = useMemo(() => mergeChannelVideos(library.sources, library.results), [library.sources, library.results]);
+ return {
+ videos: merged.videos,
+ channels: merged.channels,
+ // "no channels yet" comes from the account list, not from which requests happened to succeed
+ channelCount: channelAccounts.length,
+ failures: library.failures,
+ fetchedAt: library.fetchedAt,
+ loading: library.initialLoading,
+ refreshing: library.refreshing,
+ refresh: library.refresh,
+ };
}
diff --git a/frontend/src/features/analytics/videos/videoLibrary.ts b/frontend/src/features/analytics/videos/videoLibrary.ts
index b757810..3eaddcc 100644
--- a/frontend/src/features/analytics/videos/videoLibrary.ts
+++ b/frontend/src/features/analytics/videos/videoLibrary.ts
@@ -5,6 +5,7 @@ import type { YouTubeVideo } from '../../../../../shared/types/youtube.ts';
// the fields mergeChannelVideos reads from each fulfilled GET /api/accounts/:id/videos
export interface ChannelVideosResult {
videos: YouTubeVideo[];
+ fetchedAt?: string;
}
export interface VideoChannelAccount {
@@ -70,8 +71,10 @@ export function watchUrl(videoId: string): string {
return `https://www.youtube.com/watch?v=${videoId}`;
}
-// engagement rates are strings, so they compare as text rather than as numbers
+// engagement rates are stored as two-decimal strings, so they are compared as numbers: "9.50" is below "12.34"
function compareField(a: LibraryVideo, b: LibraryVideo, field: VideoSortField): number {
+ if (field === 'engagementRate') return Number.parseFloat(a.engagementRate) - Number.parseFloat(b.engagementRate);
+ if (field === 'publishedAt') return (Date.parse(a.publishedAt) || 0) - (Date.parse(b.publishedAt) || 0);
const aValue = a[field] ?? 0;
const bValue = b[field] ?? 0;
if (typeof aValue === 'string' && typeof bValue === 'string') return aValue.localeCompare(bValue);
@@ -110,6 +113,32 @@ export function ariaSortOf(sort: VideoSort, field: VideoSortField): 'ascending'
return 'descending';
}
+export const VIDEO_SORT_FIELDS: readonly VideoSortField[] = ['title', 'viewCount', 'likeCount', 'commentCount', 'engagementRate', 'durationSeconds', 'publishedAt'];
+
+// the same sorts as the table headers, for the grid, which has no headers to click
+export const VIDEO_SORT_OPTIONS: { value: string; label: string }[] = [
+ { value: 'viewCount:desc', label: 'Most viewed' },
+ { value: 'likeCount:desc', label: 'Most liked' },
+ { value: 'commentCount:desc', label: 'Most comments' },
+ { value: 'engagementRate:desc', label: 'Best engagement rate' },
+ { value: 'publishedAt:desc', label: 'Newest first' },
+ { value: 'publishedAt:asc', label: 'Oldest first' },
+ { value: 'durationSeconds:desc', label: 'Longest first' },
+ { value: 'title:asc', label: 'Title, A to Z' },
+];
+
+export function sortKeyOf(sort: VideoSort): string {
+ return `${sort.field}:${sort.order}`;
+}
+
+// an unknown value from the address falls back to most viewed
+export function sortFromKey(key: string): VideoSort {
+ const [field, order] = key.split(':');
+ const knownField = VIDEO_SORT_FIELDS.find(candidate => candidate === field);
+ if (!knownField || (order !== 'asc' && order !== 'desc')) return { field: 'viewCount', order: 'desc' };
+ return { field: knownField, order };
+}
+
export function videosDescription(loading: boolean, videoCount: number, channelCount: number): string {
if (loading) return 'Loading videos from your channels';
return `${fmtNum(videoCount)} videos across ${channelCount} channel${channelCount === 1 ? '' : 's'}`;
diff --git a/frontend/src/hooks/use-account-analytics.ts b/frontend/src/hooks/use-account-analytics.ts
index 05dfad4..ce67dce 100644
--- a/frontend/src/hooks/use-account-analytics.ts
+++ b/frontend/src/hooks/use-account-analytics.ts
@@ -1,55 +1,79 @@
import { useCallback, useEffect, useState } from 'react';
import { useAppContext } from '../context/AppContext';
import { api } from '../services/api';
+import { normalizeAccount } from '../utils/formatters';
export interface AccountAnalyticsPayload<P, A> {
profile: P;
analytics: A;
+ // when the numbers came from the platform; a live response without it was fetched just now
+ fetchedAt?: string;
+}
+
+export interface AccountAnalyticsOptions {
+ // true when the response is always fetched live, so its age is the moment it arrived
+ live?: boolean;
}
// pass a stable method such as api.getIGAnalytics so it loads once per account
export function useAccountAnalytics<P, A>(
account: { id?: string } | null | undefined,
- fetchAnalytics: (id: string) => Promise<AccountAnalyticsPayload<P, A>>,
+ fetchAnalytics: (id: string, fresh?: boolean) => Promise<AccountAnalyticsPayload<P, A>>,
label: string,
+ { live = false }: AccountAnalyticsOptions = {},
) {
- const { showToast } = useAppContext();
- const [loading, setLoading] = useState(true);
+ const { showToast, setAccounts } = useAppContext();
+ const [initialLoading, setInitialLoading] = useState(true);
const [profile, setProfile] = useState<P | null>(null);
const [analytics, setAnalytics] = useState<A | null>(null);
+ const [fetchedAt, setFetchedAt] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
// keyed on the account id so a background refresh does not refetch analytics
const accountId = account?.id;
- const loadAnalytics = useCallback(async () => {
- if (!accountId) return;
- setLoading(true);
+ const loadAnalytics = useCallback(async (fresh = false): Promise<boolean> => {
+ if (!accountId) return false;
try {
- const data = await fetchAnalytics(accountId);
+ const data = await fetchAnalytics(accountId, fresh);
setProfile(data.profile);
setAnalytics(data.analytics);
+ setFetchedAt(data.fetchedAt ?? (live ? new Date().toISOString() : null));
+ setError(null);
+ return true;
} catch (err) {
- showToast(`Couldn't load ${label} analytics. ${(err as Error).message}`, 'error');
+ // the page keeps the last numbers it had and shows the failure beside them
+ setError(`Couldn't load ${label} analytics. ${(err as Error).message}`);
+ return false;
} finally {
- setLoading(false);
+ setInitialLoading(false);
}
- }, [accountId, fetchAnalytics, label, showToast]);
+ }, [accountId, fetchAnalytics, label, live]);
+
+ useEffect(() => {
+ setInitialLoading(true);
+ loadAnalytics();
+ }, [loadAnalytics]);
- useEffect(() => { loadAnalytics(); }, [loadAnalytics]);
+ const retry = useCallback(() => {
+ setInitialLoading(true);
+ loadAnalytics();
+ }, [loadAnalytics]);
const handleRefresh = async () => {
if (!accountId) return;
setRefreshing(true);
try {
- await api.refreshAccount(accountId);
- await loadAnalytics();
- showToast(`${label} account refreshed`);
+ const { account: refreshed } = await api.refreshAccount(accountId);
+ // the sidebar, header and "updated" times read the shared list, so it gets the new profile too
+ setAccounts(current => current.map(item => (item.id === refreshed.id ? normalizeAccount(refreshed) : item)));
+ if (await loadAnalytics(true)) showToast(`${label} account refreshed`);
} catch (err) {
- showToast(`Refresh failed. ${(err as Error).message}`, 'error');
+ showToast(`Couldn't refresh the ${label} account. ${(err as Error).message}`, 'error');
} finally {
setRefreshing(false);
}
};
- return { loading, profile, analytics, refreshing, handleRefresh };
+ return { initialLoading, error, profile, analytics, fetchedAt, refreshing, handleRefresh, retry };
}
diff --git a/frontend/src/lib/chart.ts b/frontend/src/lib/chart.ts
index 03021b4..ff937bb 100644
--- a/frontend/src/lib/chart.ts
+++ b/frontend/src/lib/chart.ts
@@ -31,3 +31,27 @@ export const tooltipStyle = {
export const tooltipCursor = { fill: 'var(--surface-hover)' };
export const legendStyle = { fontSize: 12, color: 'var(--ink-muted)' };
+
+// a figure is a category name and its value; the summary is what a sighted reader takes from the plot at a glance
+export interface ChartPoint {
+ name: string;
+ value: number;
+}
+
+export function rankingSummary(points: readonly ChartPoint[], formatValue: (value: number) => string, unit: string): string {
+ if (points.length === 0) return 'No data yet.';
+ const sorted = [...points].sort((a, b) => b.value - a.value);
+ const top = sorted[0];
+ const bottom = sorted[sorted.length - 1];
+ if (sorted.length === 1) return `${top.name}: ${formatValue(top.value)} ${unit}.`;
+ return `Highest: ${top.name}, ${formatValue(top.value)} ${unit}. Lowest: ${bottom.name}, ${formatValue(bottom.value)} ${unit}.`;
+}
+
+export function trendSummary(points: readonly ChartPoint[], formatValue: (value: number) => string, unit: string): string {
+ if (points.length === 0) return 'No data yet.';
+ const first = points[0];
+ const last = points[points.length - 1];
+ const peak = points.reduce((best, point) => (point.value > best.value ? point : best), first);
+ if (points.length === 1) return `${first.name}: ${formatValue(first.value)} ${unit}.`;
+ return `From ${first.name} to ${last.name}: ${formatValue(first.value)} to ${formatValue(last.value)} ${unit}. Peak ${formatValue(peak.value)} in ${peak.name}.`;
+}
diff --git a/frontend/src/lib/library.ts b/frontend/src/lib/library.ts
index edb29d7..7da6eda 100644
--- a/frontend/src/lib/library.ts
+++ b/frontend/src/lib/library.ts
@@ -71,3 +71,79 @@ export function matchesText(values: unknown[], query: string): boolean {
if (!needle) return true;
return values.some(value => typeof value === 'string' && value.toLowerCase().includes(needle));
}
+
+export interface PageRangeInput {
+ page: number;
+ pageCount: number;
+ total: number;
+ shown: number;
+ pageSize?: number;
+ noun: string;
+}
+
+// "Showing 26 to 50 of 300 videos" when the page size is known, so the range is clear, not just the count
+export function pageRangeLabel({ page, pageCount, total, shown, pageSize, noun }: PageRangeInput): string {
+ if (total === 0) return `No ${noun}`;
+ if (pageCount <= 1 || !pageSize) return pageCount <= 1 ? `${total} ${noun}` : `Showing ${shown} of ${total} ${noun}`;
+ const first = (page - 1) * pageSize + 1;
+ const last = first + shown - 1;
+ return `Showing ${first} to ${last} of ${total} ${noun}`;
+}
+
+// "12 of 340 videos" once a filter narrows the list, "340 videos" otherwise
+export function resultCountLabel(matching: number, total: number, noun: string): string {
+ return matching === total ? `${total} ${noun}` : `${matching} of ${total} ${noun}`;
+}
+
+export type TrendTone = 'good' | 'bad' | 'neutral';
+
+// colour follows meaning: more followers is good, more failed replies is not
+export function trendTone(trend: number, upIsGood: boolean): TrendTone {
+ if (trend === 0) return 'neutral';
+ return (trend > 0) === upIsGood ? 'good' : 'bad';
+}
+
+// YouTube engagement above this share of views is well above typical, so the table marks it
+export const STRONG_ENGAGEMENT_PERCENT = 5;
+
+export const STRONG_ENGAGEMENT_HINT = 'Likes and comments as a share of views. Marked green above 5%, which is strong for YouTube.';
+
+export function isStrongEngagement(rate: number | string | null | undefined): boolean {
+ return Number.parseFloat(String(rate ?? 0)) > STRONG_ENGAGEMENT_PERCENT;
+}
+
+export interface SourceFailure {
+ id: string;
+ name: string;
+ message: string;
+}
+
+// the accounts whose request failed, in order, so the page can name them instead of quietly leaving them out
+export function failedSources<A extends { id: string }>(
+ accounts: readonly A[],
+ results: readonly PromiseSettledResult<unknown>[],
+ nameOf: (account: A) => string,
+): SourceFailure[] {
+ const failures: SourceFailure[] = [];
+ results.forEach((result, index) => {
+ if (result.status !== 'rejected') return;
+ const account = accounts[index];
+ const reason = result.reason as { message?: string } | undefined;
+ failures.push({ id: account.id, name: nameOf(account), message: reason?.message || 'The request failed' });
+ });
+ return failures;
+}
+
+// "2 of 5 channels could not load: Alpha (quota exceeded), Beta (not found)."
+export function failureSummary(failures: readonly SourceFailure[], total: number, noun: string): string {
+ if (failures.length === 0) return '';
+ const names = failures.map(failure => `${failure.name} (${failure.message})`).join(', ');
+ return `${failures.length} of ${total} ${noun} could not load: ${names}.`;
+}
+
+// a list built from several caches is as old as its oldest part
+export function oldestTime(times: readonly (string | null | undefined)[]): string | null {
+ const valid = times.filter((time): time is string => typeof time === 'string' && !Number.isNaN(Date.parse(time)));
+ if (valid.length === 0) return null;
+ return valid.reduce((oldest, time) => (Date.parse(time) < Date.parse(oldest) ? time : oldest));
+}
diff --git a/frontend/src/lib/metricIcons.ts b/frontend/src/lib/metricIcons.ts
new file mode 100644
index 0000000..392779e
--- /dev/null
+++ b/frontend/src/lib/metricIcons.ts
@@ -0,0 +1,42 @@
+import {
+ Award, BarChart3, BookmarkCheck, Calendar, Camera, CirclePlay, Clapperboard, Clock, Film, Flame, Gauge, Hash, Heart, Image,
+ MessageSquare, MessagesSquare, Percent, Scissors, Star, Tag, ThumbsUp, Timer, Trophy, UserPlus, Users, Video, Eye,
+} from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
+
+// one icon per meaning on every page, so the same picture never stands for two different numbers
+export const METRIC_ICONS = {
+ views: Eye,
+ averageViews: Gauge,
+ likes: ThumbsUp,
+ instagramLikes: Heart,
+ comments: MessageSquare,
+ karma: Award,
+ awards: Star,
+ upvoteRate: Percent,
+ rate: Percent,
+ audience: Users,
+ following: UserPlus,
+ videos: CirclePlay,
+ shorts: Scissors,
+ regularVideos: Video,
+ instagram: Camera,
+ reels: Clapperboard,
+ posts: Image,
+ redditPosts: MessagesSquare,
+ tracked: BookmarkCheck,
+ category: Tag,
+ tags: Hash,
+ median: BarChart3,
+ score: Flame,
+ consistency: Trophy,
+ quality: Film,
+ duration: Timer,
+ period: Calendar,
+ time: Clock,
+} satisfies Record<string, LucideIcon>;
+
+export type MetricIconName = keyof typeof METRIC_ICONS;
+
+// Instagram content types, with the same icons wherever they are counted or filtered
+export const IG_TYPE_ICONS = { reel: Clapperboard, post: Image, video: Video } satisfies Record<string, LucideIcon>;
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts
index e591aff..30a182a 100644
--- a/frontend/src/services/api.ts
+++ b/frontend/src/services/api.ts
@@ -12,7 +12,7 @@ import type {
InstagramMediaPublishResponse, InstagramMediaResponse, InstagramPublishingLimitResponse, InstagramPublishRequest,
InstagramPublishResponse, InstagramTokenRefreshResponse,
} from '@shared/types/instagram.ts';
-import type { RedditCacheData, RedditPost } from '@shared/types/reddit.ts';
+import type { RedditCacheData } from '@shared/types/reddit.ts';
import type {
AutomationAccountResponse, AutomationActivityItemResponse, AutomationActivityResponse, AutomationOverviewResponse,
AutomationRuleRequest, AutomationRuleResponse, AutomationRuleUpdateRequest, AutomationStatsResponse, AutomationTestRequest,
@@ -142,14 +142,14 @@ export const api = {
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`),
+ getIGMedia: (id: string, fresh = false) => request<InstagramMediaResponse>(`/accounts/${id}/ig-media${fresh ? '?fresh=1' : ''}`),
// Channel URL/ID resolution
resolveChannel: (input: string) => request<ResolveChannelResponse>('/resolve-channel', { method: 'POST', body: JSON.stringify({ input }) }),
// Analytics (YouTube)
getAnalytics: (id: string) => request<YouTubeAnalyticsPayload>(`/accounts/${id}/analytics`),
- getVideos: (id: string) => request<YouTubeVideosResponse>(`/accounts/${id}/videos`),
+ getVideos: (id: string, fresh = false) => request<YouTubeVideosResponse>(`/accounts/${id}/videos${fresh ? '?fresh=1' : ''}`),
getComparison: () => request<YouTubeComparisonResponse>('/comparison'),
@@ -164,8 +164,8 @@ export const api = {
publishIGContainer: (id: string, containerId: string) => request<InstagramMediaPublishResponse>(`/accounts/${id}/ig-media-publish`, { method: 'POST', body: JSON.stringify({ containerId }) }),
addRedditAccount: (username: string, cookie: string) => request<AccountResponse>('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, cookie }) }),
- getRedditAnalytics: (id: string) => request<RedditCacheData>(`/accounts/${id}/reddit-analytics`),
- getRedditPosts: (id: string) => request<RedditPost[]>(`/accounts/${id}/reddit-posts`),
+ // fresh skips the server's cache, for a person's explicit Refresh
+ getRedditAnalytics: (id: string, fresh = false) => request<RedditCacheData>(`/accounts/${id}/reddit-analytics${fresh ? '?fresh=1' : ''}`),
// Overview dashboard (tracked content + per-account analytics cache)
getOverview: () => request<OverviewResponse>('/overview'),
diff --git a/frontend/src/utils/instagramContent.ts b/frontend/src/utils/instagramContent.ts
index 6121e0a..d50869e 100644
--- a/frontend/src/utils/instagramContent.ts
+++ b/frontend/src/utils/instagramContent.ts
@@ -9,11 +9,12 @@ export interface IGContentTypeMeta {
export const IG_CONTENT_TYPES: InstagramContentType[] = ['reel', 'post', 'video'];
-// Colours are brand chart series so they follow the theme
+// chart series that follow the theme; the YouTube (chart-1) and Reddit (chart-4) hues are left out so a colour
+// never names two platforms
export const IG_CONTENT_TYPE_META: Record<InstagramContentType, IGContentTypeMeta> = {
- reel: { label: 'Reel', plural: 'Reels', color: 'var(--chart-1)' },
+ reel: { label: 'Reel', plural: 'Reels', color: 'var(--chart-5)' },
post: { label: 'Post', plural: 'Posts', color: 'var(--chart-3)' },
- video: { label: 'Video', plural: 'Videos', color: 'var(--chart-4)' },
+ video: { label: 'Video', plural: 'Videos', color: 'var(--chart-2)' },
};
export function igContentTypeMeta(type: string | null | undefined): IGContentTypeMeta {
diff --git a/frontend/tests/features/analytics/channel/channelChartData.test.ts b/frontend/tests/features/analytics/channel/channelChartData.test.ts
index 3f9f535..3f06cbc 100644
--- a/frontend/tests/features/analytics/channel/channelChartData.test.ts
+++ b/frontend/tests/features/analytics/channel/channelChartData.test.ts
@@ -37,10 +37,12 @@ test('categories use their name or a numbered fallback', () => {
assert.deepEqual(categoryDataOf({ 10: 4, 999: 1 }), [{ name: 'Music', value: 4 }, { name: 'Category 999', value: 1 }]);
});
-test('top video chart truncates titles and always adds an ellipsis', () => {
- const rows = topVideosChartOf([{ title: 'Short', viewCount: 5 }, null] as (YouTubeVideoSummary | null)[]);
- assert.deepEqual(rows[0], { name: 'Short…', views: 5, likes: 0 });
- assert.deepEqual(rows[1], { name: '…', views: 0, likes: 0 });
+test('top video chart adds an ellipsis only to titles it cut', () => {
+ const long = 'A video title well over twenty eight characters';
+ const rows = topVideosChartOf([{ title: 'Short', viewCount: 5 }, null, { title: long, viewCount: 1 }] as (YouTubeVideoSummary | null)[]);
+ assert.deepEqual(rows[0], { name: 'Short', views: 5, likes: 0 });
+ assert.deepEqual(rows[1], { name: '', views: 0, likes: 0 });
+ assert.equal(rows[2].name, `${long.slice(0, 28)}…`);
assert.deepEqual(topVideosChartOf(undefined), []);
});
diff --git a/frontend/tests/features/analytics/instagram/instagramAnalyticsData.test.ts b/frontend/tests/features/analytics/instagram/instagramAnalyticsData.test.ts
index f45efc0..df0525c 100644
--- a/frontend/tests/features/analytics/instagram/instagramAnalyticsData.test.ts
+++ b/frontend/tests/features/analytics/instagram/instagramAnalyticsData.test.ts
@@ -16,11 +16,11 @@ test('type rows keep content types with posts, in display order', () => {
const rows = typeRowsOf(typeStats as Partial<InstagramContentTypeStatsMap>);
assert.deepEqual(rows.map(row => row.type), ['reel', 'video']);
assert.equal(rows[0].name, 'Reels');
- assert.equal(rows[0].color, 'var(--chart-1)');
+ assert.equal(rows[0].color, 'var(--chart-5)');
assert.equal(rows[0].avgLikes, 10);
assert.deepEqual(contentMixOf(rows), [
- { name: 'Reels', value: 3, color: 'var(--chart-1)' },
- { name: 'Videos', value: 1, color: 'var(--chart-4)' },
+ { name: 'Reels', value: 3, color: 'var(--chart-5)' },
+ { name: 'Videos', value: 1, color: 'var(--chart-2)' },
]);
});
diff --git a/frontend/tests/features/analytics/overview/overviewLabels.test.ts b/frontend/tests/features/analytics/overview/overviewLabels.test.ts
index 94cbeb2..24b900e 100644
--- a/frontend/tests/features/analytics/overview/overviewLabels.test.ts
+++ b/frontend/tests/features/analytics/overview/overviewLabels.test.ts
@@ -58,13 +58,13 @@ test('category meta skips empty platforms', () => {
});
test('row labels follow the account platform', () => {
- assert.equal(topContentLabel(channel), '5.0K views');
+ assert.equal(topContentLabel(channel), '5K views');
assert.equal(topContentLabel(igAccount), '20 items');
assert.equal(topContentLabel(redditAccount), '70 karma');
assert.equal(accountAudienceLabel(channel), '100 subscribers');
assert.equal(accountAudienceLabel(igAccount), '300 followers');
assert.equal(accountAudienceLabel(redditAccount), '70 karma');
- assert.equal(accountContentLabel(channel), '5.0K views, 10 videos');
+ assert.equal(accountContentLabel(channel), '5K views, 10 videos');
assert.equal(accountContentLabel(igAccount), '20 items');
assert.equal(accountContentLabel(redditAccount), '60 post karma');
});
diff --git a/frontend/tests/features/analytics/overview/overviewStats.test.ts b/frontend/tests/features/analytics/overview/overviewStats.test.ts
index caac5c0..b6f0bf4 100644
--- a/frontend/tests/features/analytics/overview/overviewStats.test.ts
+++ b/frontend/tests/features/analytics/overview/overviewStats.test.ts
@@ -2,6 +2,7 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
accountTotalsOf, cacheTotalsOf, summaryOf, sortedByAudience, sortedByContent, sortedByChannelViews, igAccountRowsOf,
+ oldestFetchedAt,
} from '../../../../src/features/analytics/overview/overviewStats.ts';
import { trackedStatsOf } from '../../../../src/features/analytics/overview/overviewTrackedStats.ts';
@@ -68,3 +69,14 @@ test('Instagram rows pair each account with its cache, most viewed first', () =>
assert.deepEqual(rows.map(row => row.account.id), ['i1', 'i2']);
assert.equal(rows[1].cache, undefined);
});
+
+test('the overview reports the age of its oldest cached account and ignores accounts still syncing', () => {
+ const cache = {
+ y1: { cacheWarmed: true, fetchedAt: '2026-11-04T10:00:00Z' },
+ i1: { cacheWarmed: true, fetchedAt: '2026-11-04T08:30:00Z' },
+ r1: { cacheWarmed: false, syncing: true },
+ y2: { cacheWarmed: true },
+ };
+ assert.equal(oldestFetchedAt(cache), '2026-11-04T08:30:00Z');
+ assert.equal(oldestFetchedAt({ r1: { cacheWarmed: false } }), null);
+});
diff --git a/frontend/tests/features/analytics/reddit/redditAnalyticsData.test.ts b/frontend/tests/features/analytics/reddit/redditAnalyticsData.test.ts
index e323185..9f7121c 100644
--- a/frontend/tests/features/analytics/reddit/redditAnalyticsData.test.ts
+++ b/frontend/tests/features/analytics/reddit/redditAnalyticsData.test.ts
@@ -17,8 +17,8 @@ test('media types use their label and a fixed colour per type', () => {
test('karma summary leads with total karma', () => {
const items = karmaSummaryOf({ totalKarma: 1500, postKarma: 1000, commentKarma: 500 });
- assert.deepEqual(items.map(item => item.value), ['1.5K', '1.0K', '500', '0']);
- assert.equal(items[0].sub, '1,500');
+ assert.deepEqual(items.map(item => item.value), [1500, 1000, 500, 0]);
+ assert.equal(items[0].sub, 'All time');
assert.equal(items[0].lead, true);
});
diff --git a/frontend/tests/features/analytics/reddit/redditPostUtils.test.ts b/frontend/tests/features/analytics/reddit/redditPostUtils.test.ts
new file mode 100644
index 0000000..f22a368
--- /dev/null
+++ b/frontend/tests/features/analytics/reddit/redditPostUtils.test.ts
@@ -0,0 +1,26 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { filterAndSortRedditPosts, mergeAccountPosts, redditSortOf } from '../../../../src/features/analytics/reddit/redditPostUtils.ts';
+import type { RedditPost } from '../../../../../shared/types/reddit.ts';
+
+const post = (id: string, score: number, subreddit = 'origami') => ({ id, score, subreddit, title: id, numComments: 0, createdAt: '2026-01-01T00:00:00Z' }) as RedditPost;
+
+test('posts are tagged with their account and failed accounts are skipped', () => {
+ const accounts = [{ id: 'r1', username: 'ribbon' }, { id: 'r2', username: 'fold' }];
+ const results: PromiseSettledResult<{ posts?: RedditPost[] }>[] = [
+ { status: 'fulfilled', value: { posts: [post('a', 5)] } },
+ { status: 'rejected', reason: new Error('cookie expired') },
+ ];
+ const merged = mergeAccountPosts(accounts, results);
+ assert.deepEqual(merged.map(row => [row.id, row.accountId, row.accountUsername]), [['a', 'r1', 'ribbon']]);
+});
+
+test('posts filter by subreddit and sort by karma', () => {
+ const rows = [post('a', 5), post('b', 50), post('c', 20, 'paper')];
+ assert.deepEqual(filterAndSortRedditPosts(rows, { query: '', sort: 'score-desc', subreddit: 'origami' }).map(row => row.id), ['b', 'a']);
+});
+
+test('a sort from the address that is not an option falls back to most karma', () => {
+ assert.equal(redditSortOf('date-asc'), 'date-asc');
+ assert.equal(redditSortOf('upvotes'), 'score-desc');
+});
diff --git a/frontend/tests/features/analytics/reels/reelsLibrary.test.ts b/frontend/tests/features/analytics/reels/reelsLibrary.test.ts
index 673a5ee..15b87db 100644
--- a/frontend/tests/features/analytics/reels/reelsLibrary.test.ts
+++ b/frontend/tests/features/analytics/reels/reelsLibrary.test.ts
@@ -1,7 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
- mergeAccountMedia, typeTotalsOf, viewTotalsOf, filterAndSortMedia, typeViewsSubtitle, reelsDescription,
+ mergeAccountMedia, typeTotalsOf, viewTotalsOf, filterAndSortMedia, typeViewsSubtitle, reelsDescription, mediaSortOf,
} from '../../../../src/features/analytics/reels/reelsLibrary.ts';
import type { AccountMediaResult, LibraryMedia, MediaAccount, MediaQuery } from '../../../../src/features/analytics/reels/reelsLibrary.ts';
@@ -57,3 +57,8 @@ test('labels', () => {
assert.equal(reelsDescription(false, 1, 1), '1 item across 1 account');
assert.equal(reelsDescription(false, 2, 3), '2 items across 3 accounts');
});
+
+test('a media sort from the address that is not an option falls back to most viewed', () => {
+ assert.equal(mediaSortOf('timestamp'), 'timestamp');
+ assert.equal(mediaSortOf('caption'), 'viewCount');
+});
diff --git a/frontend/tests/features/analytics/shorts/shortsLibrary.test.ts b/frontend/tests/features/analytics/shorts/shortsLibrary.test.ts
index ff13eae..e08706f 100644
--- a/frontend/tests/features/analytics/shorts/shortsLibrary.test.ts
+++ b/frontend/tests/features/analytics/shorts/shortsLibrary.test.ts
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { shortsOf, filterAndSortShorts, shortsDescription } from '../../../../src/features/analytics/shorts/shortsLibrary.ts';
+import { shortsOf, filterAndSortShorts, shortsDescription, shortsSortOf } from '../../../../src/features/analytics/shorts/shortsLibrary.ts';
import type { ShortsQuery } from '../../../../src/features/analytics/shorts/shortsLibrary.ts';
import type { LibraryVideo } from '../../../../src/features/analytics/videos/videoLibrary.ts';
@@ -38,3 +38,8 @@ test('the description counts shorts and channels', () => {
assert.equal(shortsDescription(false, 1200, 1), '1.2K Shorts across 1 channel');
assert.equal(shortsDescription(false, 0, 3), '0 Shorts across 3 channels');
});
+
+test('a sort from the address that is not an option falls back to most viewed', () => {
+ assert.equal(shortsSortOf('likeCount'), 'likeCount');
+ assert.equal(shortsSortOf('title'), 'viewCount');
+});
diff --git a/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.ts b/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.ts
index 17041f5..60c6c39 100644
--- a/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.ts
+++ b/frontend/tests/features/analytics/tracked/trackedCategoryStats.test.ts
@@ -54,7 +54,7 @@ test('overview metrics match the page wording', () => {
const ytStats = youtubeStatsOf(videos);
const rdStats = redditStatsOf(posts);
assert.equal(itemsSubtitle(ytStats, rdStats), '2 YouTube videos, 2 Reddit posts');
- assert.deepEqual(viewsMetric(ytStats, rdStats), { value: '3.5K', subtitle: '3.0K YouTube, 500 Reddit' });
+ assert.deepEqual(viewsMetric(ytStats, rdStats), { value: '3.5K', subtitle: '3K YouTube, 500 Reddit' });
assert.deepEqual(viewsMetric(youtubeStatsOf([]), redditStatsOf([])), { value: '-', subtitle: 'No views recorded yet' });
assert.deepEqual(karmaMetric(rdStats), { value: '100', subtitle: '50 per post on average' });
assert.deepEqual(karmaMetric(redditStatsOf([])), { value: '-', subtitle: 'No Reddit posts in this category' });
diff --git a/frontend/tests/features/analytics/tracked/trackedList.test.ts b/frontend/tests/features/analytics/tracked/trackedList.test.ts
index b01a3a9..cad27fe 100644
--- a/frontend/tests/features/analytics/tracked/trackedList.test.ts
+++ b/frontend/tests/features/analytics/tracked/trackedList.test.ts
@@ -2,7 +2,7 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
SORT_OPTIONS, filterAndSortTracked, categoriesOf, trackedStatsOf, typeChipsOf, pluralize, countLabel,
- bulkCategoryMessage, parseManualViews, imageFileError, MAX_IMAGE_BYTES,
+ bulkCategoryMessage, parseManualViews, imageFileError, MAX_IMAGE_BYTES, trackedSortOf,
} from '../../../../src/features/analytics/tracked/trackedList.ts';
import type { TrackedFilterOptions } from '../../../../src/features/analytics/tracked/trackedList.ts';
import type { TrackedContentItem } from '../../../../../shared/types/domain.ts';
@@ -66,7 +66,7 @@ test('manual views accept whole numbers and clear on empty', () => {
assert.deepEqual(parseManualViews('0'), { value: 0 });
assert.ok(parseManualViews('1.5').error);
assert.ok(parseManualViews('-1').error);
- assert.equal(parseManualViews('abc').error, 'Views must be a whole number of 0 or more.');
+ assert.equal(parseManualViews('abc').error, 'Enter views as a whole number, such as 1200, 1,200 or 1.2K.');
});
test('image checks run in the original order', () => {
@@ -77,3 +77,15 @@ test('image checks run in the original order', () => {
assert.equal(imageFileError(image, true), '');
});
+test('manual views accept separators and K or M suffixes as Reddit insights show them', () => {
+ assert.deepEqual(parseManualViews('12,500'), { value: 12500 });
+ assert.deepEqual(parseManualViews('1 234'), { value: 1234 });
+ assert.deepEqual(parseManualViews('12.5k'), { value: 12500 });
+ assert.deepEqual(parseManualViews('1.2M'), { value: 1200000 });
+ assert.ok(parseManualViews('12.5x').error);
+});
+
+test('a tracked sort from the address that is not an option falls back to newest first', () => {
+ assert.equal(trackedSortOf('views-desc'), 'views-desc');
+ assert.equal(trackedSortOf('title'), 'date-desc');
+});
diff --git a/frontend/tests/features/analytics/videos/videoLibrary.test.ts b/frontend/tests/features/analytics/videos/videoLibrary.test.ts
index 5e1b4c2..b300878 100644
--- a/frontend/tests/features/analytics/videos/videoLibrary.test.ts
+++ b/frontend/tests/features/analytics/videos/videoLibrary.test.ts
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { watchUrl, filterAndSortVideos, videoStatsOf, nextSort, ariaSortOf, videosDescription, mergeChannelVideos } from '../../../../src/features/analytics/videos/videoLibrary.ts';
+import { watchUrl, filterAndSortVideos, videoStatsOf, nextSort, ariaSortOf, videosDescription, mergeChannelVideos, sortFromKey, sortKeyOf } from '../../../../src/features/analytics/videos/videoLibrary.ts';
import type { ChannelVideosResult, LibraryVideo, VideoChannelAccount, VideoQuery } from '../../../../src/features/analytics/videos/videoLibrary.ts';
const videos = [
@@ -70,3 +70,19 @@ test('channel videos merge with their channel and skip failed channels', () => {
assert.equal(merged.videos[1].durationSeconds, 30);
assert.equal(merged.videos[1].engagementRate, '0.00');
});
+
+test('engagement sorts as a number, so 12.34 ranks above 9.50', () => {
+ const videos = [
+ { videoId: 'low', engagementRate: '9.50', channelId: 'c1', viewCount: 1 },
+ { videoId: 'high', engagementRate: '12.34', channelId: 'c1', viewCount: 1 },
+ { videoId: 'mid', engagementRate: '10.00', channelId: 'c1', viewCount: 1 },
+ ] as LibraryVideo[];
+ const sorted = filterAndSortVideos(videos, { channelFilter: 'all', search: '', tier: 'all', sort: { field: 'engagementRate', order: 'desc' } });
+ assert.deepEqual(sorted.map(video => video.videoId), ['high', 'mid', 'low']);
+});
+
+test('a sort round-trips through the address and an unknown one falls back to most viewed', () => {
+ assert.deepEqual(sortFromKey(sortKeyOf({ field: 'publishedAt', order: 'asc' })), { field: 'publishedAt', order: 'asc' });
+ assert.deepEqual(sortFromKey('password:asc'), { field: 'viewCount', order: 'desc' });
+ assert.deepEqual(sortFromKey('viewCount:sideways'), { field: 'viewCount', order: 'desc' });
+});
diff --git a/frontend/tests/lib/libraryResults.test.ts b/frontend/tests/lib/libraryResults.test.ts
new file mode 100644
index 0000000..5b808d7
--- /dev/null
+++ b/frontend/tests/lib/libraryResults.test.ts
@@ -0,0 +1,51 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ failedSources, failureSummary, isStrongEngagement, oldestTime, pageRangeLabel, resultCountLabel, trendTone,
+} from '../../src/lib/library.ts';
+
+test('the page range says which items are on screen', () => {
+ assert.equal(pageRangeLabel({ page: 2, pageCount: 12, total: 300, shown: 25, pageSize: 25, noun: 'videos' }), 'Showing 26 to 50 of 300 videos');
+ assert.equal(pageRangeLabel({ page: 12, pageCount: 12, total: 290, shown: 15, pageSize: 25, noun: 'videos' }), 'Showing 276 to 290 of 290 videos');
+ assert.equal(pageRangeLabel({ page: 1, pageCount: 1, total: 7, shown: 7, pageSize: 25, noun: 'videos' }), '7 videos');
+ assert.equal(pageRangeLabel({ page: 1, pageCount: 1, total: 0, shown: 0, noun: 'videos' }), 'No videos');
+});
+
+test('the result count shows how far a filter narrowed the list', () => {
+ assert.equal(resultCountLabel(12, 340, 'videos'), '12 of 340 videos');
+ assert.equal(resultCountLabel(340, 340, 'videos'), '340 videos');
+});
+
+test('a trend is coloured by what it means, not by its sign', () => {
+ assert.equal(trendTone(12, true), 'good');
+ assert.equal(trendTone(-3, true), 'bad');
+ assert.equal(trendTone(12, false), 'bad');
+ assert.equal(trendTone(0, true), 'neutral');
+});
+
+test('failed requests are named with their reason, in account order', () => {
+ const accounts = [{ id: 'a', title: 'Alpha' }, { id: 'b', title: 'Beta' }, { id: 'c', title: 'Gamma' }];
+ const results: PromiseSettledResult<unknown>[] = [
+ { status: 'fulfilled', value: {} },
+ { status: 'rejected', reason: new Error('quota exceeded') },
+ { status: 'rejected', reason: 'not an error' },
+ ];
+ const failures = failedSources(accounts, results, account => account.title);
+ assert.deepEqual(failures, [
+ { id: 'b', name: 'Beta', message: 'quota exceeded' },
+ { id: 'c', name: 'Gamma', message: 'The request failed' },
+ ]);
+ assert.equal(failureSummary(failures, 3, 'channels'), '2 of 3 channels could not load: Beta (quota exceeded), Gamma (The request failed).');
+ assert.equal(failureSummary([], 3, 'channels'), '');
+});
+
+test('the oldest valid time wins and invalid times are ignored', () => {
+ assert.equal(oldestTime(['2026-11-04T10:00:00Z', 'then', undefined, '2026-11-04T08:00:00Z']), '2026-11-04T08:00:00Z');
+ assert.equal(oldestTime([null, 'then']), null);
+});
+
+test('engagement above 5 percent counts as strong', () => {
+ assert.equal(isStrongEngagement('5.01'), true);
+ assert.equal(isStrongEngagement(5), false);
+ assert.equal(isStrongEngagement(null), false);
+});