Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
refactor(ts): type the in-app docs pages
spacesdrive8c5c77f2446a
diff --git a/frontend/src/docs/DocsHeader.tsx b/frontend/src/docs/DocsHeader.tsxindex b093409..68405d7 100644--- a/frontend/src/docs/DocsHeader.tsx+++ b/frontend/src/docs/DocsHeader.tsx@@ -5,8 +5,18 @@ import { Button } from '@/components/ui/button';import { Logo } from '@/components/brand/Logo';import { cn } from '@/lib/utils';import { DOC_TABS, firstPagePath } from './nav';+import type { DocTab } from './nav';-export default function DocsHeader({ tab, signedIn, isDark, onToggleTheme, onOpenMenu, onOpenSearch }) {+interface DocsHeaderProps {+ tab: DocTab;+ signedIn: boolean;+ isDark: boolean;+ onToggleTheme: () => void;+ onOpenMenu: () => void;+ onOpenSearch: () => void;+}++export default function DocsHeader({ tab, signedIn, isDark, onToggleTheme, onOpenMenu, onOpenSearch }: DocsHeaderProps) {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">diff --git a/frontend/src/docs/DocsLayout.tsx b/frontend/src/docs/DocsLayout.tsxindex e6c215b..c4a37fb 100644--- a/frontend/src/docs/DocsLayout.tsx+++ b/frontend/src/docs/DocsLayout.tsx@@ -14,10 +14,10 @@ import DocsToc from './DocsToc';import DocsMobileNav from './DocsMobileNav';import DocsSearch from './DocsSearch';-function useSearchShortcut(setSearchOpen) {+function useSearchShortcut(setSearchOpen: (open: boolean) => void) {useEffect(() => {- const onKey = e => {- const typing = /input|textarea|select/i.test(e.target.tagName) || e.target.isContentEditable;+ const onKey = (e: KeyboardEvent) => {+ const typing = /input|textarea|select/i.test((e.target as HTMLElement).tagName) || (e.target as HTMLElement).isContentEditable;if ((e.key === '/' && !typing) || ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k')) {e.preventDefault();setSearchOpen(true);@@ -35,7 +35,7 @@ export default function DocsLayout() {const [searchOpen, setSearchOpen] = useState(false);const [menuOpen, setMenuOpen] = useState(false);const [copied, setCopied] = useState(false);- const articleRef = useRef(null);+ const articleRef = useRef<HTMLElement | null>(null);const tab = tabForPath(location.pathname);const { prev, next } = neighbours(location.pathname);const { items: toc, active } = useTableOfContents(articleRef, location.pathname);diff --git a/frontend/src/docs/DocsMobileNav.tsx b/frontend/src/docs/DocsMobileNav.tsxindex b150545..2431467 100644--- a/frontend/src/docs/DocsMobileNav.tsx+++ b/frontend/src/docs/DocsMobileNav.tsx@@ -3,9 +3,16 @@ 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 type { DocTab } from './nav';import DocsSidebarNav from './DocsSidebarNav';-export default function DocsMobileNav({ tab, open, onOpenChange }) {+interface DocsMobileNavProps {+ tab: DocTab;+ open: boolean;+ onOpenChange: (open: boolean) => void;+}++export default function DocsMobileNav({ tab, open, onOpenChange }: DocsMobileNavProps) {const close = () => onOpenChange(false);return (<Sheet open={open} onOpenChange={onOpenChange}>diff --git a/frontend/src/docs/DocsPager.tsx b/frontend/src/docs/DocsPager.tsxindex 6a5ae72..ea3eb1b 100644--- a/frontend/src/docs/DocsPager.tsx+++ b/frontend/src/docs/DocsPager.tsx@@ -1,8 +1,14 @@import React from 'react';import { Link } from 'react-router-dom';import { ArrowLeft, ArrowRight } from 'lucide-react';+import type { DocPageEntry } from './nav';-export default function DocsPager({ prev, next }) {+interface DocsPagerProps {+ prev: DocPageEntry | null;+ next: DocPageEntry | null;+}++export default function DocsPager({ prev, next }: DocsPagerProps) {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 ? (diff --git a/frontend/src/docs/DocsSearch.tsx b/frontend/src/docs/DocsSearch.tsxindex 2954a76..12023d1 100644--- a/frontend/src/docs/DocsSearch.tsx+++ b/frontend/src/docs/DocsSearch.tsx@@ -6,12 +6,25 @@ import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, Commandimport { filterCommands, groupCommands } from '@/lib/commandSearch';import { ALL_DOC_PAGES } from './nav';-export default function DocsSearch({ open, onOpenChange }) {+interface DocSearchCommand {+ id: string;+ label: string;+ group: string;+ keywords: string[];+ path: string;+}++interface DocsSearchProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+}++export default function DocsSearch({ open, onOpenChange }: DocsSearchProps) {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 commands = useMemo<DocSearchCommand[]>(() => 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); };+ const close = (next: boolean) => { 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">@@ -23,7 +36,7 @@ export default function DocsSearch({ open, onOpenChange }) {<CommandEmpty>No pages match "{query}"</CommandEmpty>{grouped.map(({ group, items }) => (<CommandGroup key={group} heading={group}>- {items.map(item => (+ {items.map((item: DocSearchCommand) => (<CommandItem key={item.id} value={item.id} onSelect={() => { close(false); navigate(item.path); }}><FileText />{item.label}diff --git a/frontend/src/docs/DocsSidebarNav.tsx b/frontend/src/docs/DocsSidebarNav.tsxindex ebb74d2..d71030e 100644--- a/frontend/src/docs/DocsSidebarNav.tsx+++ b/frontend/src/docs/DocsSidebarNav.tsx@@ -1,8 +1,14 @@import React from 'react';import { NavLink } from 'react-router-dom';import { cn } from '@/lib/utils';+import type { DocTab } from './nav';-export default function DocsSidebarNav({ tab, onNavigate }) {+interface DocsSidebarNavProps {+ tab: DocTab;+ onNavigate?: () => void;+}++export default function DocsSidebarNav({ tab, onNavigate }: DocsSidebarNavProps) {return (<nav aria-label={`${tab.label} pages`} className="flex flex-col gap-6">{tab.groups.map((group, i) => (diff --git a/frontend/src/docs/DocsToc.tsx b/frontend/src/docs/DocsToc.tsxindex 7db10b9..0484336 100644--- a/frontend/src/docs/DocsToc.tsx+++ b/frontend/src/docs/DocsToc.tsx@@ -1,14 +1,20 @@import React from 'react';import { ArrowUp } from 'lucide-react';import { cn } from '@/lib/utils';+import type { TocItem } from './useTableOfContents';-function jumpTo(e, id) {+function jumpTo(e: React.MouseEvent<HTMLAnchorElement>, id: string) {e.preventDefault();document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' });history.replaceState(null, '', `#${id}`);}-export default function DocsToc({ items, active }) {+interface DocsTocProps {+ items: TocItem[];+ active: string | null;+}++export default function DocsToc({ items, active }: DocsTocProps) {if (items.length === 0) return null;return (<nav aria-label="On this page" className="flex flex-col gap-3">diff --git a/frontend/src/docs/components.tsx b/frontend/src/docs/components.tsxindex cff5e85..cc8f6fe 100644--- a/frontend/src/docs/components.tsx+++ b/frontend/src/docs/components.tsx@@ -1,19 +1,27 @@import React, { useState } from 'react';import { Link } from 'react-router-dom';import { Info, AlertTriangle, Lightbulb, ShieldAlert, Check, Copy, ArrowRight } from 'lucide-react';+import type { LucideIcon } 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) {+type ElementWithChildren = React.ReactElement<{ children?: React.ReactNode }>;++function textOf(node: React.ReactNode): string {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);+ if ((node as ElementWithChildren | null | undefined)?.props?.children) return textOf((node as ElementWithChildren).props.children);return '';}-export function DocTitle({ title, lead }) {+export interface DocTitleProps {+ title: React.ReactNode;+ lead?: React.ReactNode;+}++export function DocTitle({ title, lead }: DocTitleProps) {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>@@ -22,7 +30,12 @@ export function DocTitle({ title, lead }) {);}-export function H2({ children, id }) {+export interface HeadingProps {+ children: React.ReactNode;+ id?: string;+}++export function H2({ children, id }: HeadingProps) {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}@@ -30,7 +43,7 @@ export function H2({ children, id }) {);}-export function H3({ children, id }) {+export function H3({ children, id }: HeadingProps) {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}@@ -38,36 +51,66 @@ export function H3({ children, id }) {);}-export function P({ children, className }) {+export interface PProps {+ children: React.ReactNode;+ className?: string;+}++export function P({ children, className }: PProps) {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 }) {+export interface ChildrenProps {+ children: React.ReactNode;+}++export function UL({ children }: ChildrenProps) {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 }) {+export function OL({ children }: ChildrenProps) {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 }) {+export function Code({ children }: ChildrenProps) {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 }) {+export interface AProps {+ to?: string;+ href?: string;+ children: React.ReactNode;+}++export function A({ to, href, children }: AProps) {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 = {+export type CalloutType = 'note' | 'tip' | 'warning' | 'danger';++interface CalloutStyle {+ icon: LucideIcon;+ cls: string;+ iconCls: string;+ label: string;+}++const CALLOUTS: Record<CalloutType, CalloutStyle> = {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 }) {+export interface CalloutProps {+ type?: CalloutType;+ title: React.ReactNode;+ children?: React.ReactNode;+}++export function Callout({ type = 'note', title, children }: CalloutProps) {const callout = CALLOUTS[type];const Icon = callout.icon;return (@@ -81,7 +124,12 @@ export function Callout({ type = 'note', title, children }) {);}-export function CodeBlock({ children, title }) {+export interface CodeBlockProps {+ children: string;+ title?: string;+}++export function CodeBlock({ children, title }: CodeBlockProps) {const [copied, setCopied] = useState(false);const text = String(children).replace(/^\n/, '').replace(/\n\s*$/, '');return (@@ -102,11 +150,16 @@ export function CodeBlock({ children, title }) {);}-export function Steps({ children }) {+export function Steps({ children }: ChildrenProps) {return <ol className="my-6 flex flex-col [counter-reset:step]">{children}</ol>;}-export function Step({ title, children }) {+export interface StepProps {+ title: string;+ children: React.ReactNode;+}++export function Step({ title, children }: StepProps) {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" />@@ -118,7 +171,12 @@ export function Step({ title, children }) {);}-export function Table({ head, rows }) {+export interface TableProps {+ head: string[];+ rows: React.ReactNode[][];+}++export function Table({ head, rows }: TableProps) {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">@@ -138,7 +196,7 @@ export function Table({ head, rows }) {}// Image-topped path cards. The art is the brand fold band with a ribbon crop, tinted per card.-export function PathCards({ children }) {+export function PathCards({ children }: ChildrenProps) {return <div className="my-8 grid grid-cols-1 gap-4 md:grid-cols-3">{children}</div>;}@@ -148,7 +206,14 @@ const CARD_ART = ['linear-gradient(120deg, #E8A33D 0%, #C11F2F 65%, #5E0B14 100%)',];-export function PathCard({ to, title, children, art = 0 }) {+export interface PathCardProps {+ to: string;+ title: React.ReactNode;+ children: React.ReactNode;+ art?: number;+}++export function PathCard({ to, title, children, art = 0 }: PathCardProps) {return (<Linkto={to}@@ -168,8 +233,15 @@ export function PathCard({ to, title, children, art = 0 }) {);}-export function Badge({ children, tone = 'neutral' }) {- const tones = {+export type BadgeTone = 'neutral' | 'required' | 'optional' | 'secret';++export interface BadgeProps {+ children: React.ReactNode;+ tone?: BadgeTone;+}++export function Badge({ children, tone = 'neutral' }: BadgeProps) {+ const tones: Record<BadgeTone, string> = {neutral: 'bg-surface-sunken text-ink-muted',required: 'bg-brand-soft text-brand-text',optional: 'bg-info-soft text-info',diff --git a/frontend/src/docs/nav.ts b/frontend/src/docs/nav.tsindex 38c2d88..6d52610 100644--- a/frontend/src/docs/nav.ts+++ b/frontend/src/docs/nav.ts@@ -1,6 +1,34 @@// tabs, sidebar groups and pages; routes.js maps each page to its component-export const DOC_TABS = [+export interface DocPage {+ slug: string;+ title: string;+ keywords: string[];+}++export interface DocGroup {+ label: string | null;+ pages: DocPage[];+}++export interface DocTab {+ id: string;+ label: string;+ groups: DocGroup[];+}++export interface DocPageEntry extends DocPage {+ tabId: string;+ tabLabel: string;+ path: string;+}++export interface DocNeighbours {+ prev: DocPageEntry | null;+ next: DocPageEntry | null;+}++export const DOC_TABS: DocTab[] = [{id: 'overview',label: 'Overview',@@ -90,24 +118,24 @@ export const DOC_TABS = [},];-export const ALL_DOC_PAGES = DOC_TABS.flatMap(tab => tab.groups.flatMap(group => group.pages.map(page => ({+export const ALL_DOC_PAGES: DocPageEntry[] = 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) {+export function tabForPath(pathname: string): DocTab {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) {+export function neighbours(pathname: string): DocNeighbours {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) {+export function firstPagePath(tab: DocTab): string {const page = tab.groups[0].pages[0];return page.slug ? `/docs/${page.slug}` : '/docs';}diff --git a/frontend/src/docs/pages/reference/Environment.tsx b/frontend/src/docs/pages/reference/Environment.tsxindex d5858f6..b89141e 100644--- a/frontend/src/docs/pages/reference/Environment.tsx+++ b/frontend/src/docs/pages/reference/Environment.tsx@@ -1,7 +1,9 @@import React from 'react';import { DocTitle, H2, P, UL, A, Code, Callout, Table, Badge } from '../../components';-const BACKEND_VARS = [+type Need = keyof typeof NEED;++const BACKEND_VARS: [string, Need, boolean, string, string][] = [['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.'],@@ -16,7 +18,7 @@ const BACKEND_VARS = [['UPSTASH_REDIS_REST_TOKEN', 'optional', true, 'Upstash database, REST API', 'Cache password.'],];-const FRONTEND_VARS = [+const FRONTEND_VARS: [string, Need, string][] = [['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.'],diff --git a/frontend/src/docs/pages/use/AdminLink.tsx b/frontend/src/docs/pages/use/AdminLink.tsxindex 06e9bc1..fdd4340 100644--- a/frontend/src/docs/pages/use/AdminLink.tsx+++ b/frontend/src/docs/pages/use/AdminLink.tsx@@ -2,6 +2,10 @@ import React from 'react';import { ADMIN_EMAIL, adminMailto } from '@/lib/contact';import { A } from '../../components';-export default function AdminLink({ subject }) {+interface AdminLinkProps {+ subject: string;+}++export default function AdminLink({ subject }: AdminLinkProps) {return <A href={adminMailto(subject)}>{ADMIN_EMAIL}</A>;}diff --git a/frontend/src/docs/routes.ts b/frontend/src/docs/routes.tsindex d933a55..a8057d5 100644--- a/frontend/src/docs/routes.ts+++ b/frontend/src/docs/routes.ts@@ -1,5 +1,7 @@import { createElement, lazy } from 'react';+import type { ComponentType, LazyExoticComponent } from 'react';import { Navigate } from 'react-router-dom';+import type { RouteObject } from 'react-router-dom';// Each section is one chunk; the pages inside it are named exports.const sections = {@@ -9,11 +11,16 @@ const sections = {reference: () => import('./pages/Reference'),};-function page(section, name) {- return lazy(() => sections[section]().then(m => ({ default: m[name] })));+type Sections = typeof sections;+type SectionName = keyof Sections;+type PageName<S extends SectionName> = keyof Awaited<ReturnType<Sections[S]>>;+export type DocPageComponent = LazyExoticComponent<ComponentType>;++function page<S extends SectionName>(section: S, name: PageName<S>): DocPageComponent {+ return lazy(() => sections[section]().then(m => ({ default: (m as unknown as Record<PageName<S>, ComponentType>)[name] })));}-const PAGES = {+const PAGES: Record<string, DocPageComponent> = {'': page('overview', 'Introduction'),concepts: page('overview', 'Concepts'),'use/getting-started': page('use', 'GettingStarted'),@@ -39,9 +46,9 @@ const PAGES = {'reference/faq': page('reference', 'FAQ'),};-export const DOC_ROUTE_SLUGS = Object.keys(PAGES);+export const DOC_ROUTE_SLUGS: string[] = Object.keys(PAGES);-export const docsChildRoutes = [+export const docsChildRoutes: RouteObject[] = [...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.ts b/frontend/src/docs/slug.tsindex 641cbe5..f979915 100644--- a/frontend/src/docs/slug.ts+++ b/frontend/src/docs/slug.ts@@ -1,4 +1,4 @@-export function slugify(text) {+export function slugify(text: string | null | undefined): string {return String(text || '').toLowerCase().replace(/[^a-z0-9\s-]/g, '')diff --git a/frontend/src/docs/useTableOfContents.ts b/frontend/src/docs/useTableOfContents.tsindex 7617800..c97843e 100644--- a/frontend/src/docs/useTableOfContents.ts+++ b/frontend/src/docs/useTableOfContents.ts@@ -1,14 +1,26 @@import { useEffect, useState } from 'react';+import type { RefObject } from 'react';-export function useTableOfContents(articleRef, pathname) {- const [items, setItems] = useState([]);- const [active, setActive] = useState(null);+export interface TocItem {+ id: string;+ text: string | null;+ level: number;+}++export interface TableOfContents {+ items: TocItem[];+ active: string | null;+}++export function useTableOfContents(articleRef: RefObject<HTMLElement | null>, pathname: string): TableOfContents {+ const [items, setItems] = useState<TocItem[]>([]);+ const [active, setActive] = useState<string | null>(null);useEffect(() => {const article = articleRef.current;if (!article) return undefined;const collect = () => {- const headings = [...article.querySelectorAll('[data-toc]')];+ const headings = [...article.querySelectorAll<HTMLElement>('[data-toc]')];setItems(headings.map(heading => ({ id: heading.id, text: heading.textContent, level: Number(heading.dataset.toc) })));return headings;};