Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
refactor(frontend): split docs layout and pages, rename short names
spacesdrivea4fe4b7fb37a
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.mdindex a100f45..c448c58 100644--- a/docs/architecture/frontend/FEATURES.md+++ b/docs/architecture/frontend/FEATURES.md@@ -10,11 +10,15 @@ frontend/src/│ ├── ChartPanel.jsx <- Titled chart container with an empty state│ └── ImageLightbox.jsx <- Thumbnail that opens the full image in a Dialog├── docs/ <- Public documentation at /docs (outside the feature tree: no auth, no AppContext)-│ ├── DocsLayout.jsx <- Header, tabs, sidebar, outline, search, previous and next+│ ├── DocsLayout.jsx <- Page frame: theme, search shortcut, copy page, scroll to hash+│ ├── DocsHeader.jsx, DocsSidebarNav.jsx, DocsMobileNav.jsx, DocsPager.jsx, DocsToc.jsx, DocsSearch.jsx+│ ├── useTableOfContents.js <- Collects page headings and tracks the one in view│ ├── components.jsx <- DocTitle, H2, H3, Callout, Steps, CodeBlock, Table, PathCards, Badge-│ ├── nav.js <- Tabs, groups and pages; the single source for navigation+│ ├── nav.js <- Tabs, groups and pages; the single source for navigation; firstPagePath(tab)│ ├── routes.js <- Slug to lazy page map; nav.test.js checks it matches nav.js│ └── pages/ <- Overview, Use, SelfHost, Reference (one chunk each)+│ ├── use/ <- One file per page plus AdminLink.jsx; Use.jsx re-exports them+│ ├── reference/ <- One file per page; Reference.jsx re-exports them│ └── selfHost/ <- One file per self-hosting page plus selfHostSql.js (selfHostSql.test.js); SelfHost.jsx re-exports them├── features/│ ├── analytics/@@ -46,7 +50,7 @@ frontend/src/│ │ │ ├── redditAnalyticsData.js <- Pure chart rows and stat lists (redditAnalyticsData.test.js)│ │ │ ├── RedditPosts.jsx <- Per-account post explorer│ │ │ ├── RedditPostsAll.jsx <- Global post explorer (all Reddit accounts)-│ │ │ ├── redditPostTable.jsx <- Filters and table shared by both post explorers+│ │ │ ├── RedditPostFilters.jsx, RedditPostTable.jsx <- Filters and table shared by both post explorers│ │ │ └── redditPostUtils.js <- Shared sort options, filtering and sorting│ │ └── tracked/│ │ ├── TrackedContent.jsx <- Page: tracked Reddit posts and YouTube videos@@ -99,8 +103,10 @@ frontend/src/│ │ ├── VideoExplorer.jsx <- Page: YouTube video library with filtering│ │ ├── VideoFilters.jsx, LayoutToggle.jsx, VideoListTable.jsx, VideoSortHeader.jsx, VideoGrid.jsx│ │ ├── useChannelVideos.js <- Loads every channel's videos; shared with Shorts-│ │ └── videoLibrary.js <- Pure filter, sort and totals (videoLibrary.test.js)-│ ├── analytics/shorts/ShortsExplorer.jsx <- YouTube Shorts (60 seconds or less)+│ │ └── videoLibrary.js <- Pure channel merge, filter, sort and totals (videoLibrary.test.js)+│ ├── analytics/shorts/+│ │ ├── ShortsExplorer.jsx <- Page: YouTube Shorts (60 seconds or less)+│ │ └── ShortsFilters.jsx, ShortsGrid.jsx│ └── analytics/reels/│ ├── ReelsExplorer.jsx <- Page: Instagram reels, posts and videos│ ├── ReelsMetrics.jsx, ReelsFilters.jsx, ReelsGrid.jsxdiff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.mdindex d66225a..e9d72d7 100644--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md@@ -103,7 +103,7 @@ frontend/src/channel/ ChannelAnalytics.jsx - per-channel YouTube (page; tabs, hook and helpers beside it)instagram/ InstagramAnalytics.jsx - per-account Instagram (page; sections and helpers beside it)videos/ VideoExplorer.jsx - all videos table (page; filters, table, grid and helpers beside it)- shorts/ ShortsExplorer.jsx - shorts-filtered table+ shorts/ ShortsExplorer.jsx - shorts-filtered grid (page; filters and grid beside it)reels/ ReelsExplorer.jsx - Instagram media grid (page; hook, filters and helpers beside it)reddit/ RedditAnalytics (page; sections and helpers beside it), RedditPosts, RedditPostsAll, shared post tabletracked/ TrackedContent.jsx, TrackedCategory.jsx (pages; components, hooks and helpers beside them)diff --git a/frontend/src/components/ChoiceCard.jsx b/frontend/src/components/ChoiceCard.jsxindex 40e7e96..c436ecd 100644--- a/frontend/src/components/ChoiceCard.jsx+++ b/frontend/src/components/ChoiceCard.jsx@@ -2,7 +2,7 @@ import React from 'react';import { Check } from 'lucide-react';import { cn } from '@/lib/utils';-// Large selectable card for creation flows. Behaves as a radio when `selected` is defined, else as a button.+// a radio when `selected` is defined, otherwise a plain buttonexport default function ChoiceCard({ icon, title, description, selected, onSelect, disabled, className }) {const isRadio = selected !== undefined;return (diff --git a/frontend/src/components/ConfirmDialog.jsx b/frontend/src/components/ConfirmDialog.jsxindex 119b87f..72aeb8a 100644--- a/frontend/src/components/ConfirmDialog.jsx+++ b/frontend/src/components/ConfirmDialog.jsx@@ -7,7 +7,7 @@ import {import { Spinner } from '@/components/ui/spinner';import HoldToConfirmButton from './HoldToConfirmButton';-// Confirmation for consequential actions. Destructive ones use `hold` so they cannot fire on a stray click.+// destructive actions use `hold` so a stray click cannot confirm themexport default function ConfirmDialog({open,onOpenChange,diff --git a/frontend/src/components/DetailPanel.jsx b/frontend/src/components/DetailPanel.jsxindex 14c1b39..69baf42 100644--- a/frontend/src/components/DetailPanel.jsx+++ b/frontend/src/components/DetailPanel.jsx@@ -1,7 +1,7 @@import React from 'react';import { cn } from '@/lib/utils';-// Side panel for a working surface: sticky on wide screens, stacked below the main area on narrow ones.+// sticky on wide screens, stacked below the main area on narrow onesexport default function DetailPanel({ title, description, children, footer, className }) {return (<asidediff --git a/frontend/src/components/SurfaceBox.jsx b/frontend/src/components/SurfaceBox.jsxindex 5d4756f..01b42a3 100644--- a/frontend/src/components/SurfaceBox.jsx+++ b/frontend/src/components/SurfaceBox.jsx@@ -1,7 +1,7 @@import React from 'react';import { cn } from '@/lib/utils';-// The one container for grouped content. A title row is optional; without one the box is a plain panel.+// the one container for grouped content; without a title it is a plain panelexport default function SurfaceBox({children,title,diff --git a/frontend/src/components/brand/Logo.jsx b/frontend/src/components/brand/Logo.jsxindex 6bb2c16..8f917bf 100644--- a/frontend/src/components/brand/Logo.jsx+++ b/frontend/src/components/brand/Logo.jsx@@ -3,8 +3,7 @@ import { cn } from '@/lib/utils';const LOGO_DIR = '/Logos';-// Brand rule: the colour lockup sits on paper, the reversed lockup on dusk. Both are rendered and-// CSS picks one, so the right file shows on first paint without waiting for the theme hook.+// both lockups render and css picks one, so the right file shows before the theme hook runsexport function Logo({ variant = 'lockup', className }) {if (variant === 'wordmark') {return (diff --git a/frontend/src/context/AuthContext.jsx b/frontend/src/context/AuthContext.jsxindex 665a803..727e244 100644--- a/frontend/src/context/AuthContext.jsx+++ b/frontend/src/context/AuthContext.jsx@@ -20,7 +20,7 @@ export function AuthProvider({ children }) {const signUp = (email, password) =>supabase.auth.signUp({ email, password });- // Google's button returns an ID token; the raw nonce lets Supabase confirm the token was issued for this sign-in.+ // the raw nonce lets supabase confirm the google token was issued for this sign-inconst signInWithGoogle = (idToken, nonce) =>supabase.auth.signInWithIdToken({ provider: 'google', token: idToken, nonce });diff --git a/frontend/src/docs/DocsHeader.jsx b/frontend/src/docs/DocsHeader.jsxnew file mode 100644index 0000000..b093409--- /dev/null+++ b/frontend/src/docs/DocsHeader.jsx@@ -0,0 +1,56 @@+import React from 'react';+import { Link } from 'react-router-dom';+import { Menu, Moon, Search, Sun } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Logo } from '@/components/brand/Logo';+import { cn } from '@/lib/utils';+import { DOC_TABS, firstPagePath } from './nav';++export default function DocsHeader({ tab, signedIn, isDark, onToggleTheme, onOpenMenu, onOpenSearch }) {+ return (+ <header className="sticky top-0 z-30 border-b border-line bg-surface/90 backdrop-blur-md">+ <div className="flex h-14 items-center gap-3 px-4 lg:px-6">+ <Button variant="ghost" size="icon-sm" className="lg:hidden" onClick={onOpenMenu} aria-label="Open navigation">+ <Menu />+ </Button>+ <Link to="/docs" className="flex shrink-0 items-center gap-2.5" aria-label="Twiligent documentation home">+ <Logo className="h-6" />+ <span className="hidden border-l border-line pl-2.5 text-sm font-medium text-ink-muted sm:inline">Docs</span>+ </Link>+ <button+ type="button"+ onClick={onOpenSearch}+ aria-label="Search documentation"+ className="ml-auto flex size-9 shrink-0 items-center justify-center gap-2 rounded-field border border-line-control bg-surface text-sm text-ink-faint transition-colors hover:border-line-strong/60 hover:text-ink-muted sm:mx-auto sm:w-full sm:max-w-md sm:shrink sm:justify-start sm:px-3"+ >+ <Search className="size-4 stroke-[1.75]" />+ <span className="hidden flex-1 text-left sm:inline">Search</span>+ <kbd className="hidden rounded-sm border border-line px-1.5 font-mono text-caption sm:inline">/</kbd>+ </button>+ <div className="flex shrink-0 items-center gap-1">+ <Button variant="ghost" size="icon-sm" onClick={onToggleTheme} aria-label={isDark ? 'Switch to light theme' : 'Switch to dark theme'}>+ {isDark ? <Sun /> : <Moon />}+ </Button>+ <Button size="sm" render={<Link to={signedIn ? '/' : '/login'} />}>+ {signedIn ? <>Open<span className="hidden sm:inline"> Twiligent</span></> : 'Sign in'}+ </Button>+ </div>+ </div>+ <nav aria-label="Documentation sections" className="scrollbar-hide flex h-11 items-stretch gap-5 overflow-x-auto px-4 lg:px-6">+ {DOC_TABS.map(docTab => (+ <Link+ key={docTab.id}+ to={firstPagePath(docTab)}+ aria-current={docTab.id === tab.id ? 'page' : undefined}+ className={cn(+ 'relative flex shrink-0 items-center text-sm font-medium transition-colors duration-(--duration-base)',+ docTab.id === tab.id ? 'text-ink after:absolute after:inset-x-0 after:-bottom-px after:h-0.5 after:rounded-full after:bg-brand' : 'text-ink-muted hover:text-ink',+ )}+ >+ {docTab.label}+ </Link>+ ))}+ </nav>+ </header>+ );+}diff --git a/frontend/src/docs/DocsLayout.jsx b/frontend/src/docs/DocsLayout.jsxindex 7e0d7bf..e6c215b 100644--- a/frontend/src/docs/DocsLayout.jsx+++ b/frontend/src/docs/DocsLayout.jsx@@ -1,105 +1,31 @@-import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Link, NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';-import { Search, Sun, Moon, Menu, ArrowUp, ArrowLeft, ArrowRight, Copy, Check, FileText } from 'lucide-react';+import React, { Suspense, useCallback, useEffect, useRef, useState } from 'react';+import { Outlet, useLocation } from 'react-router-dom';+import { Copy, Check } from 'lucide-react';import { Button } from '@/components/ui/button';-import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';-import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';-import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet';import { Skeleton } from '@/components/ui/skeleton';-import { Logo } from '@/components/brand/Logo';import { useSmoothTheme } from '@/hooks/use-smooth-theme';-import { filterCommands, groupCommands } from '@/lib/commandSearch';import { useAuth } from '../context/AuthContext';-import { DOC_TABS, ALL_DOC_PAGES, tabForPath, neighbours } from './nav';-import { cn } from '@/lib/utils';--function SidebarNav({ tab, onNavigate }) {- return (- <nav aria-label={`${tab.label} pages`} className="flex flex-col gap-6">- {tab.groups.map((group, i) => (- <div key={group.label || i} className="flex flex-col gap-0.5">- {group.label && <p className="mb-1 px-2 text-small font-semibold text-ink">{group.label}</p>}- {group.pages.map(page => {- const path = page.slug ? `/docs/${page.slug}` : '/docs';- return (- <NavLink- key={path}- to={path}- end- onClick={onNavigate}- className={({ isActive }) => cn(- 'rounded-row px-2 py-2 text-sm leading-[1.1rem] transition-colors duration-(--duration-base)',- isActive ? 'bg-surface-selected font-medium text-ink' : 'text-ink-muted hover:bg-surface-hover hover:text-ink',- )}- >- {page.title}- </NavLink>- );- })}- </div>- ))}- </nav>- );-}--function DocsSearch({ open, onOpenChange }) {- const navigate = useNavigate();- const [query, setQuery] = useState('');- const commands = useMemo(() => ALL_DOC_PAGES.map(p => ({ id: p.path, label: p.title, group: p.tabLabel, keywords: p.keywords, path: p.path })), []);- const grouped = useMemo(() => groupCommands(filterCommands(commands, query)), [commands, query]);- const close = next => { if (!next) setQuery(''); onOpenChange(next); };- return (- <Dialog open={open} onOpenChange={close}>- <DialogContent showCloseButton={false} className="top-[18%] translate-y-0 gap-0 overflow-hidden p-0 sm:max-w-xl">- <DialogTitle className="sr-only">Search the documentation</DialogTitle>- <DialogDescription className="sr-only">Find a page by title or topic</DialogDescription>- <Command shouldFilter={false} loop>- <CommandInput value={query} onValueChange={setQuery} placeholder="Search the docs, for example Instagram tester" />- <CommandList>- <CommandEmpty>No pages match "{query}"</CommandEmpty>- {grouped.map(({ group, items }) => (- <CommandGroup key={group} heading={group}>- {items.map(item => (- <CommandItem key={item.id} value={item.id} onSelect={() => { close(false); navigate(item.path); }}>- <FileText />- {item.label}- </CommandItem>- ))}- </CommandGroup>- ))}- </CommandList>- </Command>- </DialogContent>- </Dialog>- );-}--function useTableOfContents(articleRef, pathname) {- const [items, setItems] = useState([]);- const [active, setActive] = useState(null);-+import { tabForPath, neighbours } from './nav';+import { useTableOfContents } from './useTableOfContents';+import DocsHeader from './DocsHeader';+import DocsSidebarNav from './DocsSidebarNav';+import DocsPager from './DocsPager';+import DocsToc from './DocsToc';+import DocsMobileNav from './DocsMobileNav';+import DocsSearch from './DocsSearch';++function useSearchShortcut(setSearchOpen) {useEffect(() => {- const article = articleRef.current;- if (!article) return undefined;- const collect = () => {- const headings = [...article.querySelectorAll('[data-toc]')];- setItems(headings.map(h => ({ id: h.id, text: h.textContent, level: Number(h.dataset.toc) })));- return headings;+ const onKey = e => {+ const typing = /input|textarea|select/i.test(e.target.tagName) || e.target.isContentEditable;+ if ((e.key === '/' && !typing) || ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k')) {+ e.preventDefault();+ setSearchOpen(true);+ }};- let headings = collect();- // Pages are lazy-loaded, so headings can appear after the first render- const mutations = new MutationObserver(() => { headings = collect(); observeAll(); });- const spy = new IntersectionObserver(entries => {- const visible = entries.filter(e => e.isIntersecting).sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);- if (visible[0]) setActive(visible[0].target.id);- }, { rootMargin: '-120px 0px -65% 0px' });- function observeAll() { spy.disconnect(); headings.forEach(h => spy.observe(h)); }- observeAll();- mutations.observe(article, { childList: true, subtree: true });- return () => { mutations.disconnect(); spy.disconnect(); };- }, [articleRef, pathname]);-- return { items, active };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [setSearchOpen]);}export default function DocsLayout() {@@ -120,17 +46,7 @@ export default function DocsLayout() {else document.getElementById(location.hash.slice(1))?.scrollIntoView();}, [location.pathname, location.hash]);- useEffect(() => {- const onKey = e => {- const typing = /input|textarea|select/i.test(e.target.tagName) || e.target.isContentEditable;- if ((e.key === '/' && !typing) || ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k')) {- e.preventDefault();- setSearchOpen(true);- }- };- window.addEventListener('keydown', onKey);- return () => window.removeEventListener('keydown', onKey);- }, []);+ useSearchShortcut(setSearchOpen);const copyPage = useCallback(async () => {try {@@ -142,63 +58,22 @@ export default function DocsLayout() {}}, []);- const firstPathOf = t => {- const page = t.groups[0].pages[0];- return page.slug ? `/docs/${page.slug}` : '/docs';- };-return (<div className="min-h-svh bg-surface text-ink"><a href="#docs-content" className="sr-only focus:not-sr-only focus:fixed focus:top-3 focus:left-3 focus:z-50 focus:rounded-control focus:bg-ink focus:px-4 focus:py-2 focus:text-sm focus:text-ink-inverse">Skip to content</a>- <header className="sticky top-0 z-30 border-b border-line bg-surface/90 backdrop-blur-md">- <div className="flex h-14 items-center gap-3 px-4 lg:px-6">- <Button variant="ghost" size="icon-sm" className="lg:hidden" onClick={() => setMenuOpen(true)} aria-label="Open navigation">- <Menu />- </Button>- <Link to="/docs" className="flex shrink-0 items-center gap-2.5" aria-label="Twiligent documentation home">- <Logo className="h-6" />- <span className="hidden border-l border-line pl-2.5 text-sm font-medium text-ink-muted sm:inline">Docs</span>- </Link>- <button- type="button"- onClick={() => setSearchOpen(true)}- aria-label="Search documentation"- className="ml-auto flex size-9 shrink-0 items-center justify-center gap-2 rounded-field border border-line-control bg-surface text-sm text-ink-faint transition-colors hover:border-line-strong/60 hover:text-ink-muted sm:mx-auto sm:w-full sm:max-w-md sm:shrink sm:justify-start sm:px-3"- >- <Search className="size-4 stroke-[1.75]" />- <span className="hidden flex-1 text-left sm:inline">Search</span>- <kbd className="hidden rounded-sm border border-line px-1.5 font-mono text-caption sm:inline">/</kbd>- </button>- <div className="flex shrink-0 items-center gap-1">- <Button variant="ghost" size="icon-sm" onClick={() => setTheme(isDark ? 'light' : 'dark')} aria-label={isDark ? 'Switch to light theme' : 'Switch to dark theme'}>- {isDark ? <Sun /> : <Moon />}- </Button>- <Button size="sm" render={<Link to={session ? '/' : '/login'} />}>- {session ? <>Open<span className="hidden sm:inline"> Twiligent</span></> : 'Sign in'}- </Button>- </div>- </div>- <nav aria-label="Documentation sections" className="scrollbar-hide flex h-11 items-stretch gap-5 overflow-x-auto px-4 lg:px-6">- {DOC_TABS.map(t => (- <Link- key={t.id}- to={firstPathOf(t)}- aria-current={t.id === tab.id ? 'page' : undefined}- className={cn(- 'relative flex shrink-0 items-center text-sm font-medium transition-colors duration-(--duration-base)',- t.id === tab.id ? 'text-ink after:absolute after:inset-x-0 after:-bottom-px after:h-0.5 after:rounded-full after:bg-brand' : 'text-ink-muted hover:text-ink',- )}- >- {t.label}- </Link>- ))}- </nav>- </header>+ <DocsHeader+ tab={tab}+ signedIn={Boolean(session)}+ isDark={isDark}+ onToggleTheme={() => setTheme(isDark ? 'light' : 'dark')}+ onOpenMenu={() => setMenuOpen(true)}+ onOpenSearch={() => setSearchOpen(true)}+ /><div className="mx-auto flex max-w-[96rem]"><aside className="sticky top-[6.25rem] hidden h-[calc(100svh-6.25rem)] w-64 shrink-0 overflow-y-auto border-r border-line px-4 py-6 lg:block">- <SidebarNav tab={tab} />+ <DocsSidebarNav tab={tab} /></aside><main id="docs-content" className="min-w-0 flex-1 px-5 py-10 sm:px-8 lg:px-12">@@ -216,65 +91,16 @@ export default function DocsLayout() {</Suspense></article>- <nav aria-label="Previous and next page" className="mt-16 grid grid-cols-1 gap-3 border-t border-line pt-8 sm:grid-cols-2">- {prev ? (- <Link to={prev.path} className="group flex flex-col gap-1 rounded-card border border-line p-4 transition-colors hover:border-line-strong/50">- <span className="flex items-center gap-1 text-caption text-ink-faint"><ArrowLeft className="size-3.5" />Previous</span>- <span className="text-sm font-medium text-ink">{prev.title}</span>- </Link>- ) : <span />}- {next && (- <Link to={next.path} className="group flex flex-col items-end gap-1 rounded-card border border-line p-4 text-right transition-colors hover:border-line-strong/50">- <span className="flex items-center gap-1 text-caption text-ink-faint">Next<ArrowRight className="size-3.5" /></span>- <span className="text-sm font-medium text-ink">{next.title}</span>- </Link>- )}- </nav>+ <DocsPager prev={prev} next={next} /></div></main><aside className="sticky top-[6.25rem] hidden h-[calc(100svh-6.25rem)] w-60 shrink-0 overflow-y-auto py-10 pr-6 xl:block">- {toc.length > 0 && (- <nav aria-label="On this page" className="flex flex-col gap-3">- <p className="text-sm font-medium text-ink-muted">On this page</p>- <ul className="flex flex-col border-l border-line">- {toc.map(item => (- <li key={item.id}>- <a- href={`#${item.id}`}- onClick={e => { e.preventDefault(); document.getElementById(item.id)?.scrollIntoView({ behavior: 'smooth' }); history.replaceState(null, '', `#${item.id}`); }}- className={cn(- '-ml-px block border-l py-1 text-sm leading-5 transition-colors duration-(--duration-base)',- item.level === 3 ? 'pl-6' : 'pl-3',- active === item.id ? 'border-brand text-ink' : 'border-transparent text-ink-faint hover:text-ink',- )}- >- {item.text}- </a>- </li>- ))}- </ul>- <button type="button" onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })} className="mt-3 flex w-fit items-center gap-1.5 border-t border-line pt-4 text-sm text-ink-faint transition-colors hover:text-ink">- Scroll to top <ArrowUp className="size-3.5" />- </button>- </nav>- )}+ <DocsToc items={toc} active={active} /></aside></div>- <Sheet open={menuOpen} onOpenChange={setMenuOpen}>- <SheetContent side="left" className="w-72 overflow-y-auto p-5">- <SheetTitle className="sr-only">Documentation navigation</SheetTitle>- <div className="mb-6 flex flex-col gap-1">- {DOC_TABS.map(t => (- <Link key={t.id} to={firstPathOf(t)} onClick={() => setMenuOpen(false)} className={cn('rounded-row px-2 py-1.5 text-sm font-medium', t.id === tab.id ? 'text-ink' : 'text-ink-muted')}>- {t.label}- </Link>- ))}- </div>- <SidebarNav tab={tab} onNavigate={() => setMenuOpen(false)} />- </SheetContent>- </Sheet>+ <DocsMobileNav tab={tab} open={menuOpen} onOpenChange={setMenuOpen} /><DocsSearch open={searchOpen} onOpenChange={setSearchOpen} /></div>diff --git a/frontend/src/docs/DocsMobileNav.jsx b/frontend/src/docs/DocsMobileNav.jsxnew file mode 100644index 0000000..b150545--- /dev/null+++ b/frontend/src/docs/DocsMobileNav.jsx@@ -0,0 +1,25 @@+import React from 'react';+import { Link } from 'react-router-dom';+import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet';+import { cn } from '@/lib/utils';+import { DOC_TABS, firstPagePath } from './nav';+import DocsSidebarNav from './DocsSidebarNav';++export default function DocsMobileNav({ tab, open, onOpenChange }) {+ const close = () => onOpenChange(false);+ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent side="left" className="w-72 overflow-y-auto p-5">+ <SheetTitle className="sr-only">Documentation navigation</SheetTitle>+ <div className="mb-6 flex flex-col gap-1">+ {DOC_TABS.map(docTab => (+ <Link key={docTab.id} to={firstPagePath(docTab)} onClick={close} className={cn('rounded-row px-2 py-1.5 text-sm font-medium', docTab.id === tab.id ? 'text-ink' : 'text-ink-muted')}>+ {docTab.label}+ </Link>+ ))}+ </div>+ <DocsSidebarNav tab={tab} onNavigate={close} />+ </SheetContent>+ </Sheet>+ );+}diff --git a/frontend/src/docs/DocsPager.jsx b/frontend/src/docs/DocsPager.jsxnew file mode 100644index 0000000..6a5ae72--- /dev/null+++ b/frontend/src/docs/DocsPager.jsx@@ -0,0 +1,22 @@+import React from 'react';+import { Link } from 'react-router-dom';+import { ArrowLeft, ArrowRight } from 'lucide-react';++export default function DocsPager({ prev, next }) {+ return (+ <nav aria-label="Previous and next page" className="mt-16 grid grid-cols-1 gap-3 border-t border-line pt-8 sm:grid-cols-2">+ {prev ? (+ <Link to={prev.path} className="group flex flex-col gap-1 rounded-card border border-line p-4 transition-colors hover:border-line-strong/50">+ <span className="flex items-center gap-1 text-caption text-ink-faint"><ArrowLeft className="size-3.5" />Previous</span>+ <span className="text-sm font-medium text-ink">{prev.title}</span>+ </Link>+ ) : <span />}+ {next && (+ <Link to={next.path} className="group flex flex-col items-end gap-1 rounded-card border border-line p-4 text-right transition-colors hover:border-line-strong/50">+ <span className="flex items-center gap-1 text-caption text-ink-faint">Next<ArrowRight className="size-3.5" /></span>+ <span className="text-sm font-medium text-ink">{next.title}</span>+ </Link>+ )}+ </nav>+ );+}diff --git a/frontend/src/docs/DocsSearch.jsx b/frontend/src/docs/DocsSearch.jsxnew file mode 100644index 0000000..2954a76--- /dev/null+++ b/frontend/src/docs/DocsSearch.jsx@@ -0,0 +1,39 @@+import React, { useMemo, useState } from 'react';+import { useNavigate } from 'react-router-dom';+import { FileText } from 'lucide-react';+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';+import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';+import { filterCommands, groupCommands } from '@/lib/commandSearch';+import { ALL_DOC_PAGES } from './nav';++export default function DocsSearch({ open, onOpenChange }) {+ const navigate = useNavigate();+ const [query, setQuery] = useState('');+ const commands = useMemo(() => ALL_DOC_PAGES.map(page => ({ id: page.path, label: page.title, group: page.tabLabel, keywords: page.keywords, path: page.path })), []);+ const grouped = useMemo(() => groupCommands(filterCommands(commands, query)), [commands, query]);+ const close = next => { if (!next) setQuery(''); onOpenChange(next); };+ return (+ <Dialog open={open} onOpenChange={close}>+ <DialogContent showCloseButton={false} className="top-[18%] translate-y-0 gap-0 overflow-hidden p-0 sm:max-w-xl">+ <DialogTitle className="sr-only">Search the documentation</DialogTitle>+ <DialogDescription className="sr-only">Find a page by title or topic</DialogDescription>+ <Command shouldFilter={false} loop>+ <CommandInput value={query} onValueChange={setQuery} placeholder="Search the docs, for example Instagram tester" />+ <CommandList>+ <CommandEmpty>No pages match "{query}"</CommandEmpty>+ {grouped.map(({ group, items }) => (+ <CommandGroup key={group} heading={group}>+ {items.map(item => (+ <CommandItem key={item.id} value={item.id} onSelect={() => { close(false); navigate(item.path); }}>+ <FileText />+ {item.label}+ </CommandItem>+ ))}+ </CommandGroup>+ ))}+ </CommandList>+ </Command>+ </DialogContent>+ </Dialog>+ );+}diff --git a/frontend/src/docs/DocsSidebarNav.jsx b/frontend/src/docs/DocsSidebarNav.jsxnew file mode 100644index 0000000..ebb74d2--- /dev/null+++ b/frontend/src/docs/DocsSidebarNav.jsx@@ -0,0 +1,32 @@+import React from 'react';+import { NavLink } from 'react-router-dom';+import { cn } from '@/lib/utils';++export default function DocsSidebarNav({ tab, onNavigate }) {+ return (+ <nav aria-label={`${tab.label} pages`} className="flex flex-col gap-6">+ {tab.groups.map((group, i) => (+ <div key={group.label || i} className="flex flex-col gap-0.5">+ {group.label && <p className="mb-1 px-2 text-small font-semibold text-ink">{group.label}</p>}+ {group.pages.map(page => {+ const path = page.slug ? `/docs/${page.slug}` : '/docs';+ return (+ <NavLink+ key={path}+ to={path}+ end+ onClick={onNavigate}+ className={({ isActive }) => cn(+ 'rounded-row px-2 py-2 text-sm leading-[1.1rem] transition-colors duration-(--duration-base)',+ isActive ? 'bg-surface-selected font-medium text-ink' : 'text-ink-muted hover:bg-surface-hover hover:text-ink',+ )}+ >+ {page.title}+ </NavLink>+ );+ })}+ </div>+ ))}+ </nav>+ );+}diff --git a/frontend/src/docs/DocsToc.jsx b/frontend/src/docs/DocsToc.jsxnew file mode 100644index 0000000..7db10b9--- /dev/null+++ b/frontend/src/docs/DocsToc.jsx@@ -0,0 +1,38 @@+import React from 'react';+import { ArrowUp } from 'lucide-react';+import { cn } from '@/lib/utils';++function jumpTo(e, id) {+ e.preventDefault();+ document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' });+ history.replaceState(null, '', `#${id}`);+}++export default function DocsToc({ items, active }) {+ if (items.length === 0) return null;+ return (+ <nav aria-label="On this page" className="flex flex-col gap-3">+ <p className="text-sm font-medium text-ink-muted">On this page</p>+ <ul className="flex flex-col border-l border-line">+ {items.map(item => (+ <li key={item.id}>+ <a+ href={`#${item.id}`}+ onClick={e => jumpTo(e, item.id)}+ className={cn(+ '-ml-px block border-l py-1 text-sm leading-5 transition-colors duration-(--duration-base)',+ item.level === 3 ? 'pl-6' : 'pl-3',+ active === item.id ? 'border-brand text-ink' : 'border-transparent text-ink-faint hover:text-ink',+ )}+ >+ {item.text}+ </a>+ </li>+ ))}+ </ul>+ <button type="button" onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })} className="mt-3 flex w-fit items-center gap-1.5 border-t border-line pt-4 text-sm text-ink-faint transition-colors hover:text-ink">+ Scroll to top <ArrowUp className="size-3.5" />+ </button>+ </nav>+ );+}diff --git a/frontend/src/docs/components.jsx b/frontend/src/docs/components.jsxindex c20d746..cff5e85 100644--- a/frontend/src/docs/components.jsx+++ b/frontend/src/docs/components.jsx@@ -68,13 +68,13 @@ const CALLOUTS = {};export function Callout({ type = 'note', title, children }) {- const c = CALLOUTS[type];- const Icon = c.icon;+ const callout = CALLOUTS[type];+ const Icon = callout.icon;return (- <div className={cn('my-6 flex gap-3 rounded-field border px-4 py-3.5', c.cls)}>- <Icon className={cn('mt-0.5 size-4 shrink-0 stroke-[1.75]', c.iconCls)} aria-hidden="true" />+ <div className={cn('my-6 flex gap-3 rounded-field border px-4 py-3.5', callout.cls)}>+ <Icon className={cn('mt-0.5 size-4 shrink-0 stroke-[1.75]', callout.iconCls)} aria-hidden="true" /><div className="flex min-w-0 flex-col gap-1 text-[0.9375rem] leading-6 text-ink-muted [&_strong]:font-semibold [&_strong]:text-ink">- <p className="font-semibold text-ink"><span className="sr-only">{c.label}: </span>{title}</p>+ <p className="font-semibold text-ink"><span className="sr-only">{callout.label}: </span>{title}</p>{children && <div className="[&>p]:m-0 flex flex-col gap-2">{children}</div>}</div></div>diff --git a/frontend/src/docs/nav.js b/frontend/src/docs/nav.jsindex 9adc5fa..38c2d88 100644--- a/frontend/src/docs/nav.js+++ b/frontend/src/docs/nav.js@@ -1,4 +1,4 @@-// Documentation structure: tabs, sidebar groups, and pages. Page components are mapped in pages/index.js.+// tabs, sidebar groups and pages; routes.js maps each page to its componentexport const DOC_TABS = [{@@ -106,3 +106,8 @@ export function neighbours(pathname) {const i = ALL_DOC_PAGES.findIndex(p => p.path === pathname);return { prev: i > 0 ? ALL_DOC_PAGES[i - 1] : null, next: i >= 0 && i < ALL_DOC_PAGES.length - 1 ? ALL_DOC_PAGES[i + 1] : null };}++export function firstPagePath(tab) {+ const page = tab.groups[0].pages[0];+ return page.slug ? `/docs/${page.slug}` : '/docs';+}diff --git a/frontend/src/docs/pages/Reference.jsx b/frontend/src/docs/pages/Reference.jsxindex 78b46ef..0c37b52 100644--- a/frontend/src/docs/pages/Reference.jsx+++ b/frontend/src/docs/pages/Reference.jsx@@ -1,182 +1,5 @@-import React from 'react';-import { DocTitle, H2, H3, P, UL, A, Code, Callout, Table, Badge } from '../components';--const BACKEND_VARS = [- ['SUPABASE_URL', 'required', false, 'Supabase, Project Settings, Data API', 'Which database the Worker talks to.'],- ['SUPABASE_SERVICE_KEY', 'required', true, 'Supabase, Project Settings, API Keys, secret key (legacy: service_role)', 'Reads and writes all tables on behalf of members.'],- ['SUPABASE_ANON_KEY', 'required', false, 'Supabase, Project Settings, API Keys, publishable key (legacy: anon)', 'Checks that a sign-in token is genuine.'],- ['YOUTUBE_API_KEY', 'youtube', true, 'Google Cloud, APIs and Services, Credentials', 'Every YouTube read.'],- ['INSTAGRAM_APP_ID', 'instagram', false, 'Meta app, Instagram, API setup with Instagram business login', 'Starts Instagram sign-in.'],- ['INSTAGRAM_APP_SECRET', 'instagram', true, 'Same page as the app ID', 'Exchanges and renews Instagram access tokens.'],- ['CLOUDINARY_CLOUD_NAME', 'publishing', false, 'Cloudinary dashboard', 'Where uploaded media goes.'],- ['CLOUDINARY_UPLOAD_PRESET', 'publishing', false, 'Cloudinary, Settings, Upload, Upload presets (unsigned)', 'Lets browsers upload without the Cloudinary API secret.'],- ['BACKEND_URL', 'instagram', false, 'Your Worker address, no trailing slash', 'Builds the Instagram redirect URI.'],- ['FRONTEND_URL', 'instagram', false, 'Your Pages address', 'Where members land after Instagram sign-in.'],- ['UPSTASH_REDIS_REST_URL', 'optional', false, 'Upstash database, REST API', 'Cache address.'],- ['UPSTASH_REDIS_REST_TOKEN', 'optional', true, 'Upstash database, REST API', 'Cache password.'],-];--const FRONTEND_VARS = [- ['VITE_SUPABASE_URL', 'required', 'Same as SUPABASE_URL.'],- ['VITE_SUPABASE_ANON_KEY', 'required', 'The publishable key. Never the secret key.'],- ['VITE_API_URL', 'required', 'Backend URL plus /api, for example https://twiligent.you.workers.dev/api. Defaults to http://localhost:8787/api in development.'],- ['VITE_ADMIN_EMAIL', 'optional', 'Where members are told to write for Instagram tester access or help.'],- ['VITE_GOOGLE_CLIENT_ID', 'optional', 'Web client ID from Google Auth Platform. Shows the Sign in with Google button; leave unset to hide it.'],-];--const NEED = {- required: <Badge tone="required">Required</Badge>,- youtube: <Badge tone="optional">For YouTube</Badge>,- instagram: <Badge tone="optional">For Instagram</Badge>,- publishing: <Badge tone="optional">For publishing</Badge>,- optional: <Badge tone="optional">Optional</Badge>,-};--export function Environment() {- return (- <>- <DocTitle title="Environment variables" lead="Every value Twiligent reads, where it comes from, and where it goes." />-- <Callout type="note" title="Members can skip this page">- <p>Only the administrator of an instance sets these. If you sign in to someone else's Twiligent, nothing here applies to you.</p>- </Callout>-- <H2>Backend (Cloudflare Worker)</H2>- <P>Set each one with <Code>npx wrangler secret put NAME</Code> in <Code>backend/</Code>. For local development, put them in <Code>backend/.dev.vars</Code>, which Git ignores. See <A to="/docs/self-host/deploy-backend">Deploy the backend</A>.</P>- <Table- head={['Name', 'Needed', 'Where to get it', 'Used for']}- rows={BACKEND_VARS.map(([name, need, secret, from, use]) => [- <span className="inline-flex flex-col gap-1"><Code>{name}</Code>{secret && <Badge tone="secret">Secret</Badge>}</span>,- NEED[need],- from,- use,- ])}- />- <P>Platform keys are shared by every member of the instance. Missing ones only switch off that platform: Settings shows which are set, and members see a clear message instead of an error.</P>-- <H2>Frontend (Cloudflare Pages)</H2>- <P>Set these in <Code>frontend/.env</Code> before <Code>npm run build</Code>, or as GitHub secrets when the deploy workflow builds for you. They are built into the site and are public.</P>- <Table- head={['Name', 'Needed', 'Value']}- rows={FRONTEND_VARS.map(([name, need, value]) => [<Code>{name}</Code>, NEED[need], value])}- />-- <H2>GitHub Actions secrets</H2>- <Table- head={['Name', 'Used by']}- rows={[- [<Code>CLOUDFLARE_API_TOKEN</Code>, 'Both deploy workflows'],- [<Code>CLOUDFLARE_ACCOUNT_ID</Code>, 'Both deploy workflows'],- [<><Code>VITE_SUPABASE_URL</Code>, <Code>VITE_SUPABASE_ANON_KEY</Code>, <Code>VITE_API_URL</Code>, <Code>VITE_ADMIN_EMAIL</Code>, <Code>VITE_GOOGLE_CLIENT_ID</Code></>, 'Frontend deploy workflow'],- [<><Code>SUPABASE_URL</Code>, <Code>SUPABASE_SERVICE_KEY</Code></>, 'Backup scheduler (publish-scheduled.yml)'],- ]}- />-- <H2>Not needed</H2>- <UL>- <li><Code>REDDIT_ENCRYPTION_KEY</Code> appears in older notes but is no longer read. Reddit cookies are stored server-side and never returned to the browser.</li>- <li>A GitHub personal access token. Earlier versions asked for one in Settings; it was never used and has been removed.</li>- <li>A Reddit API key. Members use their own session cookie.</li>- </UL>- </>- );-}--export function Scheduling() {- return (- <>- <DocTitle title="How scheduling works" lead="What happens between choosing Schedule post and the post going live." />-- <H2>For members</H2>- <P>Nothing to set up. Pick a time, choose <strong>Schedule post</strong>, and close the browser if you like. The server publishes the post within 15 minutes after the time you picked.</P>-- <H2>For administrators</H2>- <P>Deploying the backend is all that is required. The Worker's cron trigger runs every 15 minutes and publishes every post that is due. The GitHub workflow is an optional second runner for extra reliability.</P>-- <H3>The lifecycle of a post</H3>- <Table- head={['Step', 'Status', 'What happens']}- rows={[- ['1', <Badge>pending</Badge>, 'The file is on Cloudinary and the post is saved with its time.'],- ['2', <Badge>publishing</Badge>, 'A scheduler claims the post. Only one scheduler can claim it, so it is published once.'],- ['3', <Badge>published</Badge>, 'Instagram accepted it. The Instagram media ID is saved.'],- ['3', <Badge>failed</Badge>, 'Instagram rejected it. The reason is saved and shown in the Error column.'],- ]}- />-- <H3>Two schedulers, one post</H3>- <P>Both schedulers claim a post by changing it from <Code>pending</Code> to <Code>publishing</Code> in a single database update that only succeeds while it is still pending. Whichever arrives second finds nothing to claim and skips it.</P>-- <H3>When posts stay pending</H3>- <UL>- <li>The Worker was never deployed, or its cron triggers were removed. Check <strong>Triggers</strong> on the Worker in the Cloudflare dashboard.</li>- <li><Code>SUPABASE_SERVICE_KEY</Code> or <Code>SUPABASE_URL</Code> is wrong on the Worker.</li>- <li>The connected Instagram account's access was removed. Reconnect it.</li>- </UL>- <P>Twiligent warns members when a post is more than 30 minutes overdue and tells them to contact the administrator.</P>- </>- );-}--export function Security() {- return (- <>- <DocTitle title="Security" lead="How member data is kept apart, and the settings an administrator must get right." />-- <H2>What members can rely on</H2>- <UL>- <li>Other members cannot see your accounts, scheduled posts or tracked content.</li>- <li>Instagram access tokens and Reddit cookies are stored on the server and never sent to any browser, including yours.</li>- <li>No member, including you, ever handles the instance's API keys.</li>- </UL>-- <H2>How isolation works</H2>- <P>The browser signs in with Supabase and sends its token with every request. The Worker verifies the token and takes the member's ID from it, never from anything the browser sends. Every database query is limited to that ID. Responses are stripped of tokens and cookies before they leave the Worker.</P>-- <H2>Administrator responsibilities</H2>- <Table- head={['Setting', 'Why it matters']}- rows={[- ['Row level security on all four tables', 'The publishable key ships in the website. With security off, anyone could use it to read every table directly.'],- ['Secret key only in server secrets', 'It bypasses all database rules. Keep it in Worker secrets and GitHub Actions secrets only.'],- ['Signups', 'Supabase allows anyone with the address to sign up. Turn signups off for a private instance.'],- ['backend/.dev.vars never committed', 'It holds every secret for local development.'],- ['Instagram testers', 'In development mode, only people you add can connect Instagram.'],- ]}- />- <P>The SQL to turn on row level security is on the <A to="/docs/self-host/supabase">Supabase</A> page.</P>- </>- );-}--export function FAQ() {- return (- <>- <DocTitle title="FAQ" lead="Short answers to the questions people ask most." />-- <H3>Do I need GitHub to schedule posts?</H3>- <P>No. Members never do. Administrators only need the deployed Worker; the GitHub workflow is an optional backup.</P>-- <H3>Do I need my own Supabase project?</H3>- <P>Only if you run your own instance. Members of someone else's instance use theirs.</P>-- <H3>Why can't I connect my Instagram account?</H3>- <P>It must be a Business or Creator account, and while the instance's Meta app is in development mode it must be added as a tester. See <A to="/docs/use/connect-accounts">Connect your accounts</A>.</P>-- <H3>Can I connect a YouTube channel I do not own?</H3>- <P>Yes. YouTube analytics use public data, so any public channel works.</P>-- <H3>Does Twiligent publish to YouTube or Reddit?</H3>- <P>No. Publishing is Instagram only. YouTube and Reddit are analytics only.</P>-- <H3>What does running an instance cost?</H3>- <P>For a small team, nothing. Supabase, Cloudflare, Cloudinary and Upstash free plans cover typical use, and the YouTube and Instagram APIs are free.</P>-- <H3>How fresh is the data?</H3>- <P>Data is fetched when you open a page or choose Refresh, and cached for a short time when Redis is set up. Instagram tokens are renewed nightly.</P>-- <H3>Who do I contact for help?</H3>- <P>The administrator of your instance. Their address is on the <A to="/docs/use/troubleshooting">Troubleshooting</A> page.</P>- </>- );-}+// each page lives in reference/; this barrel keeps them in one lazy chunk for routes.js+export { default as Environment } from './reference/Environment';+export { default as Scheduling } from './reference/Scheduling';+export { default as Security } from './reference/Security';+export { default as FAQ } from './reference/FAQ';diff --git a/frontend/src/docs/pages/Use.jsx b/frontend/src/docs/pages/Use.jsxindex 133af7e..0829e68 100644--- a/frontend/src/docs/pages/Use.jsx+++ b/frontend/src/docs/pages/Use.jsx@@ -1,207 +1,7 @@-import React from 'react';-import { ADMIN_EMAIL, adminMailto, INSTAGRAM_TESTER_INVITES_URL } from '@/lib/contact';-import { DocTitle, H2, H3, P, UL, OL, A, Code, Callout, Steps, Step, Table } from '../components';--function AdminLink({ subject }) {- return <A href={adminMailto(subject)}>{ADMIN_EMAIL}</A>;-}--export function GettingStarted() {- return (- <>- <DocTitle title="Sign in and first steps" lead="Everything a member does in the first ten minutes. No installation or setup needed." />-- <Callout type="note" title="This guide is for members">- <p>You are a member if someone gave you a Twiligent link to sign in to. The server, keys and scheduling are already handled by the administrator.</p>- </Callout>-- <Steps>- <Step title="Create your account">- <P>Open your instance's link and choose <strong>Continue with Google</strong>, if your instance offers it. Otherwise choose <strong>Create an account</strong> and use your email and a password of at least 6 characters, then sign in. If you sign in with Google using the same email as an existing account, both open the same account.</P>- </Step>- <Step title="Connect an account">- <P>Open <strong>Accounts</strong> in the sidebar and choose <strong>Add account</strong>. Pick YouTube, Instagram or Reddit. Each one is explained in <A to="/docs/use/connect-accounts">Connect your accounts</A>.</P>- </Step>- <Step title="Look around">- <P>The <strong>Overview</strong> fills in within a minute or two. Use the search box at the top of the sidebar, or press <Code>Ctrl K</Code> (<Code>Cmd K</Code> on a Mac), to jump to any page or account.</P>- </Step>- <Step title="Choose a theme">- <P>Twiligent has a light and a dark theme. Switch with the sun or moon button at the top right, or pick <strong>Match system</strong> in Settings.</P>- </Step>- </Steps>-- <H2>Where things are</H2>- <Table- head={['Page', 'Use it to']}- rows={[- [<strong>Overview</strong>, 'See audience, views, content, comments and likes across every account.'],- [<strong>Videos, Shorts</strong>, 'Browse and sort every video from your YouTube channels.'],- [<strong>Instagram content</strong>, 'Browse reels, posts and videos with views, likes and comments.'],- [<strong>Reddit posts</strong>, 'See every post from your Reddit accounts with karma and comments.'],- [<strong>Tracked content</strong>, 'Follow specific Reddit posts and YouTube videos by link.'],- [<strong>Publish</strong>, 'Post or schedule to Instagram.'],- [<strong>Accounts</strong>, 'Add, refresh and remove connected accounts.'],- [<strong>Settings</strong>, 'Theme, server status and setup guides.'],- ]}- />- </>- );-}--export function ConnectAccounts() {- return (- <>- <DocTitle title="Connect your accounts" lead="How to add YouTube channels, Instagram professional accounts and Reddit profiles." />-- <H2>YouTube</H2>- <P>Open <strong>Accounts</strong>, choose <strong>Add account</strong>, then <strong>YouTube channel</strong>. Paste a channel link, an <Code>@handle</Code> or a channel ID starting with <Code>UC</Code>, choose <strong>Find</strong> to check it, then <strong>Add channel</strong>. Any public channel works; you do not need to own it.</P>-- <H2>Instagram</H2>- <P>Instagram only connects <strong>Business</strong> or <strong>Creator</strong> accounts. You can switch a personal account to a professional one for free in the Instagram app under Settings, Account type and tools.</P>-- <H3>Get tester access first</H3>- <P>Most instances run their Meta app in development mode. In that mode Instagram only lets accounts added as <strong>testers</strong> sign in. Without tester access, Instagram shows an error or a blank page.</P>- <Steps>- <Step title="Ask the administrator">- <P>Email <AdminLink subject="Instagram tester request for Twiligent" /> with your Instagram username. The administrator adds you in the Meta app dashboard.</P>- </Step>- <Step title="Accept the invite">- <P>Sign in to Instagram on the web and open <A href={INSTAGRAM_TESTER_INVITES_URL}>Apps and websites</A>, then the <strong>Tester invites</strong> tab, and accept the invite. In the Instagram app it is under Settings and privacy, Website permissions, Apps and websites, Tester invites.</P>- </Step>- <Step title="Connect">- <P>In Twiligent, open <strong>Accounts</strong>, choose <strong>Add account</strong>, then <strong>Instagram account</strong>, then <strong>Continue to Instagram</strong>. Approve every requested permission. Instagram sends you back and the account appears in the list.</P>- </Step>- </Steps>- <Callout type="note" title="Access lasts 60 days and renews itself">- <p>Instagram access tokens last 60 days. Twiligent renews them automatically every night, so you only reconnect if you remove access in Instagram or change your password.</p>- </Callout>-- <H2>Reddit</H2>- <P>Reddit blocks most requests from servers, so Twiligent uses your browser session cookie to read your profile and posts.</P>- <OL>- <li>Sign in to reddit.com in your browser.</li>- <li>Open the browser's developer tools (F12), then <strong>Application</strong>, then <strong>Cookies</strong>, then <Code>https://www.reddit.com</Code>.</li>- <li>Find the cookie named <Code>reddit_session</Code> and copy its value.</li>- <li>In Twiligent choose <strong>Add account</strong>, <strong>Reddit account</strong>, enter your username and paste the cookie.</li>- </OL>- <Callout type="warning" title="Treat the cookie like a password">- <p>It signs in as you. Twiligent stores it on the server and never shows it again. If Reddit signs you out, the cookie stops working: remove the account and add it again with a fresh cookie.</p>- </Callout>- </>- );-}--export function Analytics() {- return (- <>- <DocTitle title="Read your analytics" lead="What each number means and where it comes from." />-- <H2>Overview</H2>- <P>The Overview has six tiles: <strong>Audience</strong>, <strong>Views</strong>, <strong>Content</strong>, <strong>Accounts</strong>, <strong>Comments</strong> and <strong>Likes</strong>. Select a tile to see its detail below. The first time you open it, Twiligent loads recent posts for each account in the background; the numbers fill in after a short wait.</P>- <Table- head={['Metric', 'How it is counted']}- rows={[- ['Audience', 'YouTube subscribers plus Instagram followers plus Reddit karma.'],- ['Views', 'YouTube channel views, Instagram views where Instagram reports them, and views on tracked content.'],- ['Likes', 'YouTube likes, Instagram likes and Reddit karma.'],- ['Karma', 'Reddit calls a post\'s upvotes "score"; Twiligent always shows it as karma.'],- ]}- />-- <H2>Account pages</H2>- <P>Select an account in the sidebar to open its own page. YouTube channels have tabs for videos, engagement, publishing times, growth, Shorts and tags. Instagram and Reddit pages show posting patterns, best days and hours, and top posts.</P>-- <H2>Why a number looks wrong</H2>- <UL>- <li><strong>Instagram views show a dash.</strong> Instagram does not report views for some older posts or when insights are unavailable. A dash means "not reported", not zero.</li>- <li><strong>Reddit has no view counts.</strong> Reddit stopped publishing views in 2018. You can enter them by hand for tracked Reddit posts.</li>- <li><strong>Numbers are a little old.</strong> Use <strong>Refresh</strong> on an account, or <strong>Refresh all</strong> in the top bar.</li>- </UL>- </>- );-}--export function Publishing() {- return (- <>- <DocTitle title="Publish and schedule" lead="Post photos, Reels and Stories to Instagram now or later." />-- <H2>Publish a single post</H2>- <Steps>- <Step title="Choose the type and file">- <P>Open <strong>Publish</strong>, pick <strong>Photo</strong>, <strong>Reel</strong> or <strong>Story</strong>, then choose the file. Photos must be JPEG; Reels must be MP4 or MOV in 9:16; Stories accept either.</P>- </Step>- <Step title="Write the caption and settings">- <P>Write the caption (up to 2,200 characters). In the panel on the right, pick the account and optionally add alt text, collaborators, tagged people, a location, and for Reels a cover image and audio name.</P>- </Step>- <Step title="Publish now or schedule">- <P>Under <strong>When</strong>, keep <strong>Publish now</strong>, or pick <strong>Schedule</strong> and set a date and time. Then choose <strong>Publish now</strong> or <strong>Schedule post</strong>.</P>- </Step>- </Steps>-- <H2>What happens after you schedule</H2>- <P>The file uploads straight away. The server publishes the post within 15 minutes after the time you picked, even when your browser is closed. There is nothing for a member to set up.</P>- <Table- head={['Status', 'Meaning']}- rows={[- [<strong>Pending</strong>, 'Waiting for its time. You can edit the caption and time, or delete it.'],- [<strong>Publishing</strong>, 'The server is publishing it right now.'],- [<strong>Published</strong>, 'Live on Instagram.'],- [<strong>Failed</strong>, 'Instagram rejected it. The Error column says why.'],- ]}- />- <Callout type="warning" title="Pending for more than 30 minutes past its time?">- <p>The scheduler on the server is not running. Email the administrator at <AdminLink subject="Scheduled posts are not publishing on Twiligent" /> with the time of the post. Publish shows the same warning automatically.</p>- </Callout>-- <H2>Bulk upload</H2>- <P>Choose <strong>Bulk upload</strong> to add many files at once. Give each file its own caption or apply one caption to all, then either publish them one after another or <strong>spread them out</strong> from a start time at an interval such as once a day.</P>-- <H2>Limits</H2>- <UL>- <li>Instagram allows 100 posts per account in any 24 hours.</li>- <li>Photos up to 8MB; videos up to 300MB and 15 minutes; Stories up to 60 seconds.</li>- <li>Publishing needs Cloudinary set up by the administrator. If it is missing, Publish says so.</li>- </UL>- </>- );-}--export function TrackedContent() {- return (- <>- <DocTitle title="Track content" lead="Follow any Reddit post or YouTube video by its link, even ones you did not make." />- <H2>Add an item</H2>- <P>Open <strong>Tracked content</strong> and choose <strong>Track content</strong>. Paste a Reddit post link or a YouTube video or Shorts link. Add an optional label and category, then choose <strong>Track</strong>.</P>- <H2>Categories</H2>- <P>Categories group items, for example by campaign. Each category gets its own page in the sidebar with combined views, karma and comments. To set a category on many items, select them with the checkboxes and use <strong>Assign category</strong>.</P>- <H2>Views and images for Reddit posts</H2>- <P>Reddit does not report views, so use <strong>Edit</strong> to enter the number from the post's insights page. Reddit posts also have no thumbnail; you can upload a screenshot so you recognise the post at a glance.</P>- <H2>Keep numbers current</H2>- <P>Use the refresh button on a row to fetch the latest karma, likes and comments for that item.</P>- </>- );-}--export function Troubleshooting() {- return (- <>- <DocTitle title="Troubleshooting" lead="Common problems for members, and who to contact when you are stuck." />- <Table- head={['Problem', 'What to do']}- rows={[- ['Instagram shows an error or a blank page when connecting', <>Your account is probably not a tester yet. See <A to="/docs/use/connect-accounts">Get tester access first</A>.</>],- ['"This Instagram account is already connected"', 'It is already in your Accounts list. Refresh it there instead.'],- ['Instagram connection says the account type is wrong', 'Switch the Instagram account to Business or Creator, then connect again.'],- ['Reddit says the session cookie is invalid or expired', 'Remove the Reddit account and add it again with a fresh reddit_session cookie.'],- ['A scheduled post stays Pending', <>Email the administrator at <AdminLink subject="Scheduled posts are not publishing on Twiligent" />.</>],- ['A scheduled post Failed', 'Read the Error column. Common causes are a file Instagram does not accept or an account whose access was removed.'],- ['Publish says Cloudinary is not set up', 'Only the administrator can fix this. Let them know.'],- ['Analytics will not load', 'Use Refresh on the account. If it keeps failing, contact the administrator; the platform key may be missing.'],- ]}- />- <H2>Contact the administrator</H2>- <P>For anything only the person running this instance can fix, email <AdminLink subject="Help with Twiligent" />. Include what you were doing, the account involved and the exact message you saw.</P>- </>- );-}+// each page lives in use/; this barrel keeps them in one lazy chunk for routes.js+export { default as GettingStarted } from './use/GettingStarted';+export { default as ConnectAccounts } from './use/ConnectAccounts';+export { default as Analytics } from './use/Analytics';+export { default as Publishing } from './use/Publishing';+export { default as TrackedContent } from './use/TrackedContent';+export { default as Troubleshooting } from './use/Troubleshooting';diff --git a/frontend/src/docs/pages/reference/Environment.jsx b/frontend/src/docs/pages/reference/Environment.jsxnew file mode 100644index 0000000..726df18--- /dev/null+++ b/frontend/src/docs/pages/reference/Environment.jsx@@ -0,0 +1,83 @@+import React from 'react';+import { DocTitle, H2, P, UL, A, Code, Callout, Table, Badge } from '../../components';++const BACKEND_VARS = [+ ['SUPABASE_URL', 'required', false, 'Supabase, Project Settings, Data API', 'Which database the Worker talks to.'],+ ['SUPABASE_SERVICE_KEY', 'required', true, 'Supabase, Project Settings, API Keys, secret key (legacy: service_role)', 'Reads and writes all tables on behalf of members.'],+ ['SUPABASE_ANON_KEY', 'required', false, 'Supabase, Project Settings, API Keys, publishable key (legacy: anon)', 'Checks that a sign-in token is genuine.'],+ ['YOUTUBE_API_KEY', 'youtube', true, 'Google Cloud, APIs and Services, Credentials', 'Every YouTube read.'],+ ['INSTAGRAM_APP_ID', 'instagram', false, 'Meta app, Instagram, API setup with Instagram business login', 'Starts Instagram sign-in.'],+ ['INSTAGRAM_APP_SECRET', 'instagram', true, 'Same page as the app ID', 'Exchanges and renews Instagram access tokens.'],+ ['CLOUDINARY_CLOUD_NAME', 'publishing', false, 'Cloudinary dashboard', 'Where uploaded media goes.'],+ ['CLOUDINARY_UPLOAD_PRESET', 'publishing', false, 'Cloudinary, Settings, Upload, Upload presets (unsigned)', 'Lets browsers upload without the Cloudinary API secret.'],+ ['BACKEND_URL', 'instagram', false, 'Your Worker address, no trailing slash', 'Builds the Instagram redirect URI.'],+ ['FRONTEND_URL', 'instagram', false, 'Your Pages address', 'Where members land after Instagram sign-in.'],+ ['UPSTASH_REDIS_REST_URL', 'optional', false, 'Upstash database, REST API', 'Cache address.'],+ ['UPSTASH_REDIS_REST_TOKEN', 'optional', true, 'Upstash database, REST API', 'Cache password.'],+];++const FRONTEND_VARS = [+ ['VITE_SUPABASE_URL', 'required', 'Same as SUPABASE_URL.'],+ ['VITE_SUPABASE_ANON_KEY', 'required', 'The publishable key. Never the secret key.'],+ ['VITE_API_URL', 'required', 'Backend URL plus /api, for example https://twiligent.you.workers.dev/api. Defaults to http://localhost:8787/api in development.'],+ ['VITE_ADMIN_EMAIL', 'optional', 'Where members are told to write for Instagram tester access or help.'],+ ['VITE_GOOGLE_CLIENT_ID', 'optional', 'Web client ID from Google Auth Platform. Shows the Sign in with Google button; leave unset to hide it.'],+];++const NEED = {+ required: <Badge tone="required">Required</Badge>,+ youtube: <Badge tone="optional">For YouTube</Badge>,+ instagram: <Badge tone="optional">For Instagram</Badge>,+ publishing: <Badge tone="optional">For publishing</Badge>,+ optional: <Badge tone="optional">Optional</Badge>,+};++export default function Environment() {+ return (+ <>+ <DocTitle title="Environment variables" lead="Every value Twiligent reads, where it comes from, and where it goes." />++ <Callout type="note" title="Members can skip this page">+ <p>Only the administrator of an instance sets these. If you sign in to someone else's Twiligent, nothing here applies to you.</p>+ </Callout>++ <H2>Backend (Cloudflare Worker)</H2>+ <P>Set each one with <Code>npx wrangler secret put NAME</Code> in <Code>backend/</Code>. For local development, put them in <Code>backend/.dev.vars</Code>, which Git ignores. See <A to="/docs/self-host/deploy-backend">Deploy the backend</A>.</P>+ <Table+ head={['Name', 'Needed', 'Where to get it', 'Used for']}+ rows={BACKEND_VARS.map(([name, need, secret, from, use]) => [+ <span className="inline-flex flex-col gap-1"><Code>{name}</Code>{secret && <Badge tone="secret">Secret</Badge>}</span>,+ NEED[need],+ from,+ use,+ ])}+ />+ <P>Platform keys are shared by every member of the instance. Missing ones only switch off that platform: Settings shows which are set, and members see a clear message instead of an error.</P>++ <H2>Frontend (Cloudflare Pages)</H2>+ <P>Set these in <Code>frontend/.env</Code> before <Code>npm run build</Code>, or as GitHub secrets when the deploy workflow builds for you. They are built into the site and are public.</P>+ <Table+ head={['Name', 'Needed', 'Value']}+ rows={FRONTEND_VARS.map(([name, need, value]) => [<Code>{name}</Code>, NEED[need], value])}+ />++ <H2>GitHub Actions secrets</H2>+ <Table+ head={['Name', 'Used by']}+ rows={[+ [<Code>CLOUDFLARE_API_TOKEN</Code>, 'Both deploy workflows'],+ [<Code>CLOUDFLARE_ACCOUNT_ID</Code>, 'Both deploy workflows'],+ [<><Code>VITE_SUPABASE_URL</Code>, <Code>VITE_SUPABASE_ANON_KEY</Code>, <Code>VITE_API_URL</Code>, <Code>VITE_ADMIN_EMAIL</Code>, <Code>VITE_GOOGLE_CLIENT_ID</Code></>, 'Frontend deploy workflow'],+ [<><Code>SUPABASE_URL</Code>, <Code>SUPABASE_SERVICE_KEY</Code></>, 'Backup scheduler (publish-scheduled.yml)'],+ ]}+ />++ <H2>Not needed</H2>+ <UL>+ <li><Code>REDDIT_ENCRYPTION_KEY</Code> appears in older notes but is no longer read. Reddit cookies are stored server-side and never returned to the browser.</li>+ <li>A GitHub personal access token. Earlier versions asked for one in Settings; it was never used and has been removed.</li>+ <li>A Reddit API key. Members use their own session cookie.</li>+ </UL>+ </>+ );+}diff --git a/frontend/src/docs/pages/reference/FAQ.jsx b/frontend/src/docs/pages/reference/FAQ.jsxnew file mode 100644index 0000000..02b75bb--- /dev/null+++ b/frontend/src/docs/pages/reference/FAQ.jsx@@ -0,0 +1,34 @@+import React from 'react';+import { DocTitle, H3, P, A } from '../../components';++export default function FAQ() {+ return (+ <>+ <DocTitle title="FAQ" lead="Short answers to the questions people ask most." />++ <H3>Do I need GitHub to schedule posts?</H3>+ <P>No. Members never do. Administrators only need the deployed Worker; the GitHub workflow is an optional backup.</P>++ <H3>Do I need my own Supabase project?</H3>+ <P>Only if you run your own instance. Members of someone else's instance use theirs.</P>++ <H3>Why can't I connect my Instagram account?</H3>+ <P>It must be a Business or Creator account, and while the instance's Meta app is in development mode it must be added as a tester. See <A to="/docs/use/connect-accounts">Connect your accounts</A>.</P>++ <H3>Can I connect a YouTube channel I do not own?</H3>+ <P>Yes. YouTube analytics use public data, so any public channel works.</P>++ <H3>Does Twiligent publish to YouTube or Reddit?</H3>+ <P>No. Publishing is Instagram only. YouTube and Reddit are analytics only.</P>++ <H3>What does running an instance cost?</H3>+ <P>For a small team, nothing. Supabase, Cloudflare, Cloudinary and Upstash free plans cover typical use, and the YouTube and Instagram APIs are free.</P>++ <H3>How fresh is the data?</H3>+ <P>Data is fetched when you open a page or choose Refresh, and cached for a short time when Redis is set up. Instagram tokens are renewed nightly.</P>++ <H3>Who do I contact for help?</H3>+ <P>The administrator of your instance. Their address is on the <A to="/docs/use/troubleshooting">Troubleshooting</A> page.</P>+ </>+ );+}diff --git a/frontend/src/docs/pages/reference/Scheduling.jsx b/frontend/src/docs/pages/reference/Scheduling.jsxnew file mode 100644index 0000000..08f3a68--- /dev/null+++ b/frontend/src/docs/pages/reference/Scheduling.jsx@@ -0,0 +1,38 @@+import React from 'react';+import { DocTitle, H2, H3, P, UL, Code, Table, Badge } from '../../components';++export default function Scheduling() {+ return (+ <>+ <DocTitle title="How scheduling works" lead="What happens between choosing Schedule post and the post going live." />++ <H2>For members</H2>+ <P>Nothing to set up. Pick a time, choose <strong>Schedule post</strong>, and close the browser if you like. The server publishes the post within 15 minutes after the time you picked.</P>++ <H2>For administrators</H2>+ <P>Deploying the backend is all that is required. The Worker's cron trigger runs every 15 minutes and publishes every post that is due. The GitHub workflow is an optional second runner for extra reliability.</P>++ <H3>The lifecycle of a post</H3>+ <Table+ head={['Step', 'Status', 'What happens']}+ rows={[+ ['1', <Badge>pending</Badge>, 'The file is on Cloudinary and the post is saved with its time.'],+ ['2', <Badge>publishing</Badge>, 'A scheduler claims the post. Only one scheduler can claim it, so it is published once.'],+ ['3', <Badge>published</Badge>, 'Instagram accepted it. The Instagram media ID is saved.'],+ ['3', <Badge>failed</Badge>, 'Instagram rejected it. The reason is saved and shown in the Error column.'],+ ]}+ />++ <H3>Two schedulers, one post</H3>+ <P>Both schedulers claim a post by changing it from <Code>pending</Code> to <Code>publishing</Code> in a single database update that only succeeds while it is still pending. Whichever arrives second finds nothing to claim and skips it.</P>++ <H3>When posts stay pending</H3>+ <UL>+ <li>The Worker was never deployed, or its cron triggers were removed. Check <strong>Triggers</strong> on the Worker in the Cloudflare dashboard.</li>+ <li><Code>SUPABASE_SERVICE_KEY</Code> or <Code>SUPABASE_URL</Code> is wrong on the Worker.</li>+ <li>The connected Instagram account's access was removed. Reconnect it.</li>+ </UL>+ <P>Twiligent warns members when a post is more than 30 minutes overdue and tells them to contact the administrator.</P>+ </>+ );+}diff --git a/frontend/src/docs/pages/reference/Security.jsx b/frontend/src/docs/pages/reference/Security.jsxnew file mode 100644index 0000000..0a3900f--- /dev/null+++ b/frontend/src/docs/pages/reference/Security.jsx@@ -0,0 +1,33 @@+import React from 'react';+import { DocTitle, H2, P, UL, A, Table } from '../../components';++export default function Security() {+ return (+ <>+ <DocTitle title="Security" lead="How member data is kept apart, and the settings an administrator must get right." />++ <H2>What members can rely on</H2>+ <UL>+ <li>Other members cannot see your accounts, scheduled posts or tracked content.</li>+ <li>Instagram access tokens and Reddit cookies are stored on the server and never sent to any browser, including yours.</li>+ <li>No member, including you, ever handles the instance's API keys.</li>+ </UL>++ <H2>How isolation works</H2>+ <P>The browser signs in with Supabase and sends its token with every request. The Worker verifies the token and takes the member's ID from it, never from anything the browser sends. Every database query is limited to that ID. Responses are stripped of tokens and cookies before they leave the Worker.</P>++ <H2>Administrator responsibilities</H2>+ <Table+ head={['Setting', 'Why it matters']}+ rows={[+ ['Row level security on all four tables', 'The publishable key ships in the website. With security off, anyone could use it to read every table directly.'],+ ['Secret key only in server secrets', 'It bypasses all database rules. Keep it in Worker secrets and GitHub Actions secrets only.'],+ ['Signups', 'Supabase allows anyone with the address to sign up. Turn signups off for a private instance.'],+ ['backend/.dev.vars never committed', 'It holds every secret for local development.'],+ ['Instagram testers', 'In development mode, only people you add can connect Instagram.'],+ ]}+ />+ <P>The SQL to turn on row level security is on the <A to="/docs/self-host/supabase">Supabase</A> page.</P>+ </>+ );+}diff --git a/frontend/src/docs/pages/use/AdminLink.jsx b/frontend/src/docs/pages/use/AdminLink.jsxnew file mode 100644index 0000000..06e9bc1--- /dev/null+++ b/frontend/src/docs/pages/use/AdminLink.jsx@@ -0,0 +1,7 @@+import React from 'react';+import { ADMIN_EMAIL, adminMailto } from '@/lib/contact';+import { A } from '../../components';++export default function AdminLink({ subject }) {+ return <A href={adminMailto(subject)}>{ADMIN_EMAIL}</A>;+}diff --git a/frontend/src/docs/pages/use/Analytics.jsx b/frontend/src/docs/pages/use/Analytics.jsxnew file mode 100644index 0000000..ad1d254--- /dev/null+++ b/frontend/src/docs/pages/use/Analytics.jsx@@ -0,0 +1,32 @@+import React from 'react';+import { DocTitle, H2, P, UL, Table } from '../../components';++export default function Analytics() {+ return (+ <>+ <DocTitle title="Read your analytics" lead="What each number means and where it comes from." />++ <H2>Overview</H2>+ <P>The Overview has six tiles: <strong>Audience</strong>, <strong>Views</strong>, <strong>Content</strong>, <strong>Accounts</strong>, <strong>Comments</strong> and <strong>Likes</strong>. Select a tile to see its detail below. The first time you open it, Twiligent loads recent posts for each account in the background; the numbers fill in after a short wait.</P>+ <Table+ head={['Metric', 'How it is counted']}+ rows={[+ ['Audience', 'YouTube subscribers plus Instagram followers plus Reddit karma.'],+ ['Views', 'YouTube channel views, Instagram views where Instagram reports them, and views on tracked content.'],+ ['Likes', 'YouTube likes, Instagram likes and Reddit karma.'],+ ['Karma', 'Reddit calls a post\'s upvotes "score"; Twiligent always shows it as karma.'],+ ]}+ />++ <H2>Account pages</H2>+ <P>Select an account in the sidebar to open its own page. YouTube channels have tabs for videos, engagement, publishing times, growth, Shorts and tags. Instagram and Reddit pages show posting patterns, best days and hours, and top posts.</P>++ <H2>Why a number looks wrong</H2>+ <UL>+ <li><strong>Instagram views show a dash.</strong> Instagram does not report views for some older posts or when insights are unavailable. A dash means "not reported", not zero.</li>+ <li><strong>Reddit has no view counts.</strong> Reddit stopped publishing views in 2018. You can enter them by hand for tracked Reddit posts.</li>+ <li><strong>Numbers are a little old.</strong> Use <strong>Refresh</strong> on an account, or <strong>Refresh all</strong> in the top bar.</li>+ </UL>+ </>+ );+}diff --git a/frontend/src/docs/pages/use/ConnectAccounts.jsx b/frontend/src/docs/pages/use/ConnectAccounts.jsxnew file mode 100644index 0000000..3758d3a--- /dev/null+++ b/frontend/src/docs/pages/use/ConnectAccounts.jsx@@ -0,0 +1,47 @@+import React from 'react';+import { INSTAGRAM_TESTER_INVITES_URL } from '@/lib/contact';+import { DocTitle, H2, H3, P, OL, A, Code, Callout, Steps, Step } from '../../components';+import AdminLink from './AdminLink';++export default function ConnectAccounts() {+ return (+ <>+ <DocTitle title="Connect your accounts" lead="How to add YouTube channels, Instagram professional accounts and Reddit profiles." />++ <H2>YouTube</H2>+ <P>Open <strong>Accounts</strong>, choose <strong>Add account</strong>, then <strong>YouTube channel</strong>. Paste a channel link, an <Code>@handle</Code> or a channel ID starting with <Code>UC</Code>, choose <strong>Find</strong> to check it, then <strong>Add channel</strong>. Any public channel works; you do not need to own it.</P>++ <H2>Instagram</H2>+ <P>Instagram only connects <strong>Business</strong> or <strong>Creator</strong> accounts. You can switch a personal account to a professional one for free in the Instagram app under Settings, Account type and tools.</P>++ <H3>Get tester access first</H3>+ <P>Most instances run their Meta app in development mode. In that mode Instagram only lets accounts added as <strong>testers</strong> sign in. Without tester access, Instagram shows an error or a blank page.</P>+ <Steps>+ <Step title="Ask the administrator">+ <P>Email <AdminLink subject="Instagram tester request for Twiligent" /> with your Instagram username. The administrator adds you in the Meta app dashboard.</P>+ </Step>+ <Step title="Accept the invite">+ <P>Sign in to Instagram on the web and open <A href={INSTAGRAM_TESTER_INVITES_URL}>Apps and websites</A>, then the <strong>Tester invites</strong> tab, and accept the invite. In the Instagram app it is under Settings and privacy, Website permissions, Apps and websites, Tester invites.</P>+ </Step>+ <Step title="Connect">+ <P>In Twiligent, open <strong>Accounts</strong>, choose <strong>Add account</strong>, then <strong>Instagram account</strong>, then <strong>Continue to Instagram</strong>. Approve every requested permission. Instagram sends you back and the account appears in the list.</P>+ </Step>+ </Steps>+ <Callout type="note" title="Access lasts 60 days and renews itself">+ <p>Instagram access tokens last 60 days. Twiligent renews them automatically every night, so you only reconnect if you remove access in Instagram or change your password.</p>+ </Callout>++ <H2>Reddit</H2>+ <P>Reddit blocks most requests from servers, so Twiligent uses your browser session cookie to read your profile and posts.</P>+ <OL>+ <li>Sign in to reddit.com in your browser.</li>+ <li>Open the browser's developer tools (F12), then <strong>Application</strong>, then <strong>Cookies</strong>, then <Code>https://www.reddit.com</Code>.</li>+ <li>Find the cookie named <Code>reddit_session</Code> and copy its value.</li>+ <li>In Twiligent choose <strong>Add account</strong>, <strong>Reddit account</strong>, enter your username and paste the cookie.</li>+ </OL>+ <Callout type="warning" title="Treat the cookie like a password">+ <p>It signs in as you. Twiligent stores it on the server and never shows it again. If Reddit signs you out, the cookie stops working: remove the account and add it again with a fresh cookie.</p>+ </Callout>+ </>+ );+}diff --git a/frontend/src/docs/pages/use/GettingStarted.jsx b/frontend/src/docs/pages/use/GettingStarted.jsxnew file mode 100644index 0000000..5efebad--- /dev/null+++ b/frontend/src/docs/pages/use/GettingStarted.jsx@@ -0,0 +1,44 @@+import React from 'react';+import { DocTitle, H2, P, A, Code, Callout, Steps, Step, Table } from '../../components';++export default function GettingStarted() {+ return (+ <>+ <DocTitle title="Sign in and first steps" lead="Everything a member does in the first ten minutes. No installation or setup needed." />++ <Callout type="note" title="This guide is for members">+ <p>You are a member if someone gave you a Twiligent link to sign in to. The server, keys and scheduling are already handled by the administrator.</p>+ </Callout>++ <Steps>+ <Step title="Create your account">+ <P>Open your instance's link and choose <strong>Continue with Google</strong>, if your instance offers it. Otherwise choose <strong>Create an account</strong> and use your email and a password of at least 6 characters, then sign in. If you sign in with Google using the same email as an existing account, both open the same account.</P>+ </Step>+ <Step title="Connect an account">+ <P>Open <strong>Accounts</strong> in the sidebar and choose <strong>Add account</strong>. Pick YouTube, Instagram or Reddit. Each one is explained in <A to="/docs/use/connect-accounts">Connect your accounts</A>.</P>+ </Step>+ <Step title="Look around">+ <P>The <strong>Overview</strong> fills in within a minute or two. Use the search box at the top of the sidebar, or press <Code>Ctrl K</Code> (<Code>Cmd K</Code> on a Mac), to jump to any page or account.</P>+ </Step>+ <Step title="Choose a theme">+ <P>Twiligent has a light and a dark theme. Switch with the sun or moon button at the top right, or pick <strong>Match system</strong> in Settings.</P>+ </Step>+ </Steps>++ <H2>Where things are</H2>+ <Table+ head={['Page', 'Use it to']}+ rows={[+ [<strong>Overview</strong>, 'See audience, views, content, comments and likes across every account.'],+ [<strong>Videos, Shorts</strong>, 'Browse and sort every video from your YouTube channels.'],+ [<strong>Instagram content</strong>, 'Browse reels, posts and videos with views, likes and comments.'],+ [<strong>Reddit posts</strong>, 'See every post from your Reddit accounts with karma and comments.'],+ [<strong>Tracked content</strong>, 'Follow specific Reddit posts and YouTube videos by link.'],+ [<strong>Publish</strong>, 'Post or schedule to Instagram.'],+ [<strong>Accounts</strong>, 'Add, refresh and remove connected accounts.'],+ [<strong>Settings</strong>, 'Theme, server status and setup guides.'],+ ]}+ />+ </>+ );+}diff --git a/frontend/src/docs/pages/use/Publishing.jsx b/frontend/src/docs/pages/use/Publishing.jsxnew file mode 100644index 0000000..622d983--- /dev/null+++ b/frontend/src/docs/pages/use/Publishing.jsx@@ -0,0 +1,49 @@+import React from 'react';+import { DocTitle, H2, P, UL, Callout, Steps, Step, Table } from '../../components';+import AdminLink from './AdminLink';++export default function Publishing() {+ return (+ <>+ <DocTitle title="Publish and schedule" lead="Post photos, Reels and Stories to Instagram now or later." />++ <H2>Publish a single post</H2>+ <Steps>+ <Step title="Choose the type and file">+ <P>Open <strong>Publish</strong>, pick <strong>Photo</strong>, <strong>Reel</strong> or <strong>Story</strong>, then choose the file. Photos must be JPEG; Reels must be MP4 or MOV in 9:16; Stories accept either.</P>+ </Step>+ <Step title="Write the caption and settings">+ <P>Write the caption (up to 2,200 characters). In the panel on the right, pick the account and optionally add alt text, collaborators, tagged people, a location, and for Reels a cover image and audio name.</P>+ </Step>+ <Step title="Publish now or schedule">+ <P>Under <strong>When</strong>, keep <strong>Publish now</strong>, or pick <strong>Schedule</strong> and set a date and time. Then choose <strong>Publish now</strong> or <strong>Schedule post</strong>.</P>+ </Step>+ </Steps>++ <H2>What happens after you schedule</H2>+ <P>The file uploads straight away. The server publishes the post within 15 minutes after the time you picked, even when your browser is closed. There is nothing for a member to set up.</P>+ <Table+ head={['Status', 'Meaning']}+ rows={[+ [<strong>Pending</strong>, 'Waiting for its time. You can edit the caption and time, or delete it.'],+ [<strong>Publishing</strong>, 'The server is publishing it right now.'],+ [<strong>Published</strong>, 'Live on Instagram.'],+ [<strong>Failed</strong>, 'Instagram rejected it. The Error column says why.'],+ ]}+ />+ <Callout type="warning" title="Pending for more than 30 minutes past its time?">+ <p>The scheduler on the server is not running. Email the administrator at <AdminLink subject="Scheduled posts are not publishing on Twiligent" /> with the time of the post. Publish shows the same warning automatically.</p>+ </Callout>++ <H2>Bulk upload</H2>+ <P>Choose <strong>Bulk upload</strong> to add many files at once. Give each file its own caption or apply one caption to all, then either publish them one after another or <strong>spread them out</strong> from a start time at an interval such as once a day.</P>++ <H2>Limits</H2>+ <UL>+ <li>Instagram allows 100 posts per account in any 24 hours.</li>+ <li>Photos up to 8MB; videos up to 300MB and 15 minutes; Stories up to 60 seconds.</li>+ <li>Publishing needs Cloudinary set up by the administrator. If it is missing, Publish says so.</li>+ </UL>+ </>+ );+}diff --git a/frontend/src/docs/pages/use/TrackedContent.jsx b/frontend/src/docs/pages/use/TrackedContent.jsxnew file mode 100644index 0000000..02ab269--- /dev/null+++ b/frontend/src/docs/pages/use/TrackedContent.jsx@@ -0,0 +1,18 @@+import React from 'react';+import { DocTitle, H2, P } from '../../components';++export default function TrackedContent() {+ return (+ <>+ <DocTitle title="Track content" lead="Follow any Reddit post or YouTube video by its link, even ones you did not make." />+ <H2>Add an item</H2>+ <P>Open <strong>Tracked content</strong> and choose <strong>Track content</strong>. Paste a Reddit post link or a YouTube video or Shorts link. Add an optional label and category, then choose <strong>Track</strong>.</P>+ <H2>Categories</H2>+ <P>Categories group items, for example by campaign. Each category gets its own page in the sidebar with combined views, karma and comments. To set a category on many items, select them with the checkboxes and use <strong>Assign category</strong>.</P>+ <H2>Views and images for Reddit posts</H2>+ <P>Reddit does not report views, so use <strong>Edit</strong> to enter the number from the post's insights page. Reddit posts also have no thumbnail; you can upload a screenshot so you recognise the post at a glance.</P>+ <H2>Keep numbers current</H2>+ <P>Use the refresh button on a row to fetch the latest karma, likes and comments for that item.</P>+ </>+ );+}diff --git a/frontend/src/docs/pages/use/Troubleshooting.jsx b/frontend/src/docs/pages/use/Troubleshooting.jsxnew file mode 100644index 0000000..388b58e--- /dev/null+++ b/frontend/src/docs/pages/use/Troubleshooting.jsx@@ -0,0 +1,26 @@+import React from 'react';+import { DocTitle, H2, P, A, Table } from '../../components';+import AdminLink from './AdminLink';++export default function Troubleshooting() {+ return (+ <>+ <DocTitle title="Troubleshooting" lead="Common problems for members, and who to contact when you are stuck." />+ <Table+ head={['Problem', 'What to do']}+ rows={[+ ['Instagram shows an error or a blank page when connecting', <>Your account is probably not a tester yet. See <A to="/docs/use/connect-accounts">Get tester access first</A>.</>],+ ['"This Instagram account is already connected"', 'It is already in your Accounts list. Refresh it there instead.'],+ ['Instagram connection says the account type is wrong', 'Switch the Instagram account to Business or Creator, then connect again.'],+ ['Reddit says the session cookie is invalid or expired', 'Remove the Reddit account and add it again with a fresh reddit_session cookie.'],+ ['A scheduled post stays Pending', <>Email the administrator at <AdminLink subject="Scheduled posts are not publishing on Twiligent" />.</>],+ ['A scheduled post Failed', 'Read the Error column. Common causes are a file Instagram does not accept or an account whose access was removed.'],+ ['Publish says Cloudinary is not set up', 'Only the administrator can fix this. Let them know.'],+ ['Analytics will not load', 'Use Refresh on the account. If it keeps failing, contact the administrator; the platform key may be missing.'],+ ]}+ />+ <H2>Contact the administrator</H2>+ <P>For anything only the person running this instance can fix, email <AdminLink subject="Help with Twiligent" />. Include what you were doing, the account involved and the exact message you saw.</P>+ </>+ );+}diff --git a/frontend/src/docs/useTableOfContents.js b/frontend/src/docs/useTableOfContents.jsnew file mode 100644index 0000000..6383c53--- /dev/null+++ b/frontend/src/docs/useTableOfContents.js@@ -0,0 +1,29 @@+import { useEffect, useState } from 'react';++export function useTableOfContents(articleRef, pathname) {+ const [items, setItems] = useState([]);+ const [active, setActive] = useState(null);++ useEffect(() => {+ const article = articleRef.current;+ if (!article) return undefined;+ const collect = () => {+ const headings = [...article.querySelectorAll('[data-toc]')];+ setItems(headings.map(heading => ({ id: heading.id, text: heading.textContent, level: Number(heading.dataset.toc) })));+ return headings;+ };+ let headings = collect();+ // pages are lazy-loaded, so headings can appear after the first render+ const mutations = new MutationObserver(() => { headings = collect(); observeAll(); });+ const spy = new IntersectionObserver(entries => {+ const visible = entries.filter(e => e.isIntersecting).sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);+ if (visible[0]) setActive(visible[0].target.id);+ }, { rootMargin: '-120px 0px -65% 0px' });+ function observeAll() { spy.disconnect(); headings.forEach(heading => spy.observe(heading)); }+ observeAll();+ mutations.observe(article, { childList: true, subtree: true });+ return () => { mutations.disconnect(); spy.disconnect(); };+ }, [articleRef, pathname]);++ return { items, active };+}diff --git a/frontend/src/features/accounts/RedditAccountFields.jsx b/frontend/src/features/accounts/RedditAccountFields.jsxindex e54e214..eab6a62 100644--- a/frontend/src/features/accounts/RedditAccountFields.jsx+++ b/frontend/src/features/accounts/RedditAccountFields.jsx@@ -35,7 +35,8 @@ export default function RedditAccountFields({ username, cookie, onUsernameChange<Alert><Info /><AlertDescription>- Sign in to reddit.com in your browser, open DevTools (F12), go to Application, then Cookies, then https://www.reddit.com, and copy the value of <strong className="font-semibold text-ink">reddit_session</strong>.+ {'Sign in to reddit.com in your browser, open DevTools (F12), go to Application, then Cookies, then https://www.reddit.com, and copy the value of '}+ <strong className="font-semibold text-ink">reddit_session</strong>.</AlertDescription></Alert></div>diff --git a/frontend/src/features/analytics/reddit/RedditPostFilters.jsx b/frontend/src/features/analytics/reddit/RedditPostFilters.jsxnew file mode 100644index 0000000..012def9--- /dev/null+++ b/frontend/src/features/analytics/reddit/RedditPostFilters.jsx@@ -0,0 +1,40 @@+import React from 'react';+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';+import SearchField from '@/components/SearchField';+import { REDDIT_SORT_OPTIONS } from './redditPostUtils';++function FilterSelect({ value, onChange, items, label, className = 'w-full sm:w-48' }) {+ return (+ <Select value={value} onValueChange={onChange} items={items}>+ <SelectTrigger className={className} aria-label={label}><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {items.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}+ </SelectGroup>+ </SelectContent>+ </Select>+ );+}++export default function RedditPostFilters({ query, onQuery, sort, onSort, subreddit, onSubreddit, subreddits, accountId, onAccount, accounts }) {+ 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 && (+ <FilterSelect+ label="Account"+ value={accountId}+ onChange={onAccount}+ items={[{ value: 'all', label: 'All accounts' }, ...accounts.map(a => ({ value: a.id, label: `u/${a.username}` }))]}+ />+ )}+ <FilterSelect+ label="Subreddit"+ value={subreddit}+ onChange={onSubreddit}+ items={[{ value: 'all', label: 'All subreddits' }, ...subreddits.map(s => ({ value: s, label: `r/${s}` }))]}+ />+ <FilterSelect label="Sort" value={sort} onChange={onSort} items={REDDIT_SORT_OPTIONS} className="w-full sm:w-44" />+ </div>+ );+}diff --git a/frontend/src/features/analytics/reddit/redditPostTable.jsx b/frontend/src/features/analytics/reddit/RedditPostTable.jsxsimilarity index 71%rename from frontend/src/features/analytics/reddit/redditPostTable.jsxrename to frontend/src/features/analytics/reddit/RedditPostTable.jsxindex 328e052..bbf946e 100644--- a/frontend/src/features/analytics/reddit/redditPostTable.jsx+++ b/frontend/src/features/analytics/reddit/RedditPostTable.jsx@@ -4,12 +4,10 @@ import { ExternalLink, FileText, Image, Video, Link2 } from 'lucide-react';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';-import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';-import SearchField from '@/components/SearchField';import SurfaceBox from '@/components/SurfaceBox';import { EmptyState } from '@/components/StateViews';import { AccountAvatar } from '@/components/platform';-import { MEDIA_TYPE_LABELS, REDDIT_SORT_OPTIONS } from './redditPostUtils';+import { MEDIA_TYPE_LABELS } from './redditPostUtils';import { fmtNum, fmtDate } from '../../../utils/formatters';import ColumnHint from '@/components/ColumnHint';@@ -20,43 +18,7 @@ function MediaTypeIcon({ type, className = 'size-3.5' }) {return <Icon className={className} />;}-function FilterSelect({ value, onChange, items, label, className = 'w-full sm:w-48' }) {- return (- <Select value={value} onValueChange={onChange} items={items}>- <SelectTrigger className={className} aria-label={label}><SelectValue /></SelectTrigger>- <SelectContent>- <SelectGroup>- {items.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}- </SelectGroup>- </SelectContent>- </Select>- );-}--export function RedditPostFilters({ query, onQuery, sort, onSort, subreddit, onSubreddit, subreddits, accountId, onAccount, accounts }) {- 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 && (- <FilterSelect- label="Account"- value={accountId}- onChange={onAccount}- items={[{ value: 'all', label: 'All accounts' }, ...accounts.map(a => ({ value: a.id, label: `u/${a.username}` }))]}- />- )}- <FilterSelect- label="Subreddit"- value={subreddit}- onChange={onSubreddit}- items={[{ value: 'all', label: 'All subreddits' }, ...subreddits.map(s => ({ value: s, label: `r/${s}` }))]}- />- <FilterSelect label="Sort" value={sort} onChange={onSort} items={REDDIT_SORT_OPTIONS} className="w-full sm:w-44" />- </div>- );-}--export function RedditPostTable({ posts, showAccount = false, accountsById = {} }) {+export default function RedditPostTable({ posts, showAccount = false, accountsById = {} }) {if (posts.length === 0) {return (<SurfaceBox>diff --git a/frontend/src/features/analytics/reddit/RedditPosts.jsx b/frontend/src/features/analytics/reddit/RedditPosts.jsxindex 08bb369..cebde98 100644--- a/frontend/src/features/analytics/reddit/RedditPosts.jsx+++ b/frontend/src/features/analytics/reddit/RedditPosts.jsx@@ -8,7 +8,8 @@ import { EmptyState } from '@/components/StateViews';import { AccountAvatar } from '@/components/platform';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';-import { RedditPostFilters, RedditPostTable } from './redditPostTable';+import RedditPostFilters from './RedditPostFilters';+import RedditPostTable from './RedditPostTable';import { filterAndSortRedditPosts, subredditsOf } from './redditPostUtils';export default function RedditPosts() {@@ -29,7 +30,7 @@ export default function RedditPosts() {.then(data => setPosts(Array.isArray(data) ? data : [])).catch(err => showToast(`Couldn't load posts. ${err.message}`, 'error')).finally(() => setLoading(false));- // Reload only when the route changes, not on every account list refresh+ // reload per route, not per account list refresh// eslint-disable-next-line react-hooks/exhaustive-deps}, [id]);diff --git a/frontend/src/features/analytics/reddit/RedditPostsAll.jsx b/frontend/src/features/analytics/reddit/RedditPostsAll.jsxindex ecdbf8a..78fc343 100644--- a/frontend/src/features/analytics/reddit/RedditPostsAll.jsx+++ b/frontend/src/features/analytics/reddit/RedditPostsAll.jsx@@ -10,7 +10,8 @@ import { EmptyState } from '@/components/StateViews';import { useAppContext } from '../../../context/AppContext';import { api } from '../../../services/api';import { fmtNum } from '../../../utils/formatters';-import { RedditPostFilters, RedditPostTable } from './redditPostTable';+import RedditPostFilters from './RedditPostFilters';+import RedditPostTable from './RedditPostTable';import { filterAndSortRedditPosts, subredditsOf } from './redditPostUtils';import { cn } from '@/lib/utils';diff --git a/frontend/src/features/analytics/shorts/ShortsExplorer.jsx b/frontend/src/features/analytics/shorts/ShortsExplorer.jsxindex 875bc0f..9bfe304 100644--- a/frontend/src/features/analytics/shorts/ShortsExplorer.jsx+++ b/frontend/src/features/analytics/shorts/ShortsExplorer.jsx@@ -1,20 +1,18 @@import React, { useMemo, useState } from 'react';import { Link } from 'react-router-dom';-import { RefreshCw, Eye, ThumbsUp, MessageSquare, Scissors, Plus } from 'lucide-react';+import { RefreshCw, Scissors, Plus } from 'lucide-react';import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';-import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';import PageHeader from '@/components/PageHeader';import SurfaceBox from '@/components/SurfaceBox';-import SearchField from '@/components/SearchField';-import FilterChips from '@/components/FilterChips';import Pager from '@/components/Pager';-import MediaCard, { MediaChip } from '@/components/MediaCard';import { EmptyState } from '@/components/StateViews';import { VIEW_TIERS, filterByTier, matchesText, pageSlice } from '@/lib/library';import { useChannelVideos } from '../videos/useChannelVideos';-import { fmtNum, fmtDuration, fmtCount } from '../../../utils/formatters';+import { fmtNum } from '../../../utils/formatters';import { cn } from '@/lib/utils';+import ShortsFilters from './ShortsFilters';+import ShortsGrid from './ShortsGrid';const ITEMS_PER_PAGE = 24;const SHORT_MAX_SECONDS = 60;@@ -100,35 +98,18 @@ export default function ShortsExplorer() {<div className="flex flex-col gap-6">{header}- <div className="flex flex-col gap-3">- <div className="flex flex-wrap items-center gap-2">- <SearchField value={search} onChange={resetPage(setSearch)} placeholder="Search Shorts" className="min-w-56 flex-1" />- {channels.length > 1 && (- <Select- value={channelFilter}- onValueChange={resetPage(setChannelFilter)}- items={[{ value: 'all', label: 'All channels' }, ...channels.map(c => ({ value: c.id, label: c.title }))]}- >- <SelectTrigger className="w-48" aria-label="Channel"><SelectValue /></SelectTrigger>- <SelectContent>- <SelectGroup>- <SelectItem value="all">All channels</SelectItem>- {channels.map(c => <SelectItem key={c.id} value={c.id}>{c.title}</SelectItem>)}- </SelectGroup>- </SelectContent>- </Select>- )}- <Select value={sortField} onValueChange={setSortField} items={SORT_OPTIONS}>- <SelectTrigger className="w-44" aria-label="Sort"><SelectValue /></SelectTrigger>- <SelectContent>- <SelectGroup>- {SORT_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}- </SelectGroup>- </SelectContent>- </Select>- </div>- <FilterChips label="Views" options={VIEW_TIERS} value={tier} onChange={resetPage(setTier)} />- </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)}+ />{filtered.length === 0 ? (<SurfaceBox>@@ -140,25 +121,7 @@ export default function ShortsExplorer() {/></SurfaceBox>) : (- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6">- {paged.items.map((v, i) => (- <MediaCard- key={`${v.videoId}-${i}`}- aspect="vertical"- href={`https://www.youtube.com/shorts/${v.videoId}`}- image={v.thumbnail}- title={v.title}- topRight={<MediaChip><Eye />{fmtNum(v.viewCount)}</MediaChip>}- bottomRight={<MediaChip>{fmtDuration(v.durationSeconds)}</MediaChip>}- meta={- <>- <span className="flex items-center gap-1"><ThumbsUp />{fmtCount(v.likeCount)}</span>- <span className="flex items-center gap-1"><MessageSquare />{fmtCount(v.commentCount)}</span>- </>- }- />- ))}- </div>+ <ShortsGrid shorts={paged.items} />)}<Pager page={paged.page} pageCount={paged.pageCount} onPageChange={setPage} total={filtered.length} shown={paged.items.length} noun="Shorts" />diff --git a/frontend/src/features/analytics/shorts/ShortsFilters.jsx b/frontend/src/features/analytics/shorts/ShortsFilters.jsxnew file mode 100644index 0000000..5bc3141--- /dev/null+++ b/frontend/src/features/analytics/shorts/ShortsFilters.jsx@@ -0,0 +1,41 @@+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 { VIEW_TIERS } from '@/lib/library';++export default function ShortsFilters({+ channels, sortOptions, search, onSearchChange, channelFilter, onChannelChange, sortField, onSortChange, tier, onTierChange,+}) {+ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center gap-2">+ <SearchField value={search} onChange={onSearchChange} placeholder="Search Shorts" className="min-w-56 flex-1" />+ {channels.length > 1 && (+ <Select+ value={channelFilter}+ onValueChange={onChannelChange}+ items={[{ value: 'all', label: 'All channels' }, ...channels.map(c => ({ value: c.id, label: c.title }))]}+ >+ <SelectTrigger className="w-48" aria-label="Channel"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectGroup>+ <SelectItem value="all">All channels</SelectItem>+ {channels.map(c => <SelectItem key={c.id} value={c.id}>{c.title}</SelectItem>)}+ </SelectGroup>+ </SelectContent>+ </Select>+ )}+ <Select value={sortField} onValueChange={onSortChange} items={sortOptions}>+ <SelectTrigger className="w-44" aria-label="Sort"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {sortOptions.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>+ <FilterChips label="Views" options={VIEW_TIERS} value={tier} onChange={onTierChange} />+ </div>+ );+}diff --git a/frontend/src/features/analytics/shorts/ShortsGrid.jsx b/frontend/src/features/analytics/shorts/ShortsGrid.jsxnew file mode 100644index 0000000..7b510a5--- /dev/null+++ b/frontend/src/features/analytics/shorts/ShortsGrid.jsx@@ -0,0 +1,28 @@+import React from 'react';+import { Eye, MessageSquare, ThumbsUp } from 'lucide-react';+import MediaCard, { MediaChip } from '@/components/MediaCard';+import { fmtNum, fmtDuration, fmtCount } from '../../../utils/formatters';++export default function ShortsGrid({ shorts }) {+ return (+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6">+ {shorts.map((video, i) => (+ <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>+ </>+ }+ />+ ))}+ </div>+ );+}diff --git a/frontend/src/features/analytics/videos/useChannelVideos.js b/frontend/src/features/analytics/videos/useChannelVideos.jsindex 42615dc..01d49c4 100644--- a/frontend/src/features/analytics/videos/useChannelVideos.js+++ b/frontend/src/features/analytics/videos/useChannelVideos.js@@ -2,7 +2,7 @@ import { useCallback, useEffect, useState } from 'react';import { api } from '../../../services/api';import { useAppContext } from '../../../context/AppContext';import { platformOf } from '@/lib/accounts';-import { engagementPercent, parseIsoDuration } from '@/lib/library';+import { mergeChannelVideos } from './videoLibrary';// Loads every video from every YouTube channel. Shared by the Videos and Shorts pages.export function useChannelVideos() {@@ -16,27 +16,9 @@ export function useChannelVideos() {try {const channelAccounts = (accounts || []).filter(a => platformOf(a) === 'youtube');const results = await Promise.allSettled(channelAccounts.map(a => api.getVideos(a.id)));- const allVideos = [];- const channelList = [];- results.forEach((result, i) => {- if (result.status !== 'fulfilled') return;- const acct = channelAccounts[i];- const res = result.value;- const channelTitle = acct.title || acct.channelTitle || 'Unknown channel';- channelList.push({ id: acct.id, title: channelTitle, account: acct });- for (const v of res.videos || res.data?.videos || []) {- allVideos.push({- ...v,- thumbnail: v.thumbnail || v.thumbnails?.medium || v.thumbnails?.high || v.thumbnails?.default || '',- channelTitle,- channelId: acct.id,- engagementRate: engagementPercent(v.viewCount, v.likeCount, v.commentCount),- durationSeconds: v.durationSeconds || parseIsoDuration(v.duration),- });- }- });- setVideos(allVideos);- setChannels(channelList);+ const merged = mergeChannelVideos(channelAccounts, results);+ setVideos(merged.videos);+ setChannels(merged.channels);} catch (err) {showToast(`Couldn't load videos. ${err.message}`, 'error');} finally {diff --git a/frontend/src/features/analytics/videos/videoLibrary.js b/frontend/src/features/analytics/videos/videoLibrary.jsindex 4ce0bdd..24bee53 100644--- a/frontend/src/features/analytics/videos/videoLibrary.js+++ b/frontend/src/features/analytics/videos/videoLibrary.js@@ -1,8 +1,32 @@// video library filters and totals; no JSX or path aliases so node --test can import it-import { VIEW_TIERS, filterByTier, matchesText } from '../../../lib/library.js';+import { VIEW_TIERS, filterByTier, matchesText, engagementPercent, parseIsoDuration } from '../../../lib/library.js';import { fmtNum } from '../../../utils/formatters.js';+// failed channels are left out; each video gains its channel, thumbnail, engagement and duration+export function mergeChannelVideos(channelAccounts, results) {+ const videos = [];+ const channels = [];+ results.forEach((result, i) => {+ if (result.status !== 'fulfilled') return;+ const acct = channelAccounts[i];+ const res = result.value;+ const channelTitle = acct.title || acct.channelTitle || 'Unknown channel';+ channels.push({ id: acct.id, title: channelTitle, account: acct });+ for (const video of res.videos || res.data?.videos || []) {+ videos.push({+ ...video,+ thumbnail: video.thumbnail || video.thumbnails?.medium || video.thumbnails?.high || video.thumbnails?.default || '',+ channelTitle,+ channelId: acct.id,+ engagementRate: engagementPercent(video.viewCount, video.likeCount, video.commentCount),+ durationSeconds: video.durationSeconds || parseIsoDuration(video.duration),+ });+ }+ });+ return { videos, channels };+}+export function watchUrl(videoId) {return `https://www.youtube.com/watch?v=${videoId}`;}diff --git a/frontend/src/features/analytics/videos/videoLibrary.test.js b/frontend/src/features/analytics/videos/videoLibrary.test.jsindex 92b52a2..0697129 100644--- a/frontend/src/features/analytics/videos/videoLibrary.test.js+++ b/frontend/src/features/analytics/videos/videoLibrary.test.js@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { watchUrl, filterAndSortVideos, videoStatsOf, nextSort, ariaSortOf, videosDescription } from './videoLibrary.js';+import { watchUrl, filterAndSortVideos, videoStatsOf, nextSort, ariaSortOf, videosDescription, mergeChannelVideos } from './videoLibrary.js';const videos = [{ videoId: 'a', title: 'Banana bread', channelId: 'c1', viewCount: 500, likeCount: 10, commentCount: 1, tags: ['baking'] },@@ -50,3 +50,22 @@ test('description and watch links', () => {assert.equal(videosDescription(false, 3, 2), '3 videos across 2 channels');assert.equal(watchUrl('xyz'), 'https://www.youtube.com/watch?v=xyz');});++test('channel videos merge with their channel and skip failed channels', () => {+ const channelAccounts = [{ id: 'c1', title: 'Alpha' }, { id: 'c2', channelTitle: 'Beta' }, { id: 'c3' }];+ const results = [+ { status: 'fulfilled', value: { videos: [{ videoId: 'a', viewCount: 200, likeCount: 10, commentCount: 0, duration: 'PT1M5S', thumbnails: { high: 'h.jpg' } }] } },+ { status: 'rejected', reason: new Error('quota') },+ { status: 'fulfilled', value: { data: { videos: [{ videoId: 'b', thumbnail: 't.jpg', durationSeconds: 30 }] } } },+ ];+ const merged = mergeChannelVideos(channelAccounts, results);+ assert.deepEqual(merged.channels.map(channel => [channel.id, channel.title]), [['c1', 'Alpha'], ['c3', 'Unknown channel']]);+ assert.equal(merged.channels[0].account, channelAccounts[0]);+ assert.deepEqual(merged.videos[0], {+ videoId: 'a', viewCount: 200, likeCount: 10, commentCount: 0, duration: 'PT1M5S', thumbnails: { high: 'h.jpg' },+ thumbnail: 'h.jpg', channelTitle: 'Alpha', channelId: 'c1', engagementRate: '5.00', durationSeconds: 65,+ });+ assert.equal(merged.videos[1].thumbnail, 't.jpg');+ assert.equal(merged.videos[1].durationSeconds, 30);+ assert.equal(merged.videos[1].engagementRate, '0.00');+});diff --git a/frontend/src/hooks/use-smooth-theme.js b/frontend/src/hooks/use-smooth-theme.jsindex bdc0978..4354738 100644--- a/frontend/src/hooks/use-smooth-theme.js+++ b/frontend/src/hooks/use-smooth-theme.js@@ -6,8 +6,7 @@ function resolve(theme) {return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';}-// Switches theme as one cross-fade of the whole page instead of every element easing at its own-// speed. The class is applied synchronously inside the transition so the new snapshot is complete.+// one page cross-fade; the class is set inside the transition so the new snapshot is completeexport function useSmoothTheme() {const { theme, resolvedTheme, setTheme } = useTheme();diff --git a/frontend/src/lib/accounts.js b/frontend/src/lib/accounts.jsindex 1f222b2..380e554 100644--- a/frontend/src/lib/accounts.js+++ b/frontend/src/lib/accounts.js@@ -1,4 +1,4 @@-// Platform helpers shared by every page. Kept free of JSX and path aliases so node --test can import it.+// platform helpers for every page; no jsx or path aliases so node --test can import itexport const PLATFORMS = ['youtube', 'instagram', 'reddit'];@@ -10,8 +10,8 @@ export const PLATFORM_META = {// Accounts saved before multi-platform support have no platform field and are YouTube channelsexport function platformOf(account) {- const p = account?.platform;- return p === 'instagram' || p === 'reddit' ? p : 'youtube';+ const platform = account?.platform;+ return platform === 'instagram' || platform === 'reddit' ? platform : 'youtube';}export function accountPath(account) {diff --git a/frontend/src/lib/accounts.test.js b/frontend/src/lib/accounts.test.jsindex 1b7758a..5d3f053 100644--- a/frontend/src/lib/accounts.test.js+++ b/frontend/src/lib/accounts.test.js@@ -2,41 +2,41 @@ import { test } from 'node:test';import assert from 'node:assert/strict';import { platformOf, accountPath, accountName, accountHandle, accountInitials, audienceOf, platformSummary } from './accounts.js';-const yt = { id: 'y1', title: 'Studio Dusk', customUrl: '@studiodusk', subscriberCount: 1200 };-const ig = { id: 'i1', platform: 'instagram', title: 'Paper Fold', username: 'paperfold', followersCount: 800 };-const rd = { id: 'r1', platform: 'reddit', username: 'ribbon', totalKarma: 50 };+const youtubeAccount = { id: 'y1', title: 'Studio Dusk', customUrl: '@studiodusk', subscriberCount: 1200 };+const instagramAccount = { id: 'i1', platform: 'instagram', title: 'Paper Fold', username: 'paperfold', followersCount: 800 };+const redditAccount = { id: 'r1', platform: 'reddit', username: 'ribbon', totalKarma: 50 };test('accounts without a platform are YouTube channels', () => {- assert.equal(platformOf(yt), 'youtube');- assert.equal(platformOf(ig), 'instagram');- assert.equal(platformOf(rd), 'reddit');+ assert.equal(platformOf(youtubeAccount), 'youtube');+ assert.equal(platformOf(instagramAccount), 'instagram');+ assert.equal(platformOf(redditAccount), 'reddit');});test('each platform routes to its own analytics page', () => {- assert.equal(accountPath(yt), '/channel/y1');- assert.equal(accountPath(ig), '/instagram/i1');- assert.equal(accountPath(rd), '/reddit/r1');+ assert.equal(accountPath(youtubeAccount), '/channel/y1');+ assert.equal(accountPath(instagramAccount), '/instagram/i1');+ assert.equal(accountPath(redditAccount), '/reddit/r1');});test('names and handles follow each platform convention', () => {- assert.equal(accountName(rd), 'u/ribbon');- assert.equal(accountName(ig), 'Paper Fold');- assert.equal(accountHandle(ig), '@paperfold');- assert.equal(accountHandle(yt), '@studiodusk');- assert.equal(accountHandle(rd), 'Reddit');+ assert.equal(accountName(redditAccount), 'u/ribbon');+ assert.equal(accountName(instagramAccount), 'Paper Fold');+ assert.equal(accountHandle(instagramAccount), '@paperfold');+ assert.equal(accountHandle(youtubeAccount), '@studiodusk');+ assert.equal(accountHandle(redditAccount), 'Reddit');});test('initials come from the title or username', () => {- assert.equal(accountInitials(yt), 'ST');+ assert.equal(accountInitials(youtubeAccount), 'ST');assert.equal(accountInitials({ title: 'u/ribbon' }), 'RI');assert.equal(accountInitials({}), '?');});test('audience uses subscribers, followers or karma', () => {- assert.deepEqual([yt, ig, rd].map(audienceOf), [1200, 800, 50]);+ assert.deepEqual([youtubeAccount, instagramAccount, redditAccount].map(audienceOf), [1200, 800, 50]);});test('the platform summary lists only platforms that have accounts', () => {- assert.equal(platformSummary([yt, ig, { ...ig, id: 'i2' }]), '1 YouTube, 2 Instagram');+ assert.equal(platformSummary([youtubeAccount, instagramAccount, { ...instagramAccount, id: 'i2' }]), '1 YouTube, 2 Instagram');assert.equal(platformSummary([]), '');});diff --git a/frontend/src/lib/chart.js b/frontend/src/lib/chart.jsindex 6f61690..312d528 100644--- a/frontend/src/lib/chart.js+++ b/frontend/src/lib/chart.js@@ -1,5 +1,4 @@-// Shared Recharts styling. Series follow the brand data-visualisation order; values are CSS variables-// so charts switch with the theme.+// series follow the brand chart order; values are css variables so charts follow the themeexport const SERIES = {primary: 'var(--chart-1)',diff --git a/frontend/src/lib/commandSearch.js b/frontend/src/lib/commandSearch.jsindex 6e9e354..59ade48 100644--- a/frontend/src/lib/commandSearch.js+++ b/frontend/src/lib/commandSearch.js@@ -6,16 +6,16 @@ function normalize(text) {// Higher is better; 0 means no match. Every query word must appear in the label or keywords.export function scoreCommand(command, query) {- const q = normalize(query);- if (!q) return 1;+ const needle = normalize(query);+ if (!needle) return 1;const label = normalize(command.label);const haystack = `${label} ${normalize(command.group)} ${(command.keywords || []).map(normalize).join(' ')}`;- const words = q.split(/\s+/);+ const words = needle.split(/\s+/);if (!words.every(w => haystack.includes(w))) return 0;- if (label === q) return 100;- if (label.startsWith(q)) return 80;+ if (label === needle) return 100;+ if (label.startsWith(needle)) return 80;if (label.split(/\s+/).some(part => part.startsWith(words[0]))) return 60;- if (label.includes(q)) return 40;+ if (label.includes(needle)) return 40;return 20;}diff --git a/frontend/src/lib/contact.js b/frontend/src/lib/contact.jsindex a691c38..9c6533f 100644--- a/frontend/src/lib/contact.js+++ b/frontend/src/lib/contact.js@@ -1,5 +1,4 @@-// Who people on this instance contact for access requests and scheduling problems.-// Self-hosters set VITE_ADMIN_EMAIL to their own address.+// who members contact for access and scheduling help; self-hosters set VITE_ADMIN_EMAILexport const ADMIN_EMAIL = import.meta.env?.VITE_ADMIN_EMAIL || '[email protected]';export function adminMailto(subject, body = '') {diff --git a/frontend/src/lib/googleIdentity.js b/frontend/src/lib/googleIdentity.jsindex 224612c..e219d70 100644--- a/frontend/src/lib/googleIdentity.js+++ b/frontend/src/lib/googleIdentity.js@@ -27,8 +27,7 @@ export async function sha256Hex(text) {return Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('');}-// Google embeds the hashed nonce in the ID token; Supabase receives the raw one and checks they match,-// so a captured token cannot be replayed.+// supabase checks the raw nonce against the hash in the token, so a captured token cannot replayexport async function createNonce() {const bytes = crypto.getRandomValues(new Uint8Array(32));const raw = btoa(String.fromCharCode(...bytes)).replace(/[+/=]/g, '');diff --git a/frontend/src/lib/holdProgress.test.js b/frontend/src/lib/holdProgress.test.jsindex 25e19a4..85ef42e 100644--- a/frontend/src/lib/holdProgress.test.js+++ b/frontend/src/lib/holdProgress.test.js@@ -26,57 +26,57 @@ function harness(duration = 1000) {}test('a full hold confirms exactly once', () => {- const h = harness(1000);- h.controller.start();- h.advance(400);- h.advance(400);- assert.equal(h.completed, 0);- h.advance(400);- assert.equal(h.completed, 1);- assert.equal(h.progress.at(-1), 1);- h.advance(400);- assert.equal(h.completed, 1, 'no further ticks after completion');+ const hold = harness(1000);+ hold.controller.start();+ hold.advance(400);+ hold.advance(400);+ assert.equal(hold.completed, 0);+ hold.advance(400);+ assert.equal(hold.completed, 1);+ assert.equal(hold.progress.at(-1), 1);+ hold.advance(400);+ assert.equal(hold.completed, 1, 'no further ticks after completion');});test('releasing early cancels and resets progress', () => {- const h = harness(1000);- h.controller.start();- h.advance(500);- h.controller.cancel();- assert.equal(h.progress.at(-1), 0);- h.advance(2000);- assert.equal(h.completed, 0);- assert.equal(h.controller.holding, false);+ const hold = harness(1000);+ hold.controller.start();+ hold.advance(500);+ hold.controller.cancel();+ assert.equal(hold.progress.at(-1), 0);+ hold.advance(2000);+ assert.equal(hold.completed, 0);+ assert.equal(hold.controller.holding, false);});test('a quick click never confirms', () => {- const h = harness(1200);- h.controller.start();- h.advance(16);- h.controller.cancel();- h.advance(5000);- assert.equal(h.completed, 0);+ const hold = harness(1200);+ hold.controller.start();+ hold.advance(16);+ hold.controller.cancel();+ hold.advance(5000);+ assert.equal(hold.completed, 0);});test('starting twice does not restart the timer', () => {- const h = harness(1000);- h.controller.start();- h.advance(600);- h.controller.start();- h.advance(500);- assert.equal(h.completed, 1);+ const hold = harness(1000);+ hold.controller.start();+ hold.advance(600);+ hold.controller.start();+ hold.advance(500);+ assert.equal(hold.completed, 1);});test('a completed controller ignores new holds until reset', () => {- const h = harness(100);- h.controller.start();- h.advance(150);- assert.equal(h.controller.completed, true);- h.controller.start();- h.advance(150);- assert.equal(h.completed, 1);- h.controller.reset();- h.controller.start();- h.advance(150);- assert.equal(h.completed, 2);+ const hold = harness(100);+ hold.controller.start();+ hold.advance(150);+ assert.equal(hold.controller.completed, true);+ hold.controller.start();+ hold.advance(150);+ assert.equal(hold.completed, 1);+ hold.controller.reset();+ hold.controller.start();+ hold.advance(150);+ assert.equal(hold.completed, 2);});diff --git a/frontend/src/lib/library.js b/frontend/src/lib/library.jsindex f49eafd..d0cb6f6 100644--- a/frontend/src/lib/library.js+++ b/frontend/src/lib/library.js@@ -2,9 +2,9 @@export function parseIsoDuration(iso) {if (!iso || iso === 'P0D') return 0;- const m = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);- if (!m) return 0;- return (parseInt(m[1] || 0, 10) * 3600) + (parseInt(m[2] || 0, 10) * 60) + parseInt(m[3] || 0, 10);+ const parts = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);+ if (!parts) return 0;+ return (parseInt(parts[1] || 0, 10) * 3600) + (parseInt(parts[2] || 0, 10) * 60) + parseInt(parts[3] || 0, 10);}// (likes + comments) / views as a percentage string, matching the backend's two-decimal format@@ -33,9 +33,9 @@ export function filterByTier(items, tiers, tierValue, field) {const tier = tiers.find(t => t.value === tierValue);if (!tier) return items;return items.filter(item => {- const n = item[field] || 0;- if (tier.min != null && n < tier.min) return false;- if (tier.max != null && n >= tier.max) return false;+ const value = item[field] || 0;+ if (tier.min != null && value < tier.min) return false;+ if (tier.max != null && value >= tier.max) return false;return true;});}@@ -52,7 +52,7 @@ export function pageSlice(items, page, perPage) {}export function matchesText(values, query) {- const q = query.trim().toLowerCase();- if (!q) return true;- return values.some(v => typeof v === 'string' && v.toLowerCase().includes(q));+ const needle = query.trim().toLowerCase();+ if (!needle) return true;+ return values.some(v => typeof v === 'string' && v.toLowerCase().includes(needle));}diff --git a/frontend/src/utils/formatters.js b/frontend/src/utils/formatters.jsindex 608cd95..08748bc 100644--- a/frontend/src/utils/formatters.js+++ b/frontend/src/utils/formatters.js@@ -29,11 +29,11 @@ export function fmtDateShort(d) {export function fmtDuration(seconds) {if (!seconds) return '0:00';- const h = Math.floor(seconds / 3600);- const m = Math.floor((seconds % 3600) / 60);- const s = seconds % 60;- if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;- return `${m}:${String(s).padStart(2, '0')}`;+ const hours = Math.floor(seconds / 3600);+ const minutes = Math.floor((seconds % 3600) / 60);+ const secs = seconds % 60;+ if (hours > 0) return `${hours}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;+ return `${minutes}:${String(secs).padStart(2, '0')}`;}export function fmtPercent(n) {diff --git a/frontend/src/utils/trackedContent.js b/frontend/src/utils/trackedContent.jsindex 07b307f..01890fc 100644--- a/frontend/src/utils/trackedContent.js+++ b/frontend/src/utils/trackedContent.js@@ -1,13 +1,11 @@-// Views for a tracked item. YouTube reports a real view count; Reddit removed view_count-// from their API in 2018, so Reddit views are whatever the user entered by hand.+// youtube reports real views; reddit dropped view_count in 2018, so its views are typed by handexport function trackedViews(item) {if (!item) return 0;if (item.contentType === 'youtube') return item.viewCount ?? 0;return item.manualViews ?? 0;}-// True when the item is a Reddit post whose views have not been entered yet, so the UI can-// distinguish "no views recorded" from a genuine zero+// false for reddit posts with no views entered, so the ui can tell that apart from a real zeroexport function hasTrackedViews(item) {if (!item) return false;if (item.contentType === 'youtube') return item.viewCount !== undefined && item.viewCount !== null;