sanity-plugin-seo-copilot 0.1.2 → 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.
- package/dist/index.js +4729 -895
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4722 -888
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/components/ChatPanel.tsx +87 -69
- package/src/components/FeedbackButton.tsx +2 -2
- package/src/components/KeywordBadge.tsx +50 -50
- package/src/components/KeywordPanel.tsx +97 -226
- package/src/components/PlacementIndicators.tsx +80 -76
- package/src/components/SEOCopilotPanel.tsx +712 -165
- package/src/components/ScoreDonut.tsx +158 -0
- package/src/components/SeedKeywordInput.tsx +128 -125
- package/src/components/ShimmerLoader.tsx +119 -0
- package/src/components/TabBar.tsx +370 -0
- package/src/components/styles.ts +66 -0
- package/src/components/tabs/AEOTab.tsx +573 -0
- package/src/components/tabs/LinkingTab.tsx +343 -0
- package/src/components/tabs/MetaTab.tsx +417 -0
- package/src/components/tabs/SummaryTab.tsx +384 -0
- package/src/components/tabs/TechnicalTab.tsx +776 -0
- package/src/hooks/useDocumentContent.ts +216 -99
- package/src/hooks/useKeywordAnalysis.ts +28 -8
- package/src/hooks/useSEOChat.ts +38 -11
- package/src/lib/api.ts +109 -13
- package/src/lib/geoAnalysis.ts +109 -0
- package/src/lib/persistence.ts +69 -0
- package/src/lib/scoring.ts +147 -0
- package/src/lib/summary.ts +504 -0
- package/src/lib/types.ts +197 -108
|
@@ -1,99 +1,216 @@
|
|
|
1
|
-
import { useState, useEffect, useRef } from "react";
|
|
2
|
-
import { useDocumentPane } from "sanity/structure";
|
|
3
|
-
import type { DocumentFields } from "../lib/types";
|
|
4
|
-
|
|
5
|
-
interface PortableTextSpan {
|
|
6
|
-
_type: string;
|
|
7
|
-
text?: string;
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
1
|
+
import { useState, useEffect, useRef } from "react";
|
|
2
|
+
import { useDocumentPane } from "sanity/structure";
|
|
3
|
+
import type { DocumentFields, HeadingItem } from "../lib/types";
|
|
4
|
+
|
|
5
|
+
interface PortableTextSpan {
|
|
6
|
+
_type: string;
|
|
7
|
+
text?: string;
|
|
8
|
+
marks?: string[];
|
|
9
|
+
children?: PortableTextSpan[];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface PortableTextMarkDef {
|
|
13
|
+
_key: string;
|
|
14
|
+
_type: string;
|
|
15
|
+
href?: string;
|
|
16
|
+
url?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface PortableTextBlock {
|
|
20
|
+
_type: string;
|
|
21
|
+
style?: string;
|
|
22
|
+
children?: PortableTextSpan[];
|
|
23
|
+
markDefs?: PortableTextMarkDef[];
|
|
24
|
+
text?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function extractText(blocks: unknown): string {
|
|
28
|
+
if (!blocks || !Array.isArray(blocks)) return "";
|
|
29
|
+
const parts: string[] = [];
|
|
30
|
+
for (const block of blocks as PortableTextBlock[]) {
|
|
31
|
+
if (block._type === "block" && block.children) {
|
|
32
|
+
const blockText = block.children.map((child) => child.text || "").join("");
|
|
33
|
+
if (blockText) parts.push(blockText);
|
|
34
|
+
} else if (typeof block === "string") {
|
|
35
|
+
parts.push(block);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return parts.join("\n");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function extractHeadings(blocks: unknown): string[] {
|
|
42
|
+
if (!blocks || !Array.isArray(blocks)) return [];
|
|
43
|
+
const headings: string[] = [];
|
|
44
|
+
for (const block of blocks as PortableTextBlock[]) {
|
|
45
|
+
if (block._type === "block" && block.style && /^h[1-6]$/.test(block.style) && block.children) {
|
|
46
|
+
const text = block.children.map((child) => child.text || "").join("");
|
|
47
|
+
if (text) headings.push(text);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return headings;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Headings with their numeric level (1-6), so the Technical tab can audit hierarchy.
|
|
54
|
+
function extractHeadingsDetailed(blocks: unknown): HeadingItem[] {
|
|
55
|
+
if (!blocks || !Array.isArray(blocks)) return [];
|
|
56
|
+
const out: HeadingItem[] = [];
|
|
57
|
+
for (const block of blocks as PortableTextBlock[]) {
|
|
58
|
+
if (block._type === "block" && block.style && /^h[1-6]$/.test(block.style) && block.children) {
|
|
59
|
+
const text = block.children.map((child) => child.text || "").join("").trim();
|
|
60
|
+
const level = Number(block.style.slice(1));
|
|
61
|
+
// Include empty headings too - the Technical tab flags them.
|
|
62
|
+
out.push({ text, level });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Every URL the editor has linked from this article body. Sanity stores them
|
|
69
|
+
// in Portable Text markDefs (with _type: "link" and href/url). We also catch
|
|
70
|
+
// inline plain-text URLs as a fallback.
|
|
71
|
+
function extractBodyLinks(blocks: unknown): string[] {
|
|
72
|
+
const urls = new Set<string>();
|
|
73
|
+
if (Array.isArray(blocks)) {
|
|
74
|
+
for (const block of blocks as PortableTextBlock[]) {
|
|
75
|
+
if (block._type === "block" && Array.isArray(block.markDefs)) {
|
|
76
|
+
for (const md of block.markDefs) {
|
|
77
|
+
const href = md.href || md.url;
|
|
78
|
+
if (typeof href === "string" && /^https?:\/\//i.test(href)) {
|
|
79
|
+
urls.add(href.trim());
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// Inline URLs that aren't in a link annotation - rare but possible.
|
|
86
|
+
if (Array.isArray(blocks)) {
|
|
87
|
+
for (const block of blocks as PortableTextBlock[]) {
|
|
88
|
+
if (block._type === "block" && Array.isArray(block.children)) {
|
|
89
|
+
const blockText = block.children.map((c) => c.text || "").join(" ");
|
|
90
|
+
const matches = blockText.match(/https?:\/\/[^\s"'<>)\]]+/g);
|
|
91
|
+
if (matches) matches.forEach((u) => urls.add(u.replace(/[.,;:!?]+$/, "")));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return Array.from(urls);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Extracts image metadata from the known top-level image fields:
|
|
99
|
+
// - names: alt text + asset filename (for the alt + filename audits)
|
|
100
|
+
// - titles: the `title` field on the image object or asset (the hover tooltip)
|
|
101
|
+
// - count: number of real images found (so the title audit can say "X of N")
|
|
102
|
+
function extractImageMeta(value: Record<string, unknown>): { names: string[]; titles: string[]; count: number } {
|
|
103
|
+
const names: string[] = [];
|
|
104
|
+
const titles: string[] = [];
|
|
105
|
+
let count = 0;
|
|
106
|
+
const imageFields = ["mainImage", "image", "heroImage", "thumbnail", "featuredImage"];
|
|
107
|
+
for (const field of imageFields) {
|
|
108
|
+
const img = value[field] as Record<string, unknown> | undefined;
|
|
109
|
+
if (!img || typeof img !== "object") continue;
|
|
110
|
+
const asset = img.asset && typeof img.asset === "object" ? (img.asset as Record<string, unknown>) : undefined;
|
|
111
|
+
// Only count entries that are actually images (have an asset or an image _type).
|
|
112
|
+
if (!asset && img._type !== "image") continue;
|
|
113
|
+
count++;
|
|
114
|
+
if (typeof img.alt === "string" && img.alt) names.push(img.alt);
|
|
115
|
+
if (asset && typeof asset.originalFilename === "string" && asset.originalFilename) names.push(asset.originalFilename);
|
|
116
|
+
// The hover-tooltip title can live on the image object or on the asset.
|
|
117
|
+
if (typeof img.title === "string" && img.title) titles.push(img.title);
|
|
118
|
+
else if (asset && typeof asset.title === "string" && asset.title) titles.push(asset.title);
|
|
119
|
+
}
|
|
120
|
+
return { names, titles, count };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function useDocumentContent(): { text: string; isLoading: boolean; documentFields: DocumentFields; documentId: string | undefined } {
|
|
124
|
+
const { value, ready } = useDocumentPane();
|
|
125
|
+
const documentId = (value?._id as string | undefined) || undefined;
|
|
126
|
+
const title = value?.title as string | undefined;
|
|
127
|
+
const body = value?.body;
|
|
128
|
+
const [debouncedText, setDebouncedText] = useState("");
|
|
129
|
+
const [isLoading, setIsLoading] = useState(!ready);
|
|
130
|
+
const [documentFields, setDocumentFields] = useState<DocumentFields>({});
|
|
131
|
+
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
132
|
+
const prevDocIdRef = useRef<string | undefined>(documentId);
|
|
133
|
+
|
|
134
|
+
// Reset loading state on doc switch so downstream tabs can show their own loading UI
|
|
135
|
+
// instead of flashing "Missing" cards based on the previous doc's data.
|
|
136
|
+
useEffect(() => {
|
|
137
|
+
if (prevDocIdRef.current !== documentId) {
|
|
138
|
+
prevDocIdRef.current = documentId;
|
|
139
|
+
setIsLoading(true);
|
|
140
|
+
}
|
|
141
|
+
}, [documentId]);
|
|
142
|
+
|
|
143
|
+
useEffect(() => {
|
|
144
|
+
const bodyText = extractText(body);
|
|
145
|
+
const fullText = [title, bodyText].filter(Boolean).join("\n\n");
|
|
146
|
+
|
|
147
|
+
const val = value as Record<string, unknown> | undefined;
|
|
148
|
+
|
|
149
|
+
// Author extraction - covers several common Sanity schemas.
|
|
150
|
+
// Note: Sanity references aren't auto-resolved by useDocumentPane; we detect them
|
|
151
|
+
// separately so the audit doesn't flag ref-based authors as "Missing".
|
|
152
|
+
let authorName: string | undefined;
|
|
153
|
+
let authorCredentials: string | undefined;
|
|
154
|
+
let authorBioUrl: string | undefined;
|
|
155
|
+
let authorIsReference = false;
|
|
156
|
+
const author = (val?.author || (Array.isArray(val?.authors) && (val.authors as unknown[])[0]) || val?.byline) as
|
|
157
|
+
| Record<string, unknown>
|
|
158
|
+
| string
|
|
159
|
+
| undefined;
|
|
160
|
+
if (typeof author === "string") {
|
|
161
|
+
authorName = author;
|
|
162
|
+
} else if (author && typeof author === "object") {
|
|
163
|
+
authorName =
|
|
164
|
+
(author.name as string | undefined) ||
|
|
165
|
+
(author.fullName as string | undefined) ||
|
|
166
|
+
(author.displayName as string | undefined);
|
|
167
|
+
authorCredentials =
|
|
168
|
+
(author.credentials as string | undefined) ||
|
|
169
|
+
(author.title as string | undefined) ||
|
|
170
|
+
(author.suffix as string | undefined);
|
|
171
|
+
authorBioUrl = (author.bioUrl as string | undefined) || ((author.slug as { current?: string })?.current ? `/author/${(author.slug as { current?: string }).current}` : undefined);
|
|
172
|
+
// Sanity reference: { _type: 'reference', _ref: '...' } with no inline name
|
|
173
|
+
if (!authorName && typeof author._ref === "string") {
|
|
174
|
+
authorIsReference = true;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
|
|
179
|
+
const fields: DocumentFields = {
|
|
180
|
+
title: title || undefined,
|
|
181
|
+
metaDescription: (val?.metaDescription || val?.summary || val?.description || val?.seoDescription) as string | undefined,
|
|
182
|
+
slug: (val?.slug as { current?: string })?.current || undefined,
|
|
183
|
+
imageNames: imageMeta.names,
|
|
184
|
+
imageTitles: imageMeta.titles,
|
|
185
|
+
imageCount: imageMeta.count,
|
|
186
|
+
headings: extractHeadings(body),
|
|
187
|
+
headingsDetailed: extractHeadingsDetailed(body),
|
|
188
|
+
bodyLinks: extractBodyLinks(body),
|
|
189
|
+
contentCategory: (val?.contentCategory || val?.category) as string | undefined,
|
|
190
|
+
contentPlacement: Array.isArray(val?.contentPlacement) ? (val.contentPlacement as string[]) : undefined,
|
|
191
|
+
authorName,
|
|
192
|
+
authorCredentials,
|
|
193
|
+
authorBioUrl,
|
|
194
|
+
authorIsReference,
|
|
195
|
+
publishedAt: (val?.publishedAt || val?.publishDate || val?._createdAt) as string | undefined,
|
|
196
|
+
updatedAt: (val?.updatedAt || val?._updatedAt) as string | undefined,
|
|
197
|
+
lastReviewedAt: (val?.lastReviewedAt || val?.lastReviewed || val?.medicallyReviewedAt) as string | undefined,
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
// documentFields are cheap and shown immediately so the Technical tab doesn't flash
|
|
201
|
+
// "Missing" cards while the text debounce is pending. Only debounce text since that
|
|
202
|
+
// drives the expensive AI analysis calls.
|
|
203
|
+
setDocumentFields(fields);
|
|
204
|
+
|
|
205
|
+
if (timerRef.current) clearTimeout(timerRef.current);
|
|
206
|
+
|
|
207
|
+
timerRef.current = setTimeout(() => {
|
|
208
|
+
setDebouncedText(fullText);
|
|
209
|
+
setIsLoading(false);
|
|
210
|
+
}, 2000);
|
|
211
|
+
|
|
212
|
+
return () => { if (timerRef.current) clearTimeout(timerRef.current); };
|
|
213
|
+
}, [title, body, value]);
|
|
214
|
+
|
|
215
|
+
return { text: debouncedText, isLoading, documentFields, documentId };
|
|
216
|
+
}
|
|
@@ -49,16 +49,16 @@ export function useKeywordAnalysis(
|
|
|
49
49
|
documentId?: string
|
|
50
50
|
) {
|
|
51
51
|
const cacheKey = documentId ? `seo-copilot-cache-${documentId}` : "seo-copilot-cache-v2";
|
|
52
|
-
const loadCached = (): { analysis: SEOAnalysis | null; deepAnalysis: DeepAnalysis | null; seeds: string[] } => {
|
|
52
|
+
const loadCached = useCallback((): { analysis: SEOAnalysis | null; deepAnalysis: DeepAnalysis | null; seeds: string[] } => {
|
|
53
53
|
try {
|
|
54
|
-
if (typeof window !== "undefined" &&
|
|
55
|
-
|
|
54
|
+
if (typeof window !== "undefined" && localStorage.getItem("seo-copilot-cache")) {
|
|
55
|
+
localStorage.removeItem("seo-copilot-cache");
|
|
56
56
|
}
|
|
57
|
-
const raw = typeof window !== "undefined" ?
|
|
57
|
+
const raw = typeof window !== "undefined" ? localStorage.getItem(cacheKey) : null;
|
|
58
58
|
if (raw) return JSON.parse(raw);
|
|
59
59
|
} catch { /* ignore */ }
|
|
60
60
|
return { analysis: null, deepAnalysis: null, seeds: [] };
|
|
61
|
-
};
|
|
61
|
+
}, [cacheKey]);
|
|
62
62
|
const cached = useRef(loadCached());
|
|
63
63
|
|
|
64
64
|
const [analysis, setAnalysisRaw] = useState<SEOAnalysis | null>(cached.current.analysis);
|
|
@@ -71,6 +71,26 @@ export function useKeywordAnalysis(
|
|
|
71
71
|
const [aeoTextSnapshot, setAeoTextSnapshot] = useState<string>("");
|
|
72
72
|
const [aeoContentChanged, setAeoContentChanged] = useState(false);
|
|
73
73
|
|
|
74
|
+
// Reload cached state when documentId (and therefore cacheKey) changes.
|
|
75
|
+
// Skip the first invocation since useState above already initialized correctly.
|
|
76
|
+
const cacheInitializedRef = useRef(false);
|
|
77
|
+
useEffect(() => {
|
|
78
|
+
if (!cacheInitializedRef.current) {
|
|
79
|
+
cacheInitializedRef.current = true;
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const fresh = loadCached();
|
|
83
|
+
cached.current = fresh;
|
|
84
|
+
setAnalysisRaw(fresh.analysis);
|
|
85
|
+
setDeepAnalysisRaw(fresh.deepAnalysis);
|
|
86
|
+
setError(null);
|
|
87
|
+
setIsLoading(false);
|
|
88
|
+
setIsVolumesLoading(false);
|
|
89
|
+
setIsDeepLoading(false);
|
|
90
|
+
setAeoTextSnapshot("");
|
|
91
|
+
setAeoContentChanged(false);
|
|
92
|
+
}, [cacheKey, loadCached]);
|
|
93
|
+
|
|
74
94
|
// Persistent volume cache - survives analysis re-runs
|
|
75
95
|
const volumeMapRef = useRef(new Map<string, { volume: number; cpc: number; competition: number }>());
|
|
76
96
|
|
|
@@ -80,14 +100,14 @@ export function useKeywordAnalysis(
|
|
|
80
100
|
setAnalysisRaw(withVolumes);
|
|
81
101
|
try {
|
|
82
102
|
const prev = loadCached();
|
|
83
|
-
|
|
103
|
+
localStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: withVolumes }));
|
|
84
104
|
} catch { /* ignore */ }
|
|
85
105
|
}, [cacheKey]);
|
|
86
106
|
const setDeepAnalysis = useCallback((val: DeepAnalysis | null) => {
|
|
87
107
|
setDeepAnalysisRaw(val);
|
|
88
108
|
try {
|
|
89
109
|
const prev = loadCached();
|
|
90
|
-
|
|
110
|
+
localStorage.setItem(cacheKey, JSON.stringify({ ...prev, deepAnalysis: val }));
|
|
91
111
|
} catch { /* ignore */ }
|
|
92
112
|
}, [cacheKey]);
|
|
93
113
|
|
|
@@ -178,7 +198,7 @@ export function useKeywordAnalysis(
|
|
|
178
198
|
setAnalysisRaw(merged);
|
|
179
199
|
try {
|
|
180
200
|
const prev = loadCached();
|
|
181
|
-
|
|
201
|
+
localStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: merged }));
|
|
182
202
|
} catch { /* ignore */ }
|
|
183
203
|
setIsVolumesLoading(false);
|
|
184
204
|
})
|
package/src/hooks/useSEOChat.ts
CHANGED
|
@@ -11,7 +11,6 @@ interface KeywordPanelData {
|
|
|
11
11
|
contentScore?: number;
|
|
12
12
|
aeoData?: {
|
|
13
13
|
questionHeadings: { suggestedHeading: string; rationale: string }[];
|
|
14
|
-
faqSuggestions: { question: string; answer: string }[];
|
|
15
14
|
};
|
|
16
15
|
}
|
|
17
16
|
|
|
@@ -36,18 +35,21 @@ export function useSEOChat(
|
|
|
36
35
|
keywordPanelData?: KeywordPanelData,
|
|
37
36
|
documentId?: string
|
|
38
37
|
) {
|
|
39
|
-
// Chat messages cached in
|
|
38
|
+
// Chat messages cached in localStorage for persistence across close/reopen.
|
|
39
|
+
// The cache key changes when documentId changes, so we must reload state on doc change.
|
|
40
40
|
const chatCacheKey = documentId ? `seo-copilot-chat-${documentId}` : "seo-copilot-chat-default";
|
|
41
|
-
const
|
|
41
|
+
const loadCachedMessages = useCallback((): ChatMessage[] => {
|
|
42
42
|
try {
|
|
43
|
-
const cached = typeof window !== "undefined" ?
|
|
43
|
+
const cached = typeof window !== "undefined" ? localStorage.getItem(chatCacheKey) : null;
|
|
44
44
|
return cached ? JSON.parse(cached) : [];
|
|
45
45
|
} catch { return []; }
|
|
46
|
-
});
|
|
46
|
+
}, [chatCacheKey]);
|
|
47
|
+
|
|
48
|
+
const [messages, setMessagesRaw] = useState<ChatMessage[]>(loadCachedMessages);
|
|
47
49
|
const setMessages = useCallback((msgs: ChatMessage[] | ((prev: ChatMessage[]) => ChatMessage[])) => {
|
|
48
50
|
setMessagesRaw((prev) => {
|
|
49
51
|
const next = typeof msgs === "function" ? msgs(prev) : msgs;
|
|
50
|
-
try {
|
|
52
|
+
try { localStorage.setItem(chatCacheKey, JSON.stringify(next)); } catch {}
|
|
51
53
|
return next;
|
|
52
54
|
});
|
|
53
55
|
}, [chatCacheKey]);
|
|
@@ -65,20 +67,45 @@ export function useSEOChat(
|
|
|
65
67
|
}, [sanityUser?.id]);
|
|
66
68
|
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
67
69
|
|
|
68
|
-
//
|
|
70
|
+
// Per-document operation version to invalidate stale in-flight loads
|
|
71
|
+
const opVersionRef = useRef(0);
|
|
72
|
+
|
|
73
|
+
// Reload state when document changes (Sanity inspector may reuse instance)
|
|
74
|
+
// Use a ref to skip the very first effect run since useState already initialized correctly.
|
|
75
|
+
const didInitRef = useRef(false);
|
|
76
|
+
useEffect(() => {
|
|
77
|
+
if (!didInitRef.current) {
|
|
78
|
+
didInitRef.current = true;
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
opVersionRef.current += 1;
|
|
82
|
+
setMessagesRaw(loadCachedMessages());
|
|
83
|
+
setIsStreaming(false);
|
|
84
|
+
setHistoryLoaded(false);
|
|
85
|
+
if (saveTimerRef.current) {
|
|
86
|
+
clearTimeout(saveTimerRef.current);
|
|
87
|
+
saveTimerRef.current = null;
|
|
88
|
+
}
|
|
89
|
+
}, [documentId, loadCachedMessages]);
|
|
90
|
+
|
|
91
|
+
// Load from server-side chat history on mount (and on doc change, since historyLoaded is reset above)
|
|
69
92
|
useEffect(() => {
|
|
70
93
|
if (!documentId || historyLoaded) return;
|
|
94
|
+
const myVersion = opVersionRef.current;
|
|
71
95
|
let cancelled = false;
|
|
72
96
|
loadChatHistory(apiUrl, userId.current, documentId).then((loaded) => {
|
|
73
|
-
if (
|
|
74
|
-
|
|
97
|
+
if (cancelled || opVersionRef.current !== myVersion) return;
|
|
98
|
+
if (loaded.length > 0) {
|
|
99
|
+
// Functional update to avoid clobbering messages the user typed during the load
|
|
100
|
+
setMessages((current) => (current.length === 0 ? loaded : current));
|
|
75
101
|
}
|
|
76
|
-
|
|
102
|
+
setHistoryLoaded(true);
|
|
77
103
|
});
|
|
78
104
|
return () => { cancelled = true; };
|
|
105
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
79
106
|
}, [apiUrl, documentId, historyLoaded]);
|
|
80
107
|
|
|
81
|
-
// Debounced save to server (best-effort,
|
|
108
|
+
// Debounced save to server (best-effort, localStorage is the primary)
|
|
82
109
|
const scheduleSave = useCallback((msgs: ChatMessage[]) => {
|
|
83
110
|
if (!documentId) return;
|
|
84
111
|
if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
|
package/src/lib/api.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { SEOAnalysis, DeepAnalysis, ChatMessage, DocumentFields } from "./types";
|
|
1
|
+
import type { SEOAnalysis, DeepAnalysis, ChatMessage, DocumentFields, ContentSuggestions, InternalLink, LinkingSuggestion, LinkCheckResult } from "./types";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Safely parse JSON from a response that may have been truncated by
|
|
@@ -58,7 +58,6 @@ export async function fetchChatStream(
|
|
|
58
58
|
missingKeywords?: { term: string; volume: number | null }[];
|
|
59
59
|
aeoData?: {
|
|
60
60
|
questionHeadings: { suggestedHeading: string; rationale: string }[];
|
|
61
|
-
faqSuggestions: { question: string; answer: string }[];
|
|
62
61
|
};
|
|
63
62
|
}
|
|
64
63
|
): Promise<ReadableStream<Uint8Array> | null> {
|
|
@@ -140,20 +139,117 @@ export async function loadChatHistory(
|
|
|
140
139
|
}
|
|
141
140
|
}
|
|
142
141
|
|
|
143
|
-
export async function
|
|
142
|
+
export async function fetchContentSuggestions(
|
|
144
143
|
apiUrl: string,
|
|
145
144
|
content: string,
|
|
146
|
-
|
|
145
|
+
primaryKeyword: string,
|
|
147
146
|
publication?: string
|
|
148
|
-
): Promise<
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
147
|
+
): Promise<ContentSuggestions> {
|
|
148
|
+
const empty: ContentSuggestions = { keyTakeaways: [], infographicOpportunities: [], bulletListItems: [] };
|
|
149
|
+
try {
|
|
150
|
+
const res = await fetch(`${apiUrl}/api/seo-copilot/content-suggestions`, {
|
|
151
|
+
method: "POST",
|
|
152
|
+
headers: { "Content-Type": "application/json" },
|
|
153
|
+
body: JSON.stringify({ content, primaryKeyword, publication }),
|
|
154
|
+
});
|
|
155
|
+
if (!res.ok) return empty;
|
|
156
|
+
const data = await res.json().catch(() => null);
|
|
157
|
+
if (!data || typeof data !== "object") return empty;
|
|
158
|
+
return {
|
|
159
|
+
keyTakeaways: Array.isArray(data.keyTakeaways) ? data.keyTakeaways : [],
|
|
160
|
+
infographicOpportunities: Array.isArray(data.infographicOpportunities) ? data.infographicOpportunities : [],
|
|
161
|
+
bulletListItems: Array.isArray(data.bulletListItems) ? data.bulletListItems : [],
|
|
162
|
+
};
|
|
163
|
+
} catch {
|
|
164
|
+
return empty;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export async function fetchInternalLinks(
|
|
169
|
+
apiUrl: string,
|
|
170
|
+
keywords: string[],
|
|
171
|
+
currentDocumentId?: string,
|
|
172
|
+
publication?: string
|
|
173
|
+
): Promise<InternalLink[]> {
|
|
174
|
+
if (!keywords || keywords.length === 0) return [];
|
|
175
|
+
try {
|
|
176
|
+
const res = await fetch(`${apiUrl}/api/seo-copilot/articles`, {
|
|
177
|
+
method: "POST",
|
|
178
|
+
headers: { "Content-Type": "application/json" },
|
|
179
|
+
body: JSON.stringify({ action: "related", keywords, publication }),
|
|
180
|
+
});
|
|
181
|
+
if (!res.ok) return [];
|
|
182
|
+
const data = await res.json().catch(() => null);
|
|
183
|
+
if (!data || typeof data !== "object") return [];
|
|
184
|
+
type ArticleResult = { _id?: string; title?: string; slug?: string; publishedAt?: string };
|
|
185
|
+
const articles: ArticleResult[] = Array.isArray(data.articles) ? data.articles : [];
|
|
186
|
+
const filtered = currentDocumentId
|
|
187
|
+
? articles.filter((a) => a._id !== currentDocumentId)
|
|
188
|
+
: articles;
|
|
189
|
+
return filtered.map((a): InternalLink => ({
|
|
190
|
+
_id: a._id,
|
|
191
|
+
title: a.title || "Untitled",
|
|
192
|
+
slug: a.slug || "",
|
|
193
|
+
publishedAt: a.publishedAt,
|
|
194
|
+
relevanceReason: matchedKeyword(a.title, keywords),
|
|
195
|
+
}));
|
|
196
|
+
} catch {
|
|
197
|
+
return [];
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function matchedKeyword(title: string | undefined, keywords: string[]): string {
|
|
202
|
+
const lower = (title || "").toLowerCase();
|
|
203
|
+
if (!lower) return "Related to current topic";
|
|
204
|
+
for (const kw of keywords) {
|
|
205
|
+
if (kw && lower.includes(kw.toLowerCase())) {
|
|
206
|
+
return `Matches "${kw}"`;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return "Related to current topic";
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export async function fetchLinkingSuggestions(
|
|
213
|
+
apiUrl: string,
|
|
214
|
+
content: string,
|
|
215
|
+
primaryKeyword: string,
|
|
216
|
+
supportingKeywords: string[],
|
|
217
|
+
currentDocumentId?: string,
|
|
218
|
+
publication?: string
|
|
219
|
+
): Promise<LinkingSuggestion[]> {
|
|
220
|
+
if (!content || content.trim().length < 50) return [];
|
|
221
|
+
try {
|
|
222
|
+
const res = await fetch(`${apiUrl}/api/seo-copilot/linking-suggestions`, {
|
|
223
|
+
method: "POST",
|
|
224
|
+
headers: { "Content-Type": "application/json" },
|
|
225
|
+
body: JSON.stringify({ content, primaryKeyword, supportingKeywords, currentDocumentId, publication }),
|
|
226
|
+
});
|
|
227
|
+
if (!res.ok) return [];
|
|
228
|
+
const data = await res.json().catch(() => null);
|
|
229
|
+
if (!data || !Array.isArray(data.suggestions)) return [];
|
|
230
|
+
return data.suggestions as LinkingSuggestion[];
|
|
231
|
+
} catch {
|
|
232
|
+
return [];
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Calls the backend broken-link scanner. Returns one result per unique URL,
|
|
237
|
+
// or an empty array on failure (so callers don't have to handle errors).
|
|
238
|
+
export async function checkLinks(apiUrl: string, urls: string[]): Promise<LinkCheckResult[]> {
|
|
239
|
+
if (!urls || urls.length === 0) return [];
|
|
240
|
+
try {
|
|
241
|
+
const res = await fetch(`${apiUrl}/api/seo-copilot/check-links`, {
|
|
242
|
+
method: "POST",
|
|
243
|
+
headers: { "Content-Type": "application/json" },
|
|
244
|
+
body: JSON.stringify({ urls }),
|
|
245
|
+
});
|
|
246
|
+
if (!res.ok) return [];
|
|
247
|
+
const data = await res.json().catch(() => null);
|
|
248
|
+
if (!data || !Array.isArray(data.results)) return [];
|
|
249
|
+
return data.results as LinkCheckResult[];
|
|
250
|
+
} catch {
|
|
251
|
+
return [];
|
|
252
|
+
}
|
|
157
253
|
}
|
|
158
254
|
|
|
159
255
|
export async function saveChatHistory(
|