@tangen/ext-seo 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/package.json +55 -4
  2. package/src/client.ts +48 -0
  3. package/src/components/SeoPanel.tsx +489 -0
  4. package/src/contract.ts +269 -0
  5. package/src/hooks.ts +74 -0
  6. package/src/index.ts +41 -0
  7. package/src/lib/alt-text.ts +59 -0
  8. package/src/lib/analytics.ts +236 -0
  9. package/src/lib/canonical.ts +87 -0
  10. package/src/lib/deployment-role.ts +18 -0
  11. package/src/lib/health-report.ts +93 -0
  12. package/src/lib/llms.ts +55 -0
  13. package/src/lib/metadata.ts +268 -0
  14. package/src/lib/not-found.ts +83 -0
  15. package/src/lib/object-url.ts +83 -0
  16. package/src/lib/optimize.ts +77 -0
  17. package/src/lib/redirects-csv.ts +84 -0
  18. package/src/lib/redirects.ts +178 -0
  19. package/src/lib/resolve.ts +157 -0
  20. package/src/lib/robots.ts +76 -0
  21. package/src/lib/schema-map.ts +66 -0
  22. package/src/lib/schemas.ts +114 -0
  23. package/src/lib/seo-analysis.ts +185 -0
  24. package/src/lib/seo-manager-nav.ts +72 -0
  25. package/src/lib/settings.ts +167 -0
  26. package/src/lib/sitemap-report.ts +38 -0
  27. package/src/lib/sitemap.ts +109 -0
  28. package/src/lib/structured-data.ts +93 -0
  29. package/src/lib/titles.ts +109 -0
  30. package/src/nextjs.ts +70 -0
  31. package/src/pages/AiGeoTab.tsx +78 -0
  32. package/src/pages/AnalyticsTab.tsx +192 -0
  33. package/src/pages/GeoTab.tsx +76 -0
  34. package/src/pages/NotFoundTab.tsx +120 -0
  35. package/src/pages/SchemasTab.tsx +134 -0
  36. package/src/pages/SeoManagerPage.tsx +329 -0
  37. package/src/pages/SettingsTab.tsx +298 -0
  38. package/src/pages/SitemapTab.tsx +51 -0
  39. package/src/pages/TitlesTab.tsx +326 -0
  40. package/src/pages/ToolsTab.tsx +142 -0
  41. package/src/pages/manager-pages.tsx +46 -0
  42. package/src/pages/redirects.tsx +411 -0
  43. package/src/server/analytics-read.ts +51 -0
  44. package/src/server/analytics-sync.ts +182 -0
  45. package/src/server/artifacts.ts +305 -0
  46. package/src/server/health.ts +97 -0
  47. package/src/server/not-found-store.ts +71 -0
  48. package/src/server/optimize.ts +75 -0
  49. package/src/server/redirect-store.ts +128 -0
  50. package/src/server/routes.ts +604 -0
  51. package/src/server/search-console.ts +148 -0
  52. package/src/server/sitemap-source.ts +153 -0
  53. package/src/server/titles.ts +88 -0
  54. package/src/server.ts +47 -0
  55. package/tangen.extension.ts +153 -0
  56. package/README.md +0 -3
