Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
feat(docs): public documentation site at /docs
spacesdrive5a034f001f01
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 3214a41..bf9a200 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -8,6 +8,7 @@ import { AppProvider } from './context/AppContext';import ProtectedRoute from './components/ProtectedRoute';import MainLayout from './layout/index';import Login from './pages/Login';+import { docsChildRoutes } from './docs/routes';const Overview = lazy(() => import('./features/analytics/overview/Overview'));const ChannelAnalytics = lazy(() => import('./features/analytics/channel/ChannelAnalytics'));@@ -23,12 +24,18 @@ const RedditPosts = lazy(() => import('./features/analytics/reddit/Redditconst RedditPostsAll = lazy(() => import('./features/analytics/reddit/RedditPostsAll'));const TrackedContent = lazy(() => import('./features/analytics/tracked/TrackedContent'));const TrackedCategory = lazy(() => import('./features/analytics/tracked/TrackedCategory'));+const DocsLayout = lazy(() => import('./docs/DocsLayout'));const router = createBrowserRouter([{path: '/login',element: <Login />,},+ {+ path: '/docs',+ element: <DocsLayout />,+ children: docsChildRoutes,+ },{path: '/',element: (diff --git a/frontend/src/components/CommandPalette.jsx b/frontend/src/components/CommandPalette.jsxindex 1ec644d..ad1b33d 100644--- a/frontend/src/components/CommandPalette.jsx+++ b/frontend/src/components/CommandPalette.jsx@@ -3,8 +3,7 @@ import { useNavigate } from 'react-router-dom';import { useSmoothTheme } from '@/hooks/use-smooth-theme';import {LayoutDashboard, PlaySquare, Scissors, Clapperboard, MessagesSquare, Bookmark, Send,- Users, Settings, RefreshCw, Sun, Moon, Monitor, LogOut, Tag, Plus,-} from 'lucide-react';+ Users, Settings, RefreshCw, Sun, Moon, Monitor, LogOut, Tag, Plus, BookOpen } from 'lucide-react';import {Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandShortcut,} from '@/components/ui/command';@@ -45,6 +44,7 @@ export default function CommandPalette({ open, onOpenChange, accounts, categorieicon: Tag, run: () => navigate(`/tracked-content/category/${encodeURIComponent(category)}`),})),{ id: 'action:add-account', group: 'Actions', label: 'Add an account', keywords: ['connect', 'youtube', 'instagram', 'reddit'], icon: Plus, run: () => navigate('/accounts?add=1') },+ { id: 'action:docs', group: 'Actions', label: 'Open documentation', keywords: ['help', 'guide', 'docs', 'setup', 'self-host'], icon: BookOpen, run: () => navigate('/docs') },{ id: 'action:refresh', group: 'Actions', label: 'Refresh all accounts', keywords: ['sync', 'update'], icon: RefreshCw, run: onRefreshAll },{ id: 'action:theme-light', group: 'Theme', label: 'Use light theme', keywords: ['appearance', 'paper'], icon: Sun, run: () => setTheme('light') },{ id: 'action:theme-dark', group: 'Theme', label: 'Use dark theme', keywords: ['appearance', 'dusk'], icon: Moon, run: () => setTheme('dark') },diff --git a/frontend/src/docs/DocsLayout.jsx b/frontend/src/docs/DocsLayout.jsxnew file mode 100644index 0000000..7e0d7bf--- /dev/null+++ b/frontend/src/docs/DocsLayout.jsx@@ -0,0 +1,282 @@+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 { 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);++ 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;+ };+ 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 };+}++export default function DocsLayout() {+ const location = useLocation();+ const { session } = useAuth();+ const { resolvedTheme, setTheme } = useSmoothTheme();+ const [searchOpen, setSearchOpen] = useState(false);+ const [menuOpen, setMenuOpen] = useState(false);+ const [copied, setCopied] = useState(false);+ const articleRef = useRef(null);+ const tab = tabForPath(location.pathname);+ const { prev, next } = neighbours(location.pathname);+ const { items: toc, active } = useTableOfContents(articleRef, location.pathname);+ const isDark = resolvedTheme === 'dark';++ useEffect(() => {+ if (!location.hash) window.scrollTo({ top: 0 });+ 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);+ }, []);++ const copyPage = useCallback(async () => {+ try {+ await navigator.clipboard.writeText(articleRef.current?.innerText || '');+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ } catch {+ setCopied(false);+ }+ }, []);++ 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>++ <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} />+ </aside>++ <main id="docs-content" className="min-w-0 flex-1 px-5 py-10 sm:px-8 lg:px-12">+ <div className="mx-auto flex max-w-[50rem] flex-col">+ <div className="mb-2 flex items-center justify-between gap-3">+ <p className="eyebrow text-brand-text">{tab.label}</p>+ <Button variant="outline" size="xs" onClick={copyPage} aria-label="Copy this page as text">+ {copied ? <Check className="text-success" /> : <Copy />}+ {copied ? 'Copied' : 'Copy page'}+ </Button>+ </div>+ <article ref={articleRef} className="animate-fold-in">+ <Suspense fallback={<div className="flex flex-col gap-4"><Skeleton className="h-11 w-2/3" /><Skeleton className="h-5 w-full" /><Skeleton className="h-64 rounded-card" /></div>}>+ <Outlet />+ </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>+ </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>+ )}+ </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>++ <DocsSearch open={searchOpen} onOpenChange={setSearchOpen} />+ </div>+ );+}diff --git a/frontend/src/docs/components.jsx b/frontend/src/docs/components.jsxnew file mode 100644index 0000000..c20d746--- /dev/null+++ b/frontend/src/docs/components.jsx@@ -0,0 +1,179 @@+import React, { useState } from 'react';+import { Link } from 'react-router-dom';+import { Info, AlertTriangle, Lightbulb, ShieldAlert, Check, Copy, ArrowRight } from 'lucide-react';+import { cn } from '@/lib/utils';+import { slugify } from './slug';++// Building blocks for documentation pages. Headings get ids so the "On this page" list can find them.++function textOf(node) {+ if (typeof node === 'string' || typeof node === 'number') return String(node);+ if (Array.isArray(node)) return node.map(textOf).join('');+ if (node?.props?.children) return textOf(node.props.children);+ return '';+}++export function DocTitle({ title, lead }) {+ return (+ <header className="mb-10 flex flex-col gap-3">+ <h1 className="font-heading text-[2.25rem] leading-[2.8125rem] font-semibold tracking-[-0.02em] text-ink">{title}</h1>+ {lead && <p className="text-lg leading-7 text-ink-muted">{lead}</p>}+ </header>+ );+}++export function H2({ children, id }) {+ return (+ <h2 id={id || slugify(textOf(children))} data-toc="2" className="mt-12 mb-4 scroll-mt-32 font-heading text-2xl leading-8 font-semibold tracking-[-0.02em] text-ink first:mt-0">+ {children}+ </h2>+ );+}++export function H3({ children, id }) {+ return (+ <h3 id={id || slugify(textOf(children))} data-toc="3" className="mt-8 mb-3 scroll-mt-32 font-heading text-xl leading-8 font-semibold tracking-[-0.01em] text-ink">+ {children}+ </h3>+ );+}++export function P({ children, className }) {+ return <p className={cn('my-4 text-base leading-7 text-ink-muted [&_strong]:font-semibold [&_strong]:text-ink', className)}>{children}</p>;+}++export function UL({ children }) {+ return <ul className="my-4 flex list-disc flex-col gap-2 pl-6 text-base leading-7 text-ink-muted marker:text-ink-faint [&_strong]:font-semibold [&_strong]:text-ink">{children}</ul>;+}++export function OL({ children }) {+ return <ol className="my-4 flex list-decimal flex-col gap-2 pl-6 text-base leading-7 text-ink-muted marker:text-ink-faint [&_strong]:font-semibold [&_strong]:text-ink">{children}</ol>;+}++export function Code({ children }) {+ return <code className="rounded-sm border border-line bg-surface-sunken px-1.5 py-0.5 font-mono text-[0.875em] text-ink">{children}</code>;+}++export function A({ to, href, children }) {+ const cls = 'font-medium text-brand-text underline decoration-brand-text/40 underline-offset-4 hover:decoration-brand-text';+ if (to) return <Link to={to} className={cls}>{children}</Link>;+ return <a href={href} target="_blank" rel="noopener noreferrer" className={cls}>{children}</a>;+}++const CALLOUTS = {+ note: { icon: Info, cls: 'border-info/30 bg-info-soft', iconCls: 'text-info', label: 'Note' },+ tip: { icon: Lightbulb, cls: 'border-success/30 bg-success-soft', iconCls: 'text-success', label: 'Tip' },+ warning: { icon: AlertTriangle, cls: 'border-warning/30 bg-warning-soft', iconCls: 'text-warning', label: 'Warning' },+ danger: { icon: ShieldAlert, cls: 'border-danger/30 bg-danger-soft', iconCls: 'text-danger', label: 'Important' },+};++export function Callout({ type = 'note', title, children }) {+ const c = CALLOUTS[type];+ const Icon = c.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="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>+ {children && <div className="[&>p]:m-0 flex flex-col gap-2">{children}</div>}+ </div>+ </div>+ );+}++export function CodeBlock({ children, title }) {+ const [copied, setCopied] = useState(false);+ const text = String(children).replace(/^\n/, '').replace(/\n\s*$/, '');+ return (+ <div className="my-6 overflow-hidden rounded-field border border-line bg-surface-sunken">+ <div className="flex items-center justify-between gap-3 border-b border-line px-4 py-2">+ <span className="font-mono text-caption text-ink-faint">{title || 'Terminal'}</span>+ <button+ type="button"+ onClick={async () => { try { await navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 1500); } catch { setCopied(false); } }}+ className="inline-flex items-center gap-1.5 rounded-row px-2 py-1 text-caption text-ink-muted transition-colors hover:bg-surface-hover hover:text-ink"+ >+ {copied ? <Check className="size-3.5 text-success" /> : <Copy className="size-3.5" />}+ {copied ? 'Copied' : 'Copy'}+ </button>+ </div>+ <pre className="overflow-x-auto px-4 py-3.5 font-mono text-[0.8125rem] leading-6 text-ink"><code>{text}</code></pre>+ </div>+ );+}++export function Steps({ children }) {+ return <ol className="my-6 flex flex-col [counter-reset:step]">{children}</ol>;+}++export function Step({ title, children }) {+ return (+ <li className="relative flex gap-4 pb-8 last:pb-0 [counter-increment:step] before:absolute before:top-9 before:bottom-1 before:left-[0.9375rem] before:w-px before:bg-line last:before:hidden">+ <span className="flex size-8 shrink-0 items-center justify-center rounded-full border border-line bg-surface-raised font-mono text-small font-medium text-ink before:content-[counter(step)]" aria-hidden="true" />+ <div className="flex min-w-0 flex-1 flex-col pt-1">+ <h3 id={slugify(title)} data-toc="3" className="scroll-mt-32 font-heading text-lg leading-7 font-semibold text-ink">{title}</h3>+ <div className="text-base leading-7 text-ink-muted [&>*:first-child]:mt-2 [&_strong]:font-semibold [&_strong]:text-ink">{children}</div>+ </div>+ </li>+ );+}++export function Table({ head, rows }) {+ return (+ <div className="my-6 overflow-x-auto rounded-field border border-line">+ <table className="w-full min-w-[36rem] text-left text-[0.875rem] leading-6">+ <thead className="border-b border-line bg-surface-sunken/60">+ <tr>{head.map(h => <th key={h} className="px-4 py-2.5 font-semibold text-ink">{h}</th>)}</tr>+ </thead>+ <tbody>+ {rows.map((row, i) => (+ <tr key={i} className="border-b border-divider last:border-0 align-top">+ {row.map((cell, j) => <td key={j} className="px-4 py-3 text-ink-muted [&_strong]:font-semibold [&_strong]:text-ink">{cell}</td>)}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++// Image-topped path cards. The art is the brand fold band with a ribbon crop, tinted per card.+export function PathCards({ children }) {+ return <div className="my-8 grid grid-cols-1 gap-4 md:grid-cols-3">{children}</div>;+}++const CARD_ART = [+ 'linear-gradient(120deg, #C11F2F 0%, #C11F2F 35%, #9A1423 70%, #5E0B14 100%)',+ 'linear-gradient(120deg, #2A1D21 0%, #5E0B14 60%, #9A1423 100%)',+ 'linear-gradient(120deg, #E8A33D 0%, #C11F2F 65%, #5E0B14 100%)',+];++export function PathCard({ to, title, children, art = 0 }) {+ return (+ <Link+ to={to}+ className="group flex flex-col overflow-hidden rounded-panel border border-line bg-surface-raised transition-colors duration-(--duration-base) hover:border-line-strong/50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"+ >+ <div className="relative h-36 overflow-hidden" style={{ background: CARD_ART[art % CARD_ART.length] }}>+ <img src="/Logos/twiligent-mark-white.svg" alt="" className="absolute -right-6 -bottom-10 w-40 opacity-20 transition-transform duration-(--duration-slow) ease-(--ease-fold) group-hover:-translate-y-1" />+ </div>+ <div className="flex flex-1 flex-col gap-2 p-5">+ <p className="flex items-center gap-1.5 font-heading text-lg font-semibold text-ink">+ {title}+ <ArrowRight className="size-4 text-ink-faint transition-transform duration-(--duration-base) group-hover:translate-x-0.5" />+ </p>+ <p className="text-[0.9375rem] leading-6 text-ink-muted">{children}</p>+ </div>+ </Link>+ );+}++export function Badge({ children, tone = 'neutral' }) {+ const tones = {+ neutral: 'bg-surface-sunken text-ink-muted',+ required: 'bg-brand-soft text-brand-text',+ optional: 'bg-info-soft text-info',+ secret: 'bg-warning-soft text-warning',+ };+ return <span className={cn('inline-flex h-5 items-center rounded-pill px-2 text-caption font-semibold whitespace-nowrap', tones[tone])}>{children}</span>;+}diff --git a/frontend/src/docs/nav.js b/frontend/src/docs/nav.jsnew file mode 100644index 0000000..1d19138--- /dev/null+++ b/frontend/src/docs/nav.js@@ -0,0 +1,107 @@+// Documentation structure: tabs, sidebar groups, and pages. Page components are mapped in pages/index.js.++export const DOC_TABS = [+ {+ id: 'overview',+ label: 'Overview',+ groups: [+ {+ label: null,+ pages: [+ { slug: '', title: 'Introduction', keywords: ['start', 'what is twiligent', 'paths'] },+ { slug: 'concepts', title: 'Members and administrators', keywords: ['instance', 'roles', 'who does what', 'shared'] },+ ],+ },+ ],+ },+ {+ id: 'use',+ label: 'Using Twiligent',+ groups: [+ {+ label: 'Get started',+ pages: [+ { slug: 'use/getting-started', title: 'Sign in and first steps', keywords: ['account', 'sign up', 'login'] },+ { slug: 'use/connect-accounts', title: 'Connect your accounts', keywords: ['youtube', 'instagram', 'reddit', 'tester', 'cookie'] },+ ],+ },+ {+ label: 'Work with Twiligent',+ pages: [+ { slug: 'use/analytics', title: 'Read your analytics', keywords: ['overview', 'videos', 'shorts', 'reels', 'charts'] },+ { slug: 'use/publishing', title: 'Publish and schedule', keywords: ['instagram', 'post', 'reel', 'story', 'bulk', 'schedule'] },+ { slug: 'use/tracked-content', title: 'Track content', keywords: ['reddit posts', 'youtube videos', 'categories', 'views'] },+ ],+ },+ {+ label: 'Help',+ pages: [+ { slug: 'use/troubleshooting', title: 'Troubleshooting', keywords: ['errors', 'pending', 'failed', 'contact', 'administrator'] },+ ],+ },+ ],+ },+ {+ id: 'self-host',+ label: 'Run your own',+ groups: [+ {+ label: 'Plan',+ pages: [+ { slug: 'self-host', title: 'Self-hosting overview', keywords: ['requirements', 'cost', 'accounts needed', 'architecture'] },+ ],+ },+ {+ label: 'Set up services',+ pages: [+ { slug: 'self-host/supabase', title: 'Supabase', keywords: ['database', 'auth', 'sql', 'rls', 'keys'] },+ { slug: 'self-host/youtube', title: 'YouTube API key', keywords: ['google cloud', 'data api'] },+ { slug: 'self-host/instagram', title: 'Instagram app', keywords: ['meta', 'facebook', 'oauth', 'redirect', 'tester', 'app review'] },+ { slug: 'self-host/cloudinary', title: 'Cloudinary', keywords: ['media', 'upload preset', 'cdn'] },+ { slug: 'self-host/redis', title: 'Upstash Redis (optional)', keywords: ['cache', 'redis'] },+ ],+ },+ {+ label: 'Deploy',+ pages: [+ { slug: 'self-host/deploy-backend', title: 'Deploy the backend', keywords: ['cloudflare', 'worker', 'wrangler', 'secrets'] },+ { slug: 'self-host/deploy-frontend', title: 'Deploy the frontend', keywords: ['cloudflare pages', 'vite', 'env'] },+ { slug: 'self-host/github', title: 'GitHub automation', keywords: ['actions', 'scheduling backup', 'deploy on push'] },+ { slug: 'self-host/checklist', title: 'Launch checklist', keywords: ['verify', 'test', 'done'] },+ ],+ },+ ],+ },+ {+ id: 'reference',+ label: 'Reference',+ groups: [+ {+ label: null,+ pages: [+ { slug: 'reference/environment', title: 'Environment variables', keywords: ['keys', 'secrets', 'config', 'env'] },+ { slug: 'reference/scheduling', title: 'How scheduling works', keywords: ['cron', 'status', 'pending', 'claim'] },+ { slug: 'reference/security', title: 'Security', keywords: ['rls', 'service key', 'tokens', 'signups'] },+ { slug: 'reference/faq', title: 'FAQ', keywords: ['questions', 'cost', 'limits'] },+ ],+ },+ ],+ },+];++export const ALL_DOC_PAGES = DOC_TABS.flatMap(tab => tab.groups.flatMap(group => group.pages.map(page => ({+ ...page,+ tabId: tab.id,+ tabLabel: tab.label,+ path: page.slug ? `/docs/${page.slug}` : '/docs',+}))));++export function tabForPath(pathname) {+ const page = ALL_DOC_PAGES.find(p => p.path === pathname);+ return DOC_TABS.find(t => t.id === page?.tabId) || DOC_TABS[0];+}++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 };+}diff --git a/frontend/src/docs/nav.test.js b/frontend/src/docs/nav.test.jsnew file mode 100644index 0000000..3212c19--- /dev/null+++ b/frontend/src/docs/nav.test.js@@ -0,0 +1,30 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { ALL_DOC_PAGES, neighbours, tabForPath } from './nav.js';+import { DOC_ROUTE_SLUGS } from './routes.js';+import { slugify } from './slug.js';++test('every page in the navigation has a route, and every route is in the navigation', () => {+ const navSlugs = ALL_DOC_PAGES.map(p => p.slug).sort();+ assert.deepEqual([...DOC_ROUTE_SLUGS].sort(), navSlugs);+});++test('page paths are unique', () => {+ const paths = ALL_DOC_PAGES.map(p => p.path);+ assert.equal(new Set(paths).size, paths.length);+});++test('neighbours link the first and last pages correctly', () => {+ assert.equal(neighbours('/docs').prev, null);+ assert.equal(neighbours('/docs').next.path, '/docs/concepts');+ assert.equal(neighbours(ALL_DOC_PAGES.at(-1).path).next, null);+});++test('tabForPath falls back to the first tab for unknown paths', () => {+ assert.equal(tabForPath('/docs/self-host/supabase').id, 'self-host');+ assert.equal(tabForPath('/docs/nope').id, 'overview');+});++test('slugify makes heading ids', () => {+ assert.equal(slugify('Why row level security, with no policies?'), 'why-row-level-security-with-no-policies');+});diff --git a/frontend/src/docs/pages/Overview.jsx b/frontend/src/docs/pages/Overview.jsxnew file mode 100644index 0000000..71cd37e--- /dev/null+++ b/frontend/src/docs/pages/Overview.jsx@@ -0,0 +1,95 @@+import React from 'react';+import { DocTitle, H2, H3, P, UL, A, Callout, PathCards, PathCard, Table } from '../components';++export function Introduction() {+ return (+ <>+ <DocTitle+ title="Twiligent documentation"+ lead="Guides for everyone who uses Twiligent, and for the people who run their own copy of it."+ />++ <H2>What Twiligent does</H2>+ <P>+ Twiligent brings your YouTube channels, Instagram professional accounts and Reddit profiles into one place. You see their analytics side by side, publish and schedule Instagram posts, and follow individual Reddit posts and YouTube videos that matter to you.+ </P>+ <P>+ Twiligent is self-hosted. Every copy of it, called an <strong>instance</strong>, belongs to the person or team who set it up. That person is the instance's <strong>administrator</strong>. Everyone who signs in to it is a <strong>member</strong>.+ </P>++ <H2>Choose your path</H2>+ <P>Which guides you need depends on one question: did someone give you a Twiligent link to sign in to, or are you setting Twiligent up yourself?</P>+ <PathCards>+ <PathCard to="/docs/use/getting-started" title="Use Twiligent" art={0}>+ You signed in to an instance someone else runs. Connect your accounts, read analytics and schedule posts. Nothing to install.+ </PathCard>+ <PathCard to="/docs/self-host" title="Run your own" art={1}>+ You want your own instance. Set up Supabase, the platform keys and Cloudflare, step by step, mostly on free plans.+ </PathCard>+ <PathCard to="/docs/reference/environment" title="Reference" art={2}>+ Every environment variable, how scheduling works, and the security model, in one place.+ </PathCard>+ </PathCards>++ <H2>What you can do</H2>+ <Table+ head={['Area', 'What it covers']}+ rows={[+ [<strong>Analytics</strong>, 'Subscribers, followers, karma, views, likes and comments across platforms, with per-account detail pages.'],+ [<strong>Libraries</strong>, 'Every YouTube video and Short, every Instagram reel, post and video, and every Reddit post, searchable and filterable.'],+ [<strong>Publishing</strong>, 'Publish photos, Reels and Stories to Instagram now, schedule them for later, or upload many files at once.'],+ [<strong>Tracked content</strong>, 'Follow any Reddit post or YouTube video by link, group them into categories and compare them.'],+ ]}+ />++ <Callout type="note" title="Not sure whether you are a member or an administrator?">+ <p>If you only ever opened a link and signed in, you are a member: read <A to="/docs/use/getting-started">Using Twiligent</A>. If you created the Supabase project and deployed the app, you are the administrator: read <A to="/docs/self-host">Run your own</A>.</p>+ </Callout>+ </>+ );+}++export function Concepts() {+ return (+ <>+ <DocTitle+ title="Members and administrators"+ lead="Who sets up what, and what each person can and cannot change."+ />++ <H2>Two roles</H2>+ <H3>Member</H3>+ <P>+ A member signs in to an existing instance with an email and password. Members connect their own YouTube, Instagram and Reddit accounts, read their analytics, publish and schedule posts, and track content. A member never needs a server, a database, API keys or GitHub.+ </P>+ <H3>Administrator</H3>+ <P>+ The administrator runs the instance. They create the Supabase project, get the platform keys (YouTube, Instagram, Cloudinary), deploy the backend and frontend to Cloudflare, and keep them running. The administrator is also the person members contact for Instagram tester access or when something is not working.+ </P>++ <H2>Who does what</H2>+ <Table+ head={['Task', 'Member', 'Administrator']}+ rows={[+ ['Sign in and add accounts', 'Yes', 'Yes'],+ ['Read analytics, publish and schedule', 'Yes', 'Yes'],+ ['Request Instagram tester access', 'Yes, by email', 'Adds the tester in the Meta app'],+ ['Set up scheduling', 'Nothing to do. The server publishes scheduled posts.', 'Deploys the backend once; optionally adds the GitHub backup'],+ ['Create and own the Supabase project', 'No', 'Yes'],+ ['Hold API keys and secrets', 'Never', 'Yes, as server secrets only'],+ ['Deploy updates', 'No', 'Yes'],+ ]}+ />++ <H2>What is shared and what is yours</H2>+ <UL>+ <li><strong>Shared by everyone on the instance:</strong> the YouTube API key, the Instagram (Meta) app, the Cloudinary account and the server itself. These are set once by the administrator.</li>+ <li><strong>Yours alone:</strong> the accounts you connect, their access tokens and cookies, your scheduled posts and your tracked content. Other members cannot see them, and the server never sends tokens or cookies back to any browser.</li>+ </UL>++ <Callout type="tip" title="Running Twiligent just for yourself?">+ <p>Then you are both. Follow <A to="/docs/self-host">Run your own</A> once, then use the app like any member.</p>+ </Callout>+ </>+ );+}diff --git a/frontend/src/docs/pages/Reference.jsx b/frontend/src/docs/pages/Reference.jsxnew file mode 100644index 0000000..decea0c--- /dev/null+++ b/frontend/src/docs/pages/Reference.jsx@@ -0,0 +1,181 @@+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.'],+];++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></>, '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>+ </>+ );+}diff --git a/frontend/src/docs/pages/SelfHost.jsx b/frontend/src/docs/pages/SelfHost.jsxnew file mode 100644index 0000000..384a2af--- /dev/null+++ b/frontend/src/docs/pages/SelfHost.jsx@@ -0,0 +1,424 @@+import React from 'react';+import { DocTitle, H2, H3, P, UL, OL, A, Code, Callout, CodeBlock, Steps, Step, Table, Badge } from '../components';++export const SCHEMA_SQL = `+create table accounts (+ id text primary key,+ user_id uuid not null references auth.users(id) on delete cascade,+ platform text not null,+ data jsonb not null+);+create index accounts_user_id_idx on accounts(user_id);++create table settings (+ user_id uuid not null references auth.users(id) on delete cascade,+ key text not null,+ value jsonb,+ primary key (user_id, key)+);++create table scheduled_posts (+ id text primary key,+ user_id uuid not null references auth.users(id) on delete cascade,+ account_id text not null references accounts(id) on delete cascade,+ status text not null default 'pending',+ scheduled_at timestamptz not null,+ data jsonb+);+create index scheduled_posts_due_idx on scheduled_posts(status, scheduled_at);++create table tracked_posts (+ id text primary key,+ user_id uuid not null references auth.users(id) on delete cascade,+ account_id text references accounts(id) on delete set null,+ url text not null,+ label text not null default '',+ category text not null default '',+ content_type text not null default 'reddit',+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ data jsonb+);+create index tracked_posts_user_id_idx on tracked_posts(user_id);++alter table accounts enable row level security;+alter table settings enable row level security;+alter table scheduled_posts enable row level security;+alter table tracked_posts enable row level security;+`;++const RLS_SQL = `+alter table accounts enable row level security;+alter table settings enable row level security;+alter table scheduled_posts enable row level security;+alter table tracked_posts enable row level security;+`;++export function Overview() {+ return (+ <>+ <DocTitle title="Self-hosting overview" lead="What you need to run your own Twiligent, what it costs, and the order to set it up in." />++ <Callout type="note" title="Only the administrator follows this section">+ <p>If you signed in to a Twiligent link someone gave you, you do not need any of this. The server, the keys and scheduling are already handled. Read <A to="/docs/use/getting-started">Using Twiligent</A> instead.</p>+ </Callout>++ <H2>How the pieces fit</H2>+ <P>Twiligent has two parts. The <strong>frontend</strong> is the website people sign in to, hosted on Cloudflare Pages. The <strong>backend</strong> is a Cloudflare Worker that talks to YouTube, Instagram and Reddit, stores data in Supabase, and publishes scheduled posts every 15 minutes. All secrets live in the backend; the frontend only holds values that are safe to be public.</P>++ <H2>Accounts you need</H2>+ <Table+ head={['Service', 'Needed for', '', 'Cost']}+ rows={[+ ['Supabase', 'Sign-in and the database', <Badge tone="required">Required</Badge>, 'Free plan is enough'],+ ['Cloudflare', 'Hosting the backend and frontend', <Badge tone="required">Required</Badge>, 'Free plan is enough'],+ ['Google Cloud', 'YouTube analytics', <Badge tone="optional">For YouTube</Badge>, 'Free, 10,000 quota units a day'],+ ['Meta for Developers', 'Connecting Instagram and publishing', <Badge tone="optional">For Instagram</Badge>, 'Free'],+ ['Cloudinary', 'Hosting media before Instagram fetches it', <Badge tone="optional">For publishing</Badge>, 'Free plan is enough'],+ ['Upstash', 'Caching to save API quota and speed pages up', <Badge tone="optional">Optional</Badge>, 'Free plan is enough'],+ ['GitHub', 'Deploy on every push, and a backup scheduler', <Badge tone="optional">Optional</Badge>, 'Free'],+ ]}+ />+ <P>Reddit needs no key. Each member pastes their own Reddit session cookie when they connect an account.</P>++ <H2>Order of setup</H2>+ <OL>+ <li><A to="/docs/self-host/supabase">Supabase</A>: create the project, the tables and turn on row level security.</li>+ <li><A to="/docs/self-host/youtube">YouTube API key</A>, <A to="/docs/self-host/instagram">Instagram app</A>, <A to="/docs/self-host/cloudinary">Cloudinary</A> and optionally <A to="/docs/self-host/redis">Upstash Redis</A>, in any order.</li>+ <li><A to="/docs/self-host/deploy-backend">Deploy the backend</A> and give it every secret.</li>+ <li><A to="/docs/self-host/deploy-frontend">Deploy the frontend</A>.</li>+ <li>Optionally connect <A to="/docs/self-host/github">GitHub</A>, then run through the <A to="/docs/self-host/checklist">launch checklist</A>.</li>+ </OL>+ <P>Keep a private note open while you work. Each page tells you which values to copy, and <A to="/docs/reference/environment">Environment variables</A> lists all of them in one table.</P>++ <H2>What you need on your computer</H2>+ <UL>+ <li>Node.js 20 or newer, and Git.</li>+ <li>A copy of the code: <Code>git clone https://github.com/spacesdrive/twiligent.git</Code></li>+ </UL>+ </>+ );+}++export function Supabase() {+ return (+ <>+ <DocTitle title="Supabase" lead="Supabase handles sign-in and stores every account, scheduled post and tracked item." />++ <Steps>+ <Step title="Create a project">+ <P>Sign in at <A href="https://supabase.com/dashboard">supabase.com/dashboard</A> and choose <strong>New project</strong>. Pick a name, a strong database password and the region closest to you. Wait about two minutes for it to start.</P>+ </Step>+ <Step title="Create the tables">+ <P>Open <strong>SQL Editor</strong>, choose <strong>New query</strong>, paste the SQL below and choose <strong>Run</strong>. It creates the four tables Twiligent uses and turns on row level security for each.</P>+ <CodeBlock title="schema.sql">{SCHEMA_SQL}</CodeBlock>+ </Step>+ <Step title="Configure sign-in">+ <P>Open <strong>Authentication</strong>, then <strong>Sign In / Providers</strong>, then <strong>Email</strong>.</P>+ <UL>+ <li>Turn off <strong>Confirm email</strong> unless you have set up an email provider. Otherwise new members never receive the confirmation and cannot sign in.</li>+ <li>To keep the instance private, turn off <strong>Allow new users to sign up</strong> after you and your team have created accounts. You can also add members yourself under <strong>Authentication</strong>, <strong>Users</strong>, <strong>Add user</strong>.</li>+ </UL>+ </Step>+ <Step title="Copy the project URL">+ <P>Open <strong>Project Settings</strong>, then <strong>Data API</strong> (or <strong>Integrations</strong>, <strong>Data API</strong>). Copy the <strong>Project URL</strong>, which looks like <Code>https://abcdefgh.supabase.co</Code>. It is used as <Code>SUPABASE_URL</Code> and <Code>VITE_SUPABASE_URL</Code>.</P>+ </Step>+ <Step title="Copy the two keys">+ <P>Open <strong>Project Settings</strong>, then <strong>API Keys</strong>. Supabase shows either the new key format or the legacy one; both work.</P>+ <Table+ head={['Key', 'Looks like', 'Used as', 'Safety']}+ rows={[+ ['Publishable key (legacy: anon)', <Code>sb_publishable_...</Code>, <><Code>SUPABASE_ANON_KEY</Code> and <Code>VITE_SUPABASE_ANON_KEY</Code></>, <Badge>Safe in the browser</Badge>],+ ['Secret key (legacy: service_role)', <Code>sb_secret_...</Code>, <Code>SUPABASE_SERVICE_KEY</Code>, <Badge tone="secret">Server only</Badge>],+ ]}+ />+ <Callout type="danger" title="Never put the secret key in the frontend">+ <p>The secret key can read and change every row in the database. It belongs only in the Worker's secrets and, if you use the backup scheduler, in GitHub Actions secrets.</p>+ </Callout>+ </Step>+ </Steps>++ <H2>Already have the tables?</H2>+ <P>If you created the tables from an older README, make sure <Code>tracked_posts</Code> exists and has the <Code>content_type</Code> column, and that row level security is on. This is safe to run more than once:</P>+ <CodeBlock title="upgrade.sql">{`+alter table tracked_posts add column if not exists content_type text not null default 'reddit';+${RLS_SQL.trim()}+`}</CodeBlock>++ <H3>Why row level security with no policies</H3>+ <P>The backend uses the secret key, which bypasses row level security, and limits every query to the signed-in user itself. Turning security on with no policies means the public publishable key, which ships in the frontend, cannot read or change any table directly. Without it, anyone holding that public key could read other members' data.</P>+ </>+ );+}++export function YouTube() {+ return (+ <>+ <DocTitle title="YouTube API key" lead="One shared key lets every member add any public channel." />+ <Steps>+ <Step title="Create a Google Cloud project">+ <P>Open <A href="https://console.cloud.google.com/projectcreate">Google Cloud Console</A> and create a project, for example <Code>twiligent</Code>.</P>+ </Step>+ <Step title="Enable the YouTube Data API">+ <P>Open <A href="https://console.cloud.google.com/apis/library/youtube.googleapis.com">YouTube Data API v3</A> in the API Library, make sure your new project is selected, and choose <strong>Enable</strong>.</P>+ </Step>+ <Step title="Create the key">+ <P>Open <strong>APIs and Services</strong>, then <A href="https://console.cloud.google.com/apis/credentials">Credentials</A>. Choose <strong>Create credentials</strong>, then <strong>API key</strong>. Copy the key; it starts with <Code>AIza</Code>. This is <Code>YOUTUBE_API_KEY</Code>.</P>+ </Step>+ <Step title="Restrict the key">+ <P>Edit the key. Under <strong>API restrictions</strong> choose <strong>Restrict key</strong> and select only YouTube Data API v3. Leave <strong>Application restrictions</strong> at None, because the key is used by the Worker, not a browser.</P>+ </Step>+ </Steps>+ <Callout type="tip" title="Quota">+ <p>The free quota is 10,000 units a day, shared by all members. Most reads cost 1 unit. Adding <A to="/docs/self-host/redis">Upstash Redis</A> caches results and makes the quota go much further.</p>+ </Callout>+ </>+ );+}++export function Instagram() {+ return (+ <>+ <DocTitle title="Instagram app" lead="A Meta app lets members sign in with Instagram so Twiligent can read insights and publish." />++ <Callout type="note" title="Before you start">+ <p>You need a Meta developer account (free, at <A href="https://developers.facebook.com">developers.facebook.com</A>) and an Instagram Business or Creator account to test with. You need your backend URL for the redirect; if you have not deployed yet, use <Code>http://localhost:8787</Code> now and add the real one later.</p>+ </Callout>++ <Steps>+ <Step title="Create the app">+ <P>In <A href="https://developers.facebook.com/apps">My Apps</A> choose <strong>Create app</strong>. When asked for a use case, pick <strong>Other</strong>, then app type <strong>Business</strong>. Give it a name your members will recognise; Instagram shows it on the sign-in screen.</P>+ </Step>+ <Step title="Add Instagram">+ <P>On the app dashboard, add the <strong>Instagram</strong> product and choose <strong>API setup with Instagram business login</strong>. Do not use the Facebook login variant.</P>+ </Step>+ <Step title="Copy the Instagram app ID and secret">+ <P>On the Instagram API setup page, copy the <strong>Instagram app ID</strong> and <strong>Instagram app secret</strong>. These are <Code>INSTAGRAM_APP_ID</Code> and <Code>INSTAGRAM_APP_SECRET</Code>.</P>+ <Callout type="warning" title="Use the Instagram values, not the Facebook ones">+ <p>The app dashboard also shows a Facebook App ID under Settings, Basic. That one does not work here and produces an "Invalid platform app" error.</p>+ </Callout>+ </Step>+ <Step title="Set the redirect URL">+ <P>In <strong>Set up Instagram business login</strong>, open <strong>Business login settings</strong> and add this OAuth redirect URI, replacing the address with your backend URL:</P>+ <CodeBlock title="Redirect URI">{'https://twiligent.your-subdomain.workers.dev/api/auth/instagram/callback'}</CodeBlock>+ <P>For local development, add <Code>http://localhost:8787/api/auth/instagram/callback</Code> as well. It must match <Code>BACKEND_URL</Code> exactly, with no trailing slash.</P>+ </Step>+ <Step title="Add testers">+ <P>While the app is in development mode, only Instagram accounts with a tester role can connect. Open <strong>App roles</strong>, then <strong>Roles</strong>, choose <strong>Add people</strong>, pick <strong>Instagram Tester</strong> and enter the Instagram username.</P>+ <P>The person then accepts the invite in Instagram under <A href="https://www.instagram.com/accounts/manage_access/">Apps and websites</A>, <strong>Tester invites</strong>. Members are told to email you for this; set your address with <Code>VITE_ADMIN_EMAIL</Code>.</P>+ </Step>+ </Steps>++ <H2>Permissions Twiligent asks for</H2>+ <Table+ head={['Permission', 'Why']}+ rows={[+ [<Code>instagram_business_basic</Code>, 'Read the profile, follower count and media list.'],+ [<Code>instagram_business_manage_insights</Code>, 'Read views, reach and other insights.'],+ [<Code>instagram_business_content_publish</Code>, 'Publish photos, Reels and Stories.'],+ [<Code>instagram_business_manage_comments</Code>, 'Read comment counts and comments.'],+ [<Code>instagram_business_manage_messages</Code>, 'Requested with the business login set; not used to send messages.'],+ ]}+ />++ <H2>Going live for everyone</H2>+ <P>To let any Instagram account connect without a tester role, submit the app for <strong>App Review</strong> with the permissions above, then switch it to <strong>Live</strong>. Meta asks for a privacy policy URL, a screencast of each permission in use, and business verification. For a private team, tester roles are usually simpler.</P>+ </>+ );+}++export function Cloudinary() {+ return (+ <>+ <DocTitle title="Cloudinary" lead="Instagram publishes from a public URL, so files are uploaded to Cloudinary first." />+ <Steps>+ <Step title="Create an account">+ <P>Sign up at <A href="https://cloudinary.com/users/register_free">cloudinary.com</A>. On the dashboard, copy the <strong>Cloud name</strong>. This is <Code>CLOUDINARY_CLOUD_NAME</Code>.</P>+ </Step>+ <Step title="Create an unsigned upload preset">+ <P>Open <strong>Settings</strong>, then <strong>Upload</strong>, then <strong>Upload presets</strong>, and choose <strong>Add upload preset</strong>. Set <strong>Signing mode</strong> to <strong>Unsigned</strong> and save. Copy the preset name. This is <Code>CLOUDINARY_UPLOAD_PRESET</Code>.</P>+ </Step>+ </Steps>+ <Callout type="note" title="Why unsigned">+ <p>Browsers upload large videos straight to Cloudinary so they never pass through the Worker. Unsigned presets allow this without exposing your Cloudinary API secret. Both values are only handed to signed-in members.</p>+ </Callout>+ <P>Without Cloudinary, everything works except publishing and uploading screenshots for tracked Reddit posts.</P>+ </>+ );+}++export function Redis() {+ return (+ <>+ <DocTitle title="Upstash Redis (optional)" lead="A cache that saves YouTube and Instagram quota and makes pages load faster." />+ <P>Twiligent works fully without Redis. Every cache read falls back to a live API call, and Redis errors are ignored. Add it when you have several members or many YouTube channels.</P>+ <Steps>+ <Step title="Create a database">+ <P>Sign in at <A href="https://console.upstash.com">console.upstash.com</A>, choose <strong>Create database</strong>, and pick the region closest to your Supabase project.</P>+ </Step>+ <Step title="Copy the REST values">+ <P>On the database page, in the <strong>REST API</strong> section, copy <strong>UPSTASH_REDIS_REST_URL</strong> and <strong>UPSTASH_REDIS_REST_TOKEN</strong>. They are used under exactly those names.</P>+ </Step>+ </Steps>+ </>+ );+}++export function DeployBackend() {+ return (+ <>+ <DocTitle title="Deploy the backend" lead="Put the Worker on Cloudflare and give it every secret." />+ <Steps>+ <Step title="Install and sign in">+ <CodeBlock>{`+cd backend+npm install+npx wrangler login+`}</CodeBlock>+ <P>A browser window opens to sign in to Cloudflare. Create a free account if you do not have one.</P>+ </Step>+ <Step title="Deploy once to get your URL">+ <CodeBlock>{'npx wrangler deploy'}</CodeBlock>+ <P>Wrangler prints the Worker address, for example <Code>https://twiligent.your-subdomain.workers.dev</Code>. This is your <strong>backend URL</strong>.</P>+ </Step>+ <Step title="Add the secrets">+ <P>Run each command and paste the value when asked. Values are encrypted by Cloudflare and never shown again.</P>+ <CodeBlock>{`+npx wrangler secret put SUPABASE_URL+npx wrangler secret put SUPABASE_SERVICE_KEY+npx wrangler secret put SUPABASE_ANON_KEY+npx wrangler secret put YOUTUBE_API_KEY+npx wrangler secret put INSTAGRAM_APP_ID+npx wrangler secret put INSTAGRAM_APP_SECRET+npx wrangler secret put CLOUDINARY_CLOUD_NAME+npx wrangler secret put CLOUDINARY_UPLOAD_PRESET+npx wrangler secret put BACKEND_URL+npx wrangler secret put FRONTEND_URL+`}</CodeBlock>+ <P>If you use Redis, also add <Code>UPSTASH_REDIS_REST_URL</Code> and <Code>UPSTASH_REDIS_REST_TOKEN</Code>. Skip any platform you do not use. <Code>FRONTEND_URL</Code> is the address of the site from the next page; you can set it after deploying the frontend.</P>+ </Step>+ <Step title="Check it is running">+ <P>Open <Code>https://your-backend-url/api/health</Code>. It should return <Code>{'{"status":"ok"}'}</Code> with a timestamp.</P>+ </Step>+ </Steps>++ <H2>Scheduled jobs</H2>+ <P>Deploying also registers two cron triggers from <Code>wrangler.toml</Code>. You do not need to set anything up.</P>+ <Table+ head={['Schedule', 'What it does']}+ rows={[+ [<Code>*/15 * * * *</Code>, 'Publishes scheduled Instagram posts that are due.'],+ [<Code>0 0 * * *</Code>, 'Renews Instagram access tokens before they expire.'],+ ]}+ />++ <H2>Run it locally</H2>+ <P>Create <Code>backend/.dev.vars</Code> with the same names and values, one per line as <Code>NAME=value</Code>, with <Code>BACKEND_URL=http://localhost:8787</Code> and <Code>FRONTEND_URL=http://localhost:5173</Code>. Then run <Code>npx wrangler dev</Code>. The file is ignored by Git; never commit it.</P>+ </>+ );+}++export function DeployFrontend() {+ return (+ <>+ <DocTitle title="Deploy the frontend" lead="Build the website and host it on Cloudflare Pages." />+ <Callout type="note" title="These values are public">+ <p>Anything starting with <Code>VITE_</Code> is built into the website and visible to every visitor. Only use the publishable Supabase key here, never the secret one.</p>+ </Callout>+ <Steps>+ <Step title="Create frontend/.env">+ <CodeBlock title="frontend/.env">{`+VITE_SUPABASE_URL=https://abcdefgh.supabase.co+VITE_SUPABASE_ANON_KEY=sb_publishable_...+VITE_API_URL=https://twiligent.your-subdomain.workers.dev/api+`}</CodeBlock>+ <P><Code>VITE_API_URL</Code> is your backend URL followed by <Code>/api</Code>. Leaving off <Code>/api</Code> is the most common setup mistake.</P>+ </Step>+ <Step title="Build and deploy">+ <CodeBlock>{`+cd frontend+npm install+npm run build+npx wrangler pages deploy dist --project-name=twiligent+`}</CodeBlock>+ <P>The first time, Wrangler creates the Pages project and prints the address, for example <Code>https://twiligent.pages.dev</Code>.</P>+ </Step>+ <Step title="Point the backend at it">+ <P>Set <Code>FRONTEND_URL</Code> on the Worker to that address, so Instagram sign-in returns members to the right place:</P>+ <CodeBlock>{`+cd ../backend+npx wrangler secret put FRONTEND_URL+`}</CodeBlock>+ </Step>+ </Steps>+ <P>Open the site, create your account and connect something. For a custom domain, add it under the Pages project's <strong>Custom domains</strong> tab and update <Code>FRONTEND_URL</Code> to match.</P>+ </>+ );+}++export function GitHub() {+ return (+ <>+ <DocTitle title="GitHub automation" lead="Deploy on every push, and keep a second scheduler running in case the Worker misses a run." />+ <P>Both parts are optional. Fork <A href="https://github.com/spacesdrive/twiligent">spacesdrive/twiligent</A> to your own GitHub account first. Add secrets in your fork under <strong>Settings</strong>, <strong>Secrets and variables</strong>, <strong>Actions</strong>, <strong>New repository secret</strong>.</P>++ <H2>Deploy on push</H2>+ <P>The workflows <Code>deploy-backend.yml</Code> and <Code>deploy-frontend.yml</Code> deploy whenever <Code>backend/</Code> or <Code>frontend/</Code> changes on <Code>main</Code>.</P>+ <Table+ head={['Secret', 'Where to get it']}+ rows={[+ [<Code>CLOUDFLARE_API_TOKEN</Code>, <>Cloudflare dashboard, <strong>My Profile</strong>, <strong>API Tokens</strong>, <strong>Create Token</strong>, template <strong>Edit Cloudflare Workers</strong>. Add the <strong>Cloudflare Pages: Edit</strong> permission.</>],+ [<Code>CLOUDFLARE_ACCOUNT_ID</Code>, 'Cloudflare dashboard, Workers and Pages overview, shown on the right as Account ID.'],+ [<Code>VITE_SUPABASE_URL</Code>, 'Same value as in frontend/.env.'],+ [<Code>VITE_SUPABASE_ANON_KEY</Code>, 'Same value as in frontend/.env.'],+ [<Code>VITE_API_URL</Code>, 'Same value as in frontend/.env, ending in /api.'],+ [<Code>VITE_ADMIN_EMAIL</Code>, 'Optional. Your contact address.'],+ ]}+ />+ <P>Worker secrets stay in Cloudflare; the backend workflow does not need them.</P>++ <H2>Backup scheduler</H2>+ <P>The Worker already publishes scheduled posts. <Code>publish-scheduled.yml</Code> runs the same job from GitHub every 15 minutes as a safety net. Each post is claimed before publishing, so it is never posted twice even when both run at once.</P>+ <Steps>+ <Step title="Add two secrets">+ <P><Code>SUPABASE_URL</Code> and <Code>SUPABASE_SERVICE_KEY</Code>, with the same values the Worker uses.</P>+ </Step>+ <Step title="Enable workflows">+ <P>Forks start with Actions turned off. Open the <strong>Actions</strong> tab and choose <strong>I understand my workflows, go ahead and enable them</strong>. Then open <strong>Instagram Scheduled Publisher</strong> and choose <strong>Enable workflow</strong>.</P>+ </Step>+ <Step title="Run it once">+ <P>Choose <strong>Run workflow</strong>. It worked if the run finishes with a green check and the log says <Code>No posts due for publishing</Code> or shows a Results line.</P>+ </Step>+ </Steps>+ <Callout type="tip" title="Private forks">+ <p>Public repositories get unlimited Actions minutes. A private fork gets 2,000 free minutes a month; change the schedule in the workflow to every 30 minutes to stay inside it.</p>+ </Callout>+ <P>The in-app version of these steps, with links filled in for your GitHub username, is in <strong>Settings</strong>, <strong>Scheduled publishing</strong>.</P>+ </>+ );+}++export function Checklist() {+ return (+ <>+ <DocTitle title="Launch checklist" lead="Confirm everything works before you invite anyone." />+ <Table+ head={['Check', 'How']}+ rows={[+ ['Backend is up', <><Code>/api/health</Code> on your backend URL returns status ok.</>],+ ['Sign-in works', 'Create an account on the site and sign in.'],+ ['Keys are detected', 'Settings, Server API keys shows YouTube, Instagram and Cloudinary as set.'],+ ['YouTube works', 'Add any public channel in Accounts.'],+ ['Instagram works', 'Connect your own tester account in Accounts.'],+ ['Publishing works', 'Schedule a post 5 minutes ahead. It shows Published within 20 minutes.'],+ ['Data is private', 'Row level security is on for all four tables (Supabase, Table Editor shows no "RLS disabled" warning).'],+ ['Signups match your plan', 'Turn off new signups in Supabase if the instance is private.'],+ ['Members can reach you', 'VITE_ADMIN_EMAIL is your address.'],+ ]}+ />+ <H2>Tell your members</H2>+ <P>Send them the site address and a link to <A to="/docs/use/getting-started">Using Twiligent</A>. They need nothing else. If they will connect Instagram, collect their usernames and add them as testers first.</P>+ </>+ );+}diff --git a/frontend/src/docs/pages/Use.jsx b/frontend/src/docs/pages/Use.jsxnew file mode 100644index 0000000..e67bb7b--- /dev/null+++ b/frontend/src/docs/pages/Use.jsx@@ -0,0 +1,207 @@+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>Create an account</strong>. Use your email and a password of at least 6 characters, then sign in.</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>+ </>+ );+}diff --git a/frontend/src/docs/routes.js b/frontend/src/docs/routes.jsnew file mode 100644index 0000000..db44e7a--- /dev/null+++ b/frontend/src/docs/routes.js@@ -0,0 +1,46 @@+import { createElement, lazy } from 'react';+import { Navigate } from 'react-router-dom';++// Each section is one chunk; the pages inside it are named exports.+const sections = {+ overview: () => import('./pages/Overview'),+ use: () => import('./pages/Use'),+ selfHost: () => import('./pages/SelfHost'),+ reference: () => import('./pages/Reference'),+};++function page(section, name) {+ return lazy(() => sections[section]().then(m => ({ default: m[name] })));+}++const PAGES = {+ '': page('overview', 'Introduction'),+ concepts: page('overview', 'Concepts'),+ 'use/getting-started': page('use', 'GettingStarted'),+ 'use/connect-accounts': page('use', 'ConnectAccounts'),+ 'use/analytics': page('use', 'Analytics'),+ 'use/publishing': page('use', 'Publishing'),+ 'use/tracked-content': page('use', 'TrackedContent'),+ 'use/troubleshooting': page('use', 'Troubleshooting'),+ 'self-host': page('selfHost', 'Overview'),+ 'self-host/supabase': page('selfHost', 'Supabase'),+ 'self-host/youtube': page('selfHost', 'YouTube'),+ 'self-host/instagram': page('selfHost', 'Instagram'),+ 'self-host/cloudinary': page('selfHost', 'Cloudinary'),+ 'self-host/redis': page('selfHost', 'Redis'),+ 'self-host/deploy-backend': page('selfHost', 'DeployBackend'),+ 'self-host/deploy-frontend': page('selfHost', 'DeployFrontend'),+ 'self-host/github': page('selfHost', 'GitHub'),+ 'self-host/checklist': page('selfHost', 'Checklist'),+ 'reference/environment': page('reference', 'Environment'),+ 'reference/scheduling': page('reference', 'Scheduling'),+ 'reference/security': page('reference', 'Security'),+ 'reference/faq': page('reference', 'FAQ'),+};++export const DOC_ROUTE_SLUGS = Object.keys(PAGES);++export const docsChildRoutes = [+ ...Object.entries(PAGES).map(([slug, Component]) => (slug ? { path: slug, Component } : { index: true, Component })),+ { path: '*', element: createElement(Navigate, { to: '/docs', replace: true }) },+];diff --git a/frontend/src/docs/slug.js b/frontend/src/docs/slug.jsnew file mode 100644index 0000000..641cbe5--- /dev/null+++ b/frontend/src/docs/slug.js@@ -0,0 +1,8 @@+export function slugify(text) {+ return String(text || '')+ .toLowerCase()+ .replace(/[^a-z0-9\s-]/g, '')+ .trim()+ .replace(/\s+/g, '-')+ .replace(/-+/g, '-');+}diff --git a/frontend/src/layout/Sidebar.jsx b/frontend/src/layout/Sidebar.jsxindex 01b0663..6bdfc1a 100644--- a/frontend/src/layout/Sidebar.jsx+++ b/frontend/src/layout/Sidebar.jsx@@ -1,7 +1,7 @@import React from 'react';import { Link, useLocation, useNavigate } from 'react-router-dom';import { useSmoothTheme } from '@/hooks/use-smooth-theme';-import { Search, Tag, Settings, LogOut, Sun, Moon, Monitor, ChevronsUpDown } from 'lucide-react';+import { Search, Tag, Settings, LogOut, Sun, Moon, Monitor, ChevronsUpDown, BookOpen } from 'lucide-react';import {Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupLabel, SidebarHeader,SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar,@@ -157,6 +157,7 @@ function UserMenu({ onSignOut }) {</DropdownMenuGroup><DropdownMenuSeparator /><DropdownMenuItem onClick={() => navigate('/settings')}><Settings />Settings</DropdownMenuItem>+ <DropdownMenuItem onClick={() => navigate('/docs')}><BookOpen />Documentation</DropdownMenuItem><DropdownMenuItem onClick={onSignOut}><LogOut />Sign out</DropdownMenuItem></DropdownMenuContent></DropdownMenu>diff --git a/frontend/src/pages/Login.jsx b/frontend/src/pages/Login.jsxindex 582695b..db6ac60 100644--- a/frontend/src/pages/Login.jsx+++ b/frontend/src/pages/Login.jsx@@ -1,5 +1,5 @@import { useState } from 'react';-import { useNavigate } from 'react-router-dom';+import { Link, useNavigate } from 'react-router-dom';import { toast } from 'sonner';import { useAuth } from '../context/AuthContext';import { Button } from '@/components/ui/button';@@ -97,6 +97,12 @@ export default function Login() {{isLogin ? 'Create an account' : 'Sign in'}</button></p>+ <p className="text-center text-small text-ink-faint">+ Need help getting started?{' '}+ <Link to="/docs" className="rounded-sm font-medium text-ink-muted underline-offset-4 hover:text-ink hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring">+ Read the docs+ </Link>+ </p></div></div></main>