@@ -0,0 +1,76 @@
1
+ /**
2
+ * File Name: GeoTab.tsx
3
+ * Purpose: SEO Manager S2: the GEO tab - how AI answer engines see the site.
4
+ * Owns the llms.txt switch (moved out of Settings) and previews the
5
+ * manifest through the member route; the per-page pieces (FAQ, the
6
+ * answer summary) live in the SEO panel of each object and are
7
+ * explained here.
8
+ *
9
+ * Author: Raghunath J
10
+ * License: MIT
11
+ */
12
+ import { useCallback, useEffect, useState } from 'react'
13
+ import { useParams } from 'react-router-dom'
14
+ import { adminFetch, useCan, toast, FormSection, Toggle, Input, Button, Callout, Skeleton, Text } from '@/kit'
15
+ import type { SeoSettings } from '../lib/settings'
16
+
17
+ interface Preview { enabled: boolean; path: string; manifest: string | null }
18
+
19
+ export function GeoPanel() {
20
+ const { workspaceId } = useParams<{ workspaceId: string }>()
21
+ const { hasCapability } = useCan()
22
+ const mayWrite = hasCapability('seo:write' as never)
23
+ const [settings, setSettings] = useState<SeoSettings | null>(null)
24
+ const [preview, setPreview] = useState<Preview | null>(null)
25
+ const [error, setError] = useState<string | null>(null)
26
+ const [saving, setSaving] = useState(false)
27
+
28
+ const load = useCallback(async () => {
29
+ setError(null)
30
+ try {
31
+ const [s, p] = await Promise.all([
32
+ adminFetch<{ data: SeoSettings }>('/admin/ext/seo/site-settings'),
33
+ adminFetch<{ data: Preview }>('/admin/ext/seo/llms-preview'),
34
+ ])
35
+ setSettings(s.data); setPreview(p.data)
36
+ } catch (e) { setError((e as Error).message || 'The GEO settings could not be loaded.') }
37
+ }, [])
38
+ useEffect(() => { void load() }, [load])
39
+
40
+ async function setEnabled(enabled: boolean) {
41
+ if (!settings) return
42
+ setSaving(true); setError(null)
43
+ try {
44
+ // The settings write is a full replace: everything else is sent back as loaded.
45
+ // Only the group this tab owns: the route merges by group now.
46
+ const res = await adminFetch<{ data: SeoSettings }>('/admin/ext/seo/site-settings', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ geo: { ...settings.geo, llmsTxtEnabled: enabled } }) })
47
+ setSettings(res.data)
48
+ setPreview((await adminFetch<{ data: Preview }>('/admin/ext/seo/llms-preview')).data)
49
+ toast.success(enabled ? 'llms.txt is published' : 'llms.txt is off')
50
+ } catch (e) { setError((e as Error).message || 'The change could not be saved.') }
51
+ finally { setSaving(false) }
52
+ }
53
+
54
+ const url = `${window.location.origin}/api/v1/ext/seo/llms.txt?workspace=${encodeURIComponent(workspaceId ?? '')}`
55
+ return (
56
+ <div className="max-w-2xl space-y-5">
57
+ {error && <Callout variant="danger">{error}</Callout>}
58
+ <FormSection title="llms.txt" description="A manifest of your published content for AI answer engines (llms.txt, and llms-full.txt with summaries). Served only while this is on.">
59
+ {!settings ? <Skeleton className="h-10 w-full" /> : (
60
+ <Toggle label="Publish llms.txt" description="Serve the manifest at the URL below." direction="switch-first" size="sm" checked={settings.geo.llmsTxtEnabled} disabled={!mayWrite || saving} onCheckedChange={(v: boolean) => { void setEnabled(v) }} />
61
+ )}
62
+ <div className="flex flex-wrap items-center gap-2">
63
+ <Input readOnly value={url} className="min-w-0 flex-1 font-mono text-[11px]" aria-label="llms.txt URL" />
64
+ <Button size="sm" variant="secondary" onClick={() => { navigator.clipboard?.writeText(url); toast.success('llms.txt URL copied') }}>Copy</Button>
65
+ <Button size="sm" variant="secondary" onClick={() => { void load() }} disabled={saving}>Refresh preview</Button>
66
+ </div>
67
+ {preview && (preview.enabled && preview.manifest
68
+ ? <pre className="max-h-80 overflow-auto rounded border border-border bg-surface-sunken p-3 text-[11px] leading-5 text-fg">{preview.manifest}</pre>
69
+ : <Text variant="help">The manifest is off. Turn it on to preview what engines would read.</Text>)}
70
+ </FormSection>
71
+ <FormSection title="Per page" description="What each page tells an answer engine is set in its SEO panel.">
72
+ <Text variant="help">The <strong>answer summary</strong> is the two or three sentences an engine may quote; <strong>FAQ</strong> pairs become FAQPage structured data. Both take an AI draft when the workspace has AI enabled, and both work without it.</Text>
73
+ </FormSection>
74
+ </div>
75
+ )
76
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * File Name: NotFoundTab.tsx
3
+ * Purpose: The 404 Monitor (plan-seo-manager-v2 V5): the paths visitors
4
+ * asked for that the site could not answer, busiest first, each
5
+ * with a Create redirect that opens the redirect form already
6
+ * filled in. Paths only - the page can show nothing about a
7
+ * visitor because nothing about one is stored.
8
+ *
9
+ * Author: Raghunath J
10
+ * License: MIT
11
+ */
12
+ import { useCallback, useEffect, useState } from 'react'
13
+ import { useNavigate, useParams } from 'react-router-dom'
14
+ import { AdminPage, Button, DataList, ListChip, Text, adminFetch, toast, useCan, useConfirm } from '@/kit'
15
+ import { IconWarning, IconHash, IconClock, IconLink } from '@tangen/icons'
16
+ import { MISS_CAP, type MissRow } from '../lib/not-found'
17
+ import { seoManagerHref, MANAGER_PAGE_SIZE } from '../lib/seo-manager-nav'
18
+
19
+ export function SeoNotFoundPage() {
20
+ const { workspaceId = '' } = useParams<{ workspaceId: string }>()
21
+ const navigate = useNavigate()
22
+ const { hasCapability } = useCan()
23
+ const { confirm, confirmDialog } = useConfirm()
24
+ const mayWrite = hasCapability('seo:write')
25
+
26
+ const [rows, setRows] = useState<MissRow[]>([])
27
+ const [meta, setMeta] = useState<{ total: number; tracked: number; cap: number }>({ total: 0, tracked: 0, cap: MISS_CAP })
28
+ const [loading, setLoading] = useState(true)
29
+ const [error, setError] = useState<string | null>(null)
30
+ const [search, setSearch] = useState('')
31
+ const [sort, setSort] = useState<{ field: string; direction: 'asc' | 'desc' } | undefined>(undefined)
32
+ const [page, setPage] = useState(1)
33
+
34
+ const load = useCallback(async () => {
35
+ setLoading(true); setError(null)
36
+ try {
37
+ const res = await adminFetch<{ data: MissRow[]; meta: { total: number; tracked: number; cap: number } }>('/admin/ext/seo/not-found', undefined, {
38
+ ...(sort ? { sort: sort.field, dir: sort.direction } : {}),
39
+ limit: String(MANAGER_PAGE_SIZE), offset: String((page - 1) * MANAGER_PAGE_SIZE),
40
+ })
41
+ setRows(res.data ?? [])
42
+ setMeta(res.meta ?? { total: 0, tracked: 0, cap: MISS_CAP })
43
+ } catch (e) {
44
+ setError((e as Error).message || 'The list of missing pages could not be loaded.')
45
+ } finally { setLoading(false) }
46
+ }, [sort, page])
47
+ useEffect(() => { load() }, [load])
48
+
49
+ const ignore = async (row: MissRow) => {
50
+ const ok = await confirm({
51
+ title: 'Ignore this path?',
52
+ message: `${row.path} leaves the list and stops being counted. Nothing on the site changes.`,
53
+ confirmLabel: 'Ignore',
54
+ })
55
+ if (!ok) return
56
+ try {
57
+ await adminFetch('/admin/ext/seo/not-found/ignore', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path: row.path }) })
58
+ await load()
59
+ } catch (e) { toast.error(e instanceof Error ? e.message : 'That path could not be ignored') }
60
+ }
61
+
62
+ const columns = [
63
+ { key: 'path', header: 'Path', icon: <IconLink />, sortKey: 'path', cell: (r: MissRow) => <span className="font-mono text-xs">{r.path}</span> },
64
+ { key: 'hits', header: 'Requests', icon: <IconHash />, sortKey: 'hits', align: 'right' as const, cell: (r: MissRow) => <span className="tabular-nums">{r.hits.toLocaleString()}</span> },
65
+ { key: 'firstSeenAt', header: 'First seen', icon: <IconClock />, sortKey: 'firstSeenAt', cell: (r: MissRow) => <span className="text-fg-subtle">{new Date(r.firstSeenAt).toLocaleDateString()}</span> },
66
+ { key: 'lastSeenAt', header: 'Last seen', icon: <IconClock />, sortKey: 'lastSeenAt', cell: (r: MissRow) => <span className="text-fg-subtle">{new Date(r.lastSeenAt).toLocaleString()}</span> },
67
+ {
68
+ key: 'actions', header: '', align: 'right' as const,
69
+ cell: (r: MissRow) => mayWrite ? (
70
+ <div className="flex justify-end gap-1.5">
71
+ <Button size="xs" variant="secondary" onClick={() => navigate(`${seoManagerHref(workspaceId, 'redirects')}?source=${encodeURIComponent(r.path)}`)}>Create redirect</Button>
72
+ <Button size="xs" variant="ghost" onClick={() => ignore(r)}>Ignore</Button>
73
+ </div>
74
+ ) : null,
75
+ },
76
+ ]
77
+
78
+ return (
79
+ <AdminPage
80
+ title="404 Monitor"
81
+ description="Addresses visitors asked for that your site could not answer."
82
+ access={{ capability: 'seo:read' }}
83
+ >
84
+ <div className="space-y-4">
85
+ <DataList<MissRow>
86
+ chrome="framed"
87
+ columns={columns}
88
+ rows={search.trim() ? rows.filter((r) => r.path.toLowerCase().includes(search.trim().toLowerCase())) : rows}
89
+ rowKey={(r) => r.path}
90
+ loading={loading}
91
+ error={error ? { message: error, onRetry: load } : undefined}
92
+ total={meta.total}
93
+ page={page}
94
+ pageSize={MANAGER_PAGE_SIZE}
95
+ onPageChange={setPage}
96
+ sortConfig={sort}
97
+ onSortChange={setSort}
98
+ search={search}
99
+ onSearchChange={setSearch}
100
+ searchPlaceholder="Search a path"
101
+ filtered={search.trim() !== ''}
102
+ toolbarLeft={<ListChip icon={<IconWarning />} label="Missing pages" count={meta.total} />}
103
+ filteredEmptyState={{
104
+ title: `No path matches "${search}"`,
105
+ description: 'Only the paths Tangen has recorded appear here.',
106
+ action: <Button size="sm" variant="secondary" onClick={() => setSearch('')}>Clear search</Button>,
107
+ }}
108
+ emptyState={{
109
+ title: 'No missing pages recorded',
110
+ description: 'A path appears here when your site asks Tangen for a redirect and there is none, or when it reports the miss itself.',
111
+ }}
112
+ />
113
+ <Text variant="help">
114
+ {`Paths only: the query string is dropped and nothing about the visitor is stored. ${meta.tracked.toLocaleString()} of ${meta.cap.toLocaleString()} tracked paths in use; at the limit the least requested path makes room. Ignoring a path keeps it out of the list for good.`}
115
+ </Text>
116
+ </div>
117
+ {confirmDialog}
118
+ </AdminPage>
119
+ )
120
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * File Name: SchemasTab.tsx
3
+ * Purpose: The SEO Manager's Schemas tab (plan-seo-next Phase 2). Maps each
4
+ * content type to a JSON-LD kind (Article, Product, ...) and its
5
+ * properties to content fields, over GET/POST /admin/ext/seo/schemas.
6
+ * The generated node then rides every published page's /meta. Built on
7
+ * the Lightfield kit (@/kit); the server codec normalizeSchemaMap is
8
+ * the source of truth.
9
+ *
10
+ * Author: Raghunath J
11
+ * License: MIT
12
+ *
13
+ * Dependencies/Notes: @/kit only, no raw form elements (kit-lint). No em dashes.
14
+ */
15
+ import { useCallback, useEffect, useState } from 'react'
16
+ import {
17
+ adminFetch, useCan, toast,
18
+ FormSection, FormRow, FormFooter,
19
+ Select, SelectItem, Button, Callout, Skeleton, Text,
20
+ } from '@/kit'
21
+ import { SCHEMA_KINDS, schemaPropsFor, type SchemaKind, type SchemaMap, type TypeSchemaConfig } from '../lib/schema-map'
22
+
23
+ const UNMAPPED = '__none__'
24
+ const KIND_NONE = 'none'
25
+
26
+ interface TypeInfo { name: string; label: string; fields: { name: string; label: string }[] }
27
+
28
+ export function SchemasPanel() {
29
+ const { hasCapability } = useCan()
30
+ const mayWrite = hasCapability('seo:write' as never)
31
+
32
+ const [loading, setLoading] = useState(true)
33
+ const [error, setError] = useState<string | null>(null)
34
+ const [saving, setSaving] = useState(false)
35
+ const [types, setTypes] = useState<TypeInfo[]>([])
36
+ const [map, setMap] = useState<SchemaMap>({})
37
+
38
+ const load = useCallback(async () => {
39
+ setLoading(true); setError(null)
40
+ try {
41
+ const res = await adminFetch<{ data: { map: SchemaMap; types: TypeInfo[] } }>('/admin/ext/seo/schemas')
42
+ setTypes(res.data.types ?? [])
43
+ setMap(res.data.map ?? {})
44
+ } catch (e) {
45
+ setError((e as Error).message || 'The schema settings could not be loaded.')
46
+ } finally { setLoading(false) }
47
+ }, [])
48
+
49
+ useEffect(() => { load() }, [load])
50
+
51
+ function setKind(type: string, kind: string) {
52
+ setMap((prev) => {
53
+ const next = { ...prev }
54
+ if (kind === KIND_NONE) delete next[type]
55
+ else next[type] = { kind: kind as SchemaKind, fieldMap: prev[type]?.fieldMap ?? {} }
56
+ return next
57
+ })
58
+ }
59
+
60
+ function setField(type: string, prop: string, field: string) {
61
+ setMap((prev) => {
62
+ const cfg = prev[type]
63
+ if (!cfg) return prev
64
+ const fieldMap = { ...cfg.fieldMap }
65
+ if (field === UNMAPPED) delete fieldMap[prop]
66
+ else fieldMap[prop] = field
67
+ return { ...prev, [type]: { ...cfg, fieldMap } }
68
+ })
69
+ }
70
+
71
+ async function save() {
72
+ setSaving(true); setError(null)
73
+ try {
74
+ const res = await adminFetch<{ data: SchemaMap }>('/admin/ext/seo/schemas', { method: 'POST', body: JSON.stringify(map) })
75
+ setMap(res.data)
76
+ toast.success('Schema mapping saved')
77
+ } catch (e) {
78
+ setError((e as Error).message || 'The schema mapping could not be saved.')
79
+ } finally { setSaving(false) }
80
+ }
81
+
82
+ if (loading) return <div className="space-y-4"><Skeleton className="h-40 w-full" /><Skeleton className="h-40 w-full" /></div>
83
+
84
+ const ro = !mayWrite
85
+
86
+ return (
87
+ <div className="max-w-2xl space-y-5">
88
+ {error && <Callout variant="danger">{error}</Callout>}
89
+ {ro && <Callout variant="info">You can view the schema mapping but not change it. Managing it needs the seo:write permission.</Callout>}
90
+ <Text variant="help">
91
+ Pick a schema.org type for each content type, then map its properties to your fields. The generated JSON-LD is added to every published page of that type; a page can still add its own structured data.
92
+ </Text>
93
+
94
+ {types.length === 0 && <Callout variant="info">No content types yet. Add a content type and it will appear here.</Callout>}
95
+
96
+ {types.map((t) => {
97
+ const cfg: TypeSchemaConfig | undefined = map[t.name]
98
+ const kind = cfg?.kind ?? KIND_NONE
99
+ const props = schemaPropsFor(kind)
100
+ return (
101
+ <FormSection key={t.name} title={t.label} description={`Content type: ${t.name}`}>
102
+ <FormRow label="Schema type" htmlFor={`seo-schema-kind-${t.name}`}>
103
+ {/* The trigger is a button: it needs its own name, since the row
104
+ label cannot give one (see @tangen/ui select.tsx). */}
105
+ <Select id={`seo-schema-kind-${t.name}`} aria-label={`Schema type for ${t.label}`} value={kind} onValueChange={(v) => setKind(t.name, v)} disabled={ro}>
106
+ <SelectItem value={KIND_NONE}>No schema</SelectItem>
107
+ {SCHEMA_KINDS.map((k) => <SelectItem key={k} value={k}>{k}</SelectItem>)}
108
+ </Select>
109
+ </FormRow>
110
+ {props.length > 0 && (
111
+ <div className="grid gap-3 sm:grid-cols-2">
112
+ {props.map((prop) => (
113
+ <FormRow key={prop} label={prop} htmlFor={`seo-schema-${t.name}-${prop}`}>
114
+ <Select id={`seo-schema-${t.name}-${prop}`} aria-label={`${prop} for ${t.label}`} value={cfg?.fieldMap[prop] ?? UNMAPPED} onValueChange={(v) => setField(t.name, prop, v)} disabled={ro}>
115
+ <SelectItem value={UNMAPPED}>Not mapped</SelectItem>
116
+ {t.fields.map((f) => <SelectItem key={f.name} value={f.name}>{f.label}</SelectItem>)}
117
+ </Select>
118
+ </FormRow>
119
+ ))}
120
+ </div>
121
+ )}
122
+ </FormSection>
123
+ )
124
+ })}
125
+
126
+ {!ro && types.length > 0 && (
127
+ <FormFooter>
128
+ <Button variant="secondary" size="sm" onClick={load} disabled={saving}>Reset</Button>
129
+ <Button size="sm" isLoading={saving} onClick={save}>Save schemas</Button>
130
+ </FormFooter>
131
+ )}
132
+ </div>
133
+ )
134
+ }
@@ -0,0 +1,329 @@
1
+ /**
2
+ * File Name: SeoManagerPage.tsx
3
+ * Purpose: The SEO Manager's Dashboard (plan-seo-manager-v2 V1): the health
4
+ * report over the workspace's own published content - a score, the
5
+ * coverage per type, the services around the site, and the objects
6
+ * that need attention - each number from `GET health-report`. No
7
+ * Search Console tiles until a connection exists: a card says how
8
+ * to connect instead. A v1 `?tab=` link is sent to its child page.
9
+ *
10
+ * Author: Raghunath J
11
+ * License: MIT
12
+ */
13
+ import { useCallback, useEffect, useState } from 'react'
14
+ import { Link, Navigate, useNavigate, useParams, useSearchParams } from 'react-router-dom'
15
+ import { AdminPage, Panel, Text, Button, DataList, ListChip, TEXT_LINK, adminFetch, toast, useCan, type DataListColumn } from '@/kit'
16
+ import { IconRefresh, IconTable, IconListChecks, IconChevronRight, IconFileList, IconProhibited, IconSparkles, IconBarChart } from '@tangen/icons'
17
+ import { legacyTabPath, seoManagerHref, DASHBOARD_PAGE_SIZE } from '../lib/seo-manager-nav'
18
+ import { scoreTone, type HealthReport } from '../lib/health-report'
19
+ import { Stat, type AnalyticsViewData } from './AnalyticsTab'
20
+
21
+ export function SeoManagerPage() {
22
+ const { workspaceId = '' } = useParams<{ workspaceId: string }>()
23
+ const [params] = useSearchParams()
24
+ const legacy = legacyTabPath(params.get('tab'))
25
+ if (legacy) return <Navigate to={seoManagerHref(workspaceId, legacy)} replace />
26
+ return <Dashboard workspaceId={workspaceId} />
27
+ }
28
+
29
+ function Dashboard({ workspaceId }: { workspaceId: string }) {
30
+ const navigate = useNavigate()
31
+ const [report, setReport] = useState<HealthReport | null>(null)
32
+ // V4: the search numbers ride along only when a connection actually reported some.
33
+ const [analytics, setAnalytics] = useState<AnalyticsViewData | null>(null)
34
+ const [loading, setLoading] = useState(true)
35
+ const [busy, setBusy] = useState(false)
36
+ const { hasCapability } = useCan()
37
+ const canWrite = hasCapability('seo:write')
38
+
39
+ const load = useCallback(async (rebuild: boolean) => {
40
+ try {
41
+ const r = await adminFetch<{ data: HealthReport }>('/admin/ext/seo/health-report', rebuild ? { method: 'POST' } : undefined)
42
+ setReport(r.data)
43
+ if (r.data.services.searchConsole.connected) {
44
+ const a = await adminFetch<{ data: AnalyticsViewData }>('/admin/ext/seo/analytics?days=28').catch(() => null)
45
+ setAnalytics(a?.data ?? null)
46
+ }
47
+ } catch (e) {
48
+ toast.error(e instanceof Error ? e.message : 'The health report could not be loaded')
49
+ }
50
+ }, [])
51
+ useEffect(() => { load(false).finally(() => setLoading(false)) }, [load])
52
+ const recheck = async () => { setBusy(true); try { await load(true) } finally { setBusy(false) } }
53
+
54
+ return (
55
+ <AdminPage
56
+ title="SEO Manager"
57
+ description="How the site's published content stands in search, from its own metadata."
58
+ access={{ capability: 'seo:read' }}
59
+ loading={loading}
60
+ actions={canWrite ? <Button size="sm" variant="secondary" icon={<IconRefresh className="size-3.5" />} disabled={busy} onClick={recheck}>{busy ? 'Checking' : 'Recheck'}</Button> : undefined}
61
+ >
62
+ {report && (
63
+ <div className="space-y-4">
64
+ {analytics?.summary && analytics.summary.days > 0 && (
65
+ <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
66
+ <Stat label="Clicks" summary={analytics.summary} metric="clicks" format={(n) => Math.round(n).toLocaleString()} />
67
+ <Stat label="Impressions" summary={analytics.summary} metric="impressions" format={(n) => Math.round(n).toLocaleString()} />
68
+ <Stat label="Average CTR" summary={analytics.summary} metric="ctr" format={(n) => `${(n * 100).toFixed(1)}%`} />
69
+ <Stat label="Average position" summary={analytics.summary} metric="position" format={(n) => n.toFixed(1)} />
70
+ </div>
71
+ )}
72
+ <div className="grid gap-4 lg:grid-cols-[284px_1fr]">
73
+ <HealthCard report={report} />
74
+ <div className="space-y-4">
75
+ <CoverageCard report={report} />
76
+ <ServicesCard report={report} workspaceId={workspaceId} />
77
+ </div>
78
+ </div>
79
+ <AttentionCard workspaceId={workspaceId} onOpen={(o) => navigate(`/${workspaceId}/objects/${o.type}/${o.id}`)} />
80
+ <Text variant="help">Generated {new Date(report.generatedAt).toLocaleString()} over {report.scanned.toLocaleString()} published objects. A publish refreshes it; Recheck rebuilds it now.</Text>
81
+ </div>
82
+ )}
83
+ </AdminPage>
84
+ )
85
+ }
86
+
87
+ const TONE_TEXT = { good: 'text-success-fg', ok: 'text-warning-fg', poor: 'text-danger-fg' } as const
88
+ const TONE_STROKE = { good: 'text-success', ok: 'text-warning', poor: 'text-danger' } as const
89
+ const TONE_LABEL = { good: 'Good', ok: 'Needs work', poor: 'Poor' } as const
90
+
91
+ /**
92
+ * A dashboard card. The chrome is the kit's, not its own: these sit beside
93
+ * framed DataLists on the same page, and a wider radius with a heavier shadow
94
+ * made them read as widgets pasted onto the page rather than part of it.
95
+ */
96
+ function Card({ title, sub, children, className = '' }: { title: string; sub?: string; children: React.ReactNode; className?: string }) {
97
+ return (
98
+ <Panel flush className={`p-5 ${className}`}>
99
+ <div className="flex items-baseline gap-2">
100
+ <h3 className="text-sm font-semibold text-fg">{title}</h3>
101
+ {sub && <span className="text-ui-xs text-fg-subtle">{sub}</span>}
102
+ </div>
103
+ {children}
104
+ </Panel>
105
+ )
106
+ }
107
+
108
+ /** The score ring: one SVG arc over a track, the same thresholds as the panel's badge. */
109
+ function HealthCard({ report }: { report: HealthReport }) {
110
+ const tone = scoreTone(report.score)
111
+ const r = 57, c = 2 * Math.PI * r
112
+ const offset = report.score === null ? c : c * (1 - report.score / 100)
113
+ return (
114
+ <Card title="Site health">
115
+ <div className="mt-2 flex flex-col items-center">
116
+ <div className="relative my-2 size-[138px]">
117
+ <svg width="138" height="138" viewBox="0 0 138 138" className="-rotate-90" aria-hidden="true">
118
+ <circle cx="69" cy="69" r={r} fill="none" stroke="currentColor" strokeWidth="12" className="text-surface-sunken" />
119
+ {tone && <circle cx="69" cy="69" r={r} fill="none" stroke="currentColor" strokeWidth="12" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={offset} className={TONE_STROKE[tone]} />}
120
+ </svg>
121
+ <div className="absolute inset-0 grid place-content-center text-center">
122
+ <span className="text-[34px] font-semibold tracking-tight text-fg tabular-nums">{report.score ?? '–'}</span>
123
+ <span className={`text-[10.5px] font-semibold uppercase tracking-wider ${tone ? TONE_TEXT[tone] : 'text-fg-faint'}`}>{tone ? TONE_LABEL[tone] : 'No content'}</span>
124
+ </div>
125
+ </div>
126
+ <div className="w-full space-y-2 text-ui-xs">
127
+ {(['good', 'ok', 'poor'] as const).map((k) => (
128
+ <div key={k} className="flex items-center gap-2 text-fg-muted">
129
+ <span className={`size-2 rounded-sm ${k === 'good' ? 'bg-success' : k === 'ok' ? 'bg-warning' : 'bg-danger'}`} />
130
+ {TONE_LABEL[k]}
131
+ <span className="ml-auto font-semibold text-fg tabular-nums">{report.counts[k].toLocaleString()}</span>
132
+ </div>
133
+ ))}
134
+ </div>
135
+ </div>
136
+ </Card>
137
+ )
138
+ }
139
+
140
+ /** One segmented bar per content type: optimised, missing a description, no metadata. */
141
+ function CoverageCard({ report }: { report: HealthReport }) {
142
+ const total = report.coverage.reduce((n, c) => n + c.total, 0)
143
+ return (
144
+ <Card title="Content coverage" sub={`${total.toLocaleString()} published objects across ${report.coverage.length} ${report.coverage.length === 1 ? 'type' : 'types'}`}>
145
+ {report.coverage.length === 0 ? (
146
+ <Text variant="help" className="mt-2">Nothing is published yet. Coverage appears with the first published object.</Text>
147
+ ) : (
148
+ <div className="mt-3 space-y-3">
149
+ {report.coverage.map((c) => (
150
+ <div key={c.type}>
151
+ <div className="flex items-center justify-between text-ui-xs">
152
+ <span className="font-medium text-fg">{c.type}</span>
153
+ <span className="text-fg-subtle tabular-nums">{c.total.toLocaleString()}</span>
154
+ </div>
155
+ <div className="mt-1.5 flex h-2.5 overflow-hidden rounded-full bg-surface-sunken">
156
+ <i style={{ width: `${(100 * c.optimised) / c.total}%` }} className="bg-success" />
157
+ <i style={{ width: `${(100 * c.missingDescription) / c.total}%` }} className="bg-warning" />
158
+ <i style={{ width: `${(100 * c.noMetadata) / c.total}%` }} className="bg-danger" />
159
+ </div>
160
+ </div>
161
+ ))}
162
+ <div className="flex flex-wrap gap-4 text-ui-xs text-fg-muted">
163
+ <span><b className="text-fg">{report.coverage.reduce((n, c) => n + c.optimised, 0).toLocaleString()}</b> with a description</span>
164
+ <span className="text-warning-fg"><b>{report.coverage.reduce((n, c) => n + c.missingDescription, 0).toLocaleString()}</b> missing a description</span>
165
+ <span className="text-danger-fg"><b>{report.coverage.reduce((n, c) => n + c.noMetadata, 0).toLocaleString()}</b> no metadata</span>
166
+ </div>
167
+ </div>
168
+ )}
169
+ </Card>
170
+ )
171
+ }
172
+
173
+ /** One service: what it is, how it stands, and the one thing to do about it. */
174
+ function ServiceRow({ icon, name, state, tone, detail, action }: {
175
+ icon: React.ReactNode
176
+ name: string
177
+ state: string
178
+ tone: 'on' | 'off' | 'warn'
179
+ detail?: string
180
+ action?: React.ReactNode
181
+ }) {
182
+ const dot = tone === 'on' ? 'bg-success' : tone === 'warn' ? 'bg-warning' : 'bg-fg-faint'
183
+ return (
184
+ <div className="flex items-start gap-3 py-3">
185
+ <span className="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-lg bg-surface-sunken text-fg-muted [&_svg]:size-4">{icon}</span>
186
+ <div className="min-w-0 flex-1">
187
+ <div className="flex items-center gap-2">
188
+ <p className="text-ui-sm font-medium text-fg">{name}</p>
189
+ <span className={`size-1.5 shrink-0 rounded-full ${dot}`} aria-hidden="true" />
190
+ <p className="truncate text-ui-xs text-fg-muted">{state}</p>
191
+ </div>
192
+ {detail && <p className="mt-0.5 text-ui-xs text-fg-subtle">{detail}</p>}
193
+ </div>
194
+ {action && <div className="shrink-0 pt-0.5 text-ui-xs">{action}</div>}
195
+ </div>
196
+ )
197
+ }
198
+
199
+ function ServicesCard({ report, workspaceId }: { report: HealthReport; workspaceId: string }) {
200
+ const s = report.services
201
+ return (
202
+ <Card title="Services" sub="What the site serves search engines">
203
+ <div className="mt-1 grid gap-x-8 sm:grid-cols-2 sm:[&>*:nth-child(n+3)]:border-t sm:[&>*:nth-child(n+3)]:border-border-subtle [&>*+*]:border-t [&>*+*]:border-border-subtle sm:[&>*:nth-child(2)]:border-t-0">
204
+ <ServiceRow
205
+ icon={<IconFileList />}
206
+ name="Sitemap"
207
+ state={`${s.sitemap.entries.toLocaleString()} ${s.sitemap.entries === 1 ? 'URL' : 'URLs'} in ${s.sitemap.pageCount} ${s.sitemap.pageCount === 1 ? 'file' : 'files'}`}
208
+ tone={s.sitemap.entries > 0 ? 'on' : 'warn'}
209
+ detail={s.sitemap.truncated ? 'Cut short at the size limit.' : s.sitemap.entries === 0 ? 'No page resolved a URL yet.' : undefined}
210
+ action={<Link className={TEXT_LINK} to={seoManagerHref(workspaceId, 'sitemap')}>Report</Link>}
211
+ />
212
+ <ServiceRow
213
+ icon={<IconProhibited />}
214
+ name="robots.txt"
215
+ state="Served"
216
+ tone="on"
217
+ action={<Link className={TEXT_LINK} to={seoManagerHref(workspaceId, 'tools')}>Preview</Link>}
218
+ />
219
+ <ServiceRow
220
+ icon={<IconSparkles />}
221
+ name="llms.txt"
222
+ state={s.llmsTxt.enabled ? 'On' : 'Off'}
223
+ tone={s.llmsTxt.enabled ? 'on' : 'off'}
224
+ detail={s.llmsTxt.enabled ? undefined : 'AI answer engines read it when it is on.'}
225
+ action={<Link className={TEXT_LINK} to={seoManagerHref(workspaceId, 'ai-geo')}>{s.llmsTxt.enabled ? 'Preview' : 'Turn on'}</Link>}
226
+ />
227
+ <ServiceRow
228
+ icon={<IconBarChart />}
229
+ name="Search Console"
230
+ state={s.searchConsole.connected ? 'Connected' : 'Not connected'}
231
+ tone={s.searchConsole.connected ? 'on' : 'off'}
232
+ detail={s.searchConsole.connected ? undefined : 'Clicks, impressions and positions appear once connected.'}
233
+ action={s.searchConsole.connected
234
+ ? <Link className={TEXT_LINK} to={seoManagerHref(workspaceId, 'analytics')}>Analytics</Link>
235
+ : <Link className={TEXT_LINK} to={`/${workspaceId}/settings/connections`}>Connect</Link>}
236
+ />
237
+ </div>
238
+ </Card>
239
+ )
240
+ }
241
+
242
+ interface AttentionRow {
243
+ id: string
244
+ type: string
245
+ objectTitle: string | null
246
+ state: 'good' | 'needs-work' | 'missing'
247
+ issues: string[]
248
+ }
249
+
250
+ /**
251
+ * The pages that need work, PAGED BY THE SERVER over the same list Titles &
252
+ * Meta shows (`state=attention`), so there is no shortlist and no cap: what
253
+ * the footer counts is every page that needs work.
254
+ */
255
+ function AttentionCard({ workspaceId, onOpen }: { workspaceId: string; onOpen: (row: AttentionRow) => void }) {
256
+ const navigate = useNavigate()
257
+ const pageSize = DASHBOARD_PAGE_SIZE
258
+ const [page, setPage] = useState(1)
259
+ const [rows, setRows] = useState<AttentionRow[]>([])
260
+ const [total, setTotal] = useState(0)
261
+ const [loading, setLoading] = useState(true)
262
+ const [error, setError] = useState<string | null>(null)
263
+
264
+ const load = useCallback(async () => {
265
+ setLoading(true); setError(null)
266
+ try {
267
+ const params = new URLSearchParams({ state: 'attention', sort: 'state', limit: String(pageSize), offset: String((page - 1) * pageSize) })
268
+ const res = await adminFetch<{ data: AttentionRow[]; meta: { total: number } }>(`/admin/ext/seo/titles?${params.toString()}`)
269
+ setRows(res.data ?? [])
270
+ setTotal(res.meta?.total ?? 0)
271
+ } catch (e) {
272
+ setError((e as Error).message || 'The list could not be loaded.')
273
+ } finally { setLoading(false) }
274
+ }, [page])
275
+ useEffect(() => { load() }, [load])
276
+
277
+ const columns: DataListColumn<AttentionRow>[] = [
278
+ {
279
+ key: 'title', header: 'Page', icon: <IconTable />,
280
+ cell: (o) => (
281
+ <div className="flex min-w-0 items-center gap-2.5">
282
+ <span className={`size-2 shrink-0 rounded-full ${o.state === 'missing' ? 'bg-danger' : 'bg-warning'}`} aria-hidden="true" />
283
+ <div className="min-w-0">
284
+ <p className="truncate font-medium text-fg">{o.objectTitle || o.id}</p>
285
+ <p className="truncate text-[11px] text-fg-subtle">{o.type}</p>
286
+ </div>
287
+ </div>
288
+ ),
289
+ },
290
+ {
291
+ key: 'issues', header: 'What to fix', icon: <IconListChecks />,
292
+ // The whole sentence, wrapped: the kit clips a cell at 30 characters by
293
+ // default, which cut "Aim for 50-60 characters" mid-word.
294
+ clipAt: false,
295
+ cell: (o) => <span className="block whitespace-normal text-fg-muted">{o.issues.join(' ')}</span>,
296
+ },
297
+ {
298
+ key: 'go', header: '', className: 'w-10 text-right',
299
+ // The row is the target; the arrow says so without spending a word on it.
300
+ cell: () => <IconChevronRight className="ml-auto size-4 text-fg-faint" aria-hidden="true" />,
301
+ },
302
+ ]
303
+
304
+ return (
305
+ <DataList<AttentionRow>
306
+ chrome="framed"
307
+ columns={columns}
308
+ rows={rows}
309
+ rowKey={(o) => `${o.type}:${o.id}`}
310
+ loading={loading}
311
+ onRowClick={onOpen}
312
+ page={page}
313
+ pageSize={pageSize}
314
+ total={total}
315
+ onPageChange={setPage}
316
+ error={error ? { message: error, onRetry: load } : undefined}
317
+ toolbarLeft={<ListChip icon={<IconListChecks />} label="Needs attention" count={total} />}
318
+ toolbarRight={(
319
+ <Button size="xs" variant="secondary" onClick={() => navigate(`${seoManagerHref(workspaceId, 'titles')}?state=attention`)}>
320
+ Edit all
321
+ </Button>
322
+ )}
323
+ emptyState={{
324
+ title: 'Nothing needs attention',
325
+ description: 'Every published page has a title and description in the ideal range.',
326
+ }}
327
+ />
328
+ )
329
+ }