sanity-plugin-seo-copilot 0.1.0 → 0.1.2

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.
@@ -1,225 +1,226 @@
1
- import { useState, useEffect, useCallback, useRef } from "react";
2
- import { fetchAnalysis, lookupKeywords } from "../lib/api";
3
- import type { SEOAnalysis, DeepAnalysis, DocumentFields } from "../lib/types";
4
-
5
- function mergeVolumes(
6
- analysis: SEOAnalysis,
7
- volumeMap: Map<string, { volume: number; cpc: number; competition: number }>
8
- ): SEOAnalysis {
9
- const updated = { ...analysis };
10
-
11
- // Merge volumes into all primaryKeywordCandidates
12
- if (updated.primaryKeywordCandidates && updated.primaryKeywordCandidates.length > 0) {
13
- updated.primaryKeywordCandidates = updated.primaryKeywordCandidates.map((candidate) => {
14
- const data = volumeMap.get(candidate.term.toLowerCase());
15
- return data ? { ...candidate, volume: data.volume, cpc: data.cpc, competition: data.competition } : candidate;
16
- });
17
- }
18
-
19
- // Also update legacy primaryKeyword
20
- const primaryData = volumeMap.get(updated.primaryKeyword.term.toLowerCase());
21
- if (primaryData) {
22
- updated.primaryKeyword = {
23
- ...updated.primaryKeyword,
24
- volume: primaryData.volume,
25
- cpc: primaryData.cpc,
26
- competition: primaryData.competition,
27
- };
28
- }
29
-
30
- updated.supportingKeywords = updated.supportingKeywords.map((kw) => {
31
- const data = volumeMap.get(kw.term.toLowerCase());
32
- return data ? { ...kw, volume: data.volume } : kw;
33
- });
34
-
35
- updated.missingKeywords = updated.missingKeywords.map((kw) => {
36
- const data = volumeMap.get(kw.term.toLowerCase());
37
- return data ? { ...kw, volume: data.volume } : kw;
38
- });
39
-
40
- return updated;
41
- }
42
-
43
- export function useKeywordAnalysis(
44
- text: string,
45
- apiUrl: string,
46
- publication?: string,
47
- seedKeywords?: string[],
48
- documentFields?: DocumentFields,
49
- focusPrimary?: string,
50
- documentId?: string
51
- ) {
52
- // Restore cached results from sessionStorage on mount (survives inspector close/reopen)
53
- const cacheKey = documentId ? `seo-copilot-cache-${documentId}` : "seo-copilot-cache-v2";
54
- const loadCached = (): { analysis: SEOAnalysis | null; deepAnalysis: DeepAnalysis | null; seeds: string[] } => {
55
- try {
56
- if (typeof window !== "undefined" && sessionStorage.getItem("seo-copilot-cache")) {
57
- sessionStorage.removeItem("seo-copilot-cache");
58
- }
59
- const raw = typeof window !== "undefined" ? sessionStorage.getItem(cacheKey) : null;
60
- if (raw) return JSON.parse(raw);
61
- } catch { /* ignore */ }
62
- return { analysis: null, deepAnalysis: null, seeds: [] };
63
- };
64
- const cached = useRef(loadCached());
65
-
66
- const [analysis, setAnalysisRaw] = useState<SEOAnalysis | null>(cached.current.analysis);
67
- const [isLoading, setIsLoading] = useState(false);
68
- const [isVolumesLoading, setIsVolumesLoading] = useState(false);
69
- const [error, setError] = useState<string | null>(null);
70
-
71
- const [deepAnalysis, setDeepAnalysisRaw] = useState<DeepAnalysis | null>(cached.current.deepAnalysis);
72
- const [isDeepLoading, setIsDeepLoading] = useState(false);
73
- const [aeoTextSnapshot, setAeoTextSnapshot] = useState<string>("");
74
- const [aeoContentChanged, setAeoContentChanged] = useState(false);
75
-
76
- const setAnalysis = useCallback((val: SEOAnalysis | null) => {
77
- setAnalysisRaw(val);
78
- try {
79
- const prev = loadCached();
80
- sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: val }));
81
- } catch { /* ignore */ }
82
- }, [cacheKey]);
83
- const setDeepAnalysis = useCallback((val: DeepAnalysis | null) => {
84
- setDeepAnalysisRaw(val);
85
- try {
86
- const prev = loadCached();
87
- sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, deepAnalysis: val }));
88
- } catch { /* ignore */ }
89
- }, [cacheKey]);
90
-
91
- // focusPrimary is a LIGHT signal - not merged into seeds (too heavy).
92
- // Seeds heavily weight. focusPrimary just slightly nudges.
93
- const effectiveSeeds = seedKeywords;
94
-
95
- // Track if content changed since AEO was generated
96
- useEffect(() => {
97
- if (deepAnalysis && aeoTextSnapshot && text !== aeoTextSnapshot) {
98
- setAeoContentChanged(true);
99
- }
100
- }, [text, deepAnalysis, aeoTextSnapshot]);
101
-
102
- // Track whether initial volume lookup has been done for this analysis
103
- const volumesLoadedRef = useRef(false);
104
- const lastAnalysisRef = useRef<SEOAnalysis | null>(null);
105
- const prevSeedsRef = useRef(effectiveSeeds?.join(",") || "");
106
- const prevFocusRef = useRef(focusPrimary || "");
107
-
108
- // Reset volume tracking when seeds or primary keyword change (these are explicit user actions)
109
- const currentSeedsKey = effectiveSeeds?.join(",") || "";
110
- const currentFocusKey = focusPrimary || "";
111
- if (currentSeedsKey !== prevSeedsRef.current || currentFocusKey !== prevFocusRef.current) {
112
- volumesLoadedRef.current = false;
113
- prevSeedsRef.current = currentSeedsKey;
114
- prevFocusRef.current = currentFocusKey;
115
- }
116
-
117
- // Real-time analysis: Claude suggests keywords (no volume lookups on content changes)
118
- useEffect(() => {
119
- if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
120
- setAnalysis(null);
121
- volumesLoadedRef.current = false;
122
- return;
123
- }
124
-
125
- let cancelled = false;
126
- setIsLoading(true);
127
- setError(null);
128
-
129
- fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary)
130
- .then((result) => {
131
- if (cancelled) return;
132
- const analysisResult = result as SEOAnalysis;
133
- lastAnalysisRef.current = analysisResult;
134
-
135
- // Show keywords immediately without volumes
136
- setAnalysis(analysisResult);
137
- setIsLoading(false);
138
-
139
- // Only auto-lookup volumes on FIRST analysis (initial load)
140
- // Subsequent content changes show keywords without re-looking up volumes
141
- if (!volumesLoadedRef.current) {
142
- volumesLoadedRef.current = true;
143
- doVolumeLookup(analysisResult, cancelled);
144
- }
145
- })
146
- .catch((err) => {
147
- if (!cancelled) {
148
- setError(err.message);
149
- setIsLoading(false);
150
- }
151
- });
152
-
153
- return () => {
154
- cancelled = true;
155
- };
156
- }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary]);
157
-
158
- // Volume lookup helper - reused by auto-lookup and manual refresh
159
- const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, cancelled?: boolean) => {
160
- setIsVolumesLoading(true);
161
-
162
- const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
163
- const allTerms = [
164
- ...new Set([
165
- ...candidateTerms,
166
- analysisResult.primaryKeyword.term,
167
- ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
168
- ...analysisResult.missingKeywords.map((kw) => kw.term),
169
- ]),
170
- ];
171
-
172
- lookupKeywords(apiUrl, allTerms)
173
- .then(({ results }) => {
174
- if (cancelled) return;
175
- const volumeMap = new Map(
176
- results.map((r) => [r.keyword.toLowerCase(), r])
177
- );
178
- setAnalysis(mergeVolumes(analysisResult, volumeMap));
179
- setIsVolumesLoading(false);
180
- })
181
- .catch(() => {
182
- if (!cancelled) {
183
- setIsVolumesLoading(false);
184
- }
185
- });
186
- }, [apiUrl]);
187
-
188
- // Manual refresh volumes - called by UI actions (seed change, primary change, refresh button)
189
- const refreshVolumes = useCallback(() => {
190
- const current = lastAnalysisRef.current || analysis;
191
- if (!current) return;
192
- doVolumeLookup(current);
193
- }, [analysis, doVolumeLookup]);
194
-
195
- const runDeepAnalysis = useCallback(() => {
196
- if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) return;
197
-
198
- setIsDeepLoading(true);
199
- setError(null);
200
- setAeoContentChanged(false);
201
- setAeoTextSnapshot(text);
202
-
203
- fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary)
204
- .then((result) => {
205
- setDeepAnalysis(result as DeepAnalysis);
206
- setIsDeepLoading(false);
207
- })
208
- .catch((err) => {
209
- setError(err.message);
210
- setIsDeepLoading(false);
211
- });
212
- }, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields]);
213
-
214
- return {
215
- analysis,
216
- isLoading,
217
- isVolumesLoading,
218
- error,
219
- deepAnalysis,
220
- isDeepLoading,
221
- runDeepAnalysis,
222
- refreshVolumes,
223
- aeoContentChanged,
224
- };
225
- }
1
+ import { useState, useEffect, useCallback, useRef } from "react";
2
+ import { fetchAnalysis, lookupKeywords } from "../lib/api";
3
+ import type { SEOAnalysis, DeepAnalysis, DocumentFields } from "../lib/types";
4
+
5
+ function mergeVolumes(
6
+ analysis: SEOAnalysis,
7
+ volumeMap: Map<string, { volume: number; cpc: number; competition: number }>
8
+ ): SEOAnalysis {
9
+ if (volumeMap.size === 0) return analysis;
10
+ const updated = { ...analysis };
11
+
12
+ if (updated.primaryKeywordCandidates && updated.primaryKeywordCandidates.length > 0) {
13
+ updated.primaryKeywordCandidates = updated.primaryKeywordCandidates.map((candidate) => {
14
+ const data = volumeMap.get(candidate.term.toLowerCase());
15
+ return data ? { ...candidate, volume: data.volume, cpc: data.cpc, competition: data.competition } : candidate;
16
+ });
17
+ }
18
+
19
+ const primaryData = volumeMap.get(updated.primaryKeyword.term.toLowerCase());
20
+ if (primaryData) {
21
+ updated.primaryKeyword = {
22
+ ...updated.primaryKeyword,
23
+ volume: primaryData.volume,
24
+ cpc: primaryData.cpc,
25
+ competition: primaryData.competition,
26
+ };
27
+ }
28
+
29
+ updated.supportingKeywords = updated.supportingKeywords.map((kw) => {
30
+ const data = volumeMap.get(kw.term.toLowerCase());
31
+ return data ? { ...kw, volume: data.volume } : kw;
32
+ });
33
+
34
+ updated.missingKeywords = updated.missingKeywords.map((kw) => {
35
+ const data = volumeMap.get(kw.term.toLowerCase());
36
+ return data ? { ...kw, volume: data.volume } : kw;
37
+ });
38
+
39
+ return updated;
40
+ }
41
+
42
+ export function useKeywordAnalysis(
43
+ text: string,
44
+ apiUrl: string,
45
+ publication?: string,
46
+ seedKeywords?: string[],
47
+ documentFields?: DocumentFields,
48
+ focusPrimary?: string,
49
+ documentId?: string
50
+ ) {
51
+ const cacheKey = documentId ? `seo-copilot-cache-${documentId}` : "seo-copilot-cache-v2";
52
+ const loadCached = (): { analysis: SEOAnalysis | null; deepAnalysis: DeepAnalysis | null; seeds: string[] } => {
53
+ try {
54
+ if (typeof window !== "undefined" && sessionStorage.getItem("seo-copilot-cache")) {
55
+ sessionStorage.removeItem("seo-copilot-cache");
56
+ }
57
+ const raw = typeof window !== "undefined" ? sessionStorage.getItem(cacheKey) : null;
58
+ if (raw) return JSON.parse(raw);
59
+ } catch { /* ignore */ }
60
+ return { analysis: null, deepAnalysis: null, seeds: [] };
61
+ };
62
+ const cached = useRef(loadCached());
63
+
64
+ const [analysis, setAnalysisRaw] = useState<SEOAnalysis | null>(cached.current.analysis);
65
+ const [isLoading, setIsLoading] = useState(false);
66
+ const [isVolumesLoading, setIsVolumesLoading] = useState(false);
67
+ const [error, setError] = useState<string | null>(null);
68
+
69
+ const [deepAnalysis, setDeepAnalysisRaw] = useState<DeepAnalysis | null>(cached.current.deepAnalysis);
70
+ const [isDeepLoading, setIsDeepLoading] = useState(false);
71
+ const [aeoTextSnapshot, setAeoTextSnapshot] = useState<string>("");
72
+ const [aeoContentChanged, setAeoContentChanged] = useState(false);
73
+
74
+ // Persistent volume cache - survives analysis re-runs
75
+ const volumeMapRef = useRef(new Map<string, { volume: number; cpc: number; competition: number }>());
76
+
77
+ const setAnalysis = useCallback((val: SEOAnalysis | null) => {
78
+ // Always re-apply cached volumes to any new analysis
79
+ const withVolumes = val ? mergeVolumes(val, volumeMapRef.current) : null;
80
+ setAnalysisRaw(withVolumes);
81
+ try {
82
+ const prev = loadCached();
83
+ sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: withVolumes }));
84
+ } catch { /* ignore */ }
85
+ }, [cacheKey]);
86
+ const setDeepAnalysis = useCallback((val: DeepAnalysis | null) => {
87
+ setDeepAnalysisRaw(val);
88
+ try {
89
+ const prev = loadCached();
90
+ sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, deepAnalysis: val }));
91
+ } catch { /* ignore */ }
92
+ }, [cacheKey]);
93
+
94
+ const effectiveSeeds = seedKeywords;
95
+
96
+ useEffect(() => {
97
+ if (deepAnalysis && aeoTextSnapshot && text !== aeoTextSnapshot) {
98
+ setAeoContentChanged(true);
99
+ }
100
+ }, [text, deepAnalysis, aeoTextSnapshot]);
101
+
102
+ const lastAnalysisRef = useRef<SEOAnalysis | null>(null);
103
+
104
+ useEffect(() => {
105
+ if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
106
+ setAnalysis(null);
107
+ return;
108
+ }
109
+
110
+ let cancelled = false;
111
+ setIsLoading(true);
112
+ setError(null);
113
+
114
+ fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary)
115
+ .then((result) => {
116
+ if (cancelled) return;
117
+ const analysisResult = result as SEOAnalysis;
118
+ lastAnalysisRef.current = analysisResult;
119
+ setAnalysis(analysisResult); // volumes auto-applied via setAnalysis wrapper
120
+ setIsLoading(false);
121
+
122
+ // Look up volumes for any NEW terms not already in the cache
123
+ const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
124
+ const allTerms = [
125
+ ...new Set([
126
+ ...candidateTerms,
127
+ analysisResult.primaryKeyword.term,
128
+ ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
129
+ ...analysisResult.missingKeywords.map((kw) => kw.term),
130
+ ]),
131
+ ];
132
+ const uncachedTerms = allTerms.filter((t) => !volumeMapRef.current.has(t.toLowerCase()));
133
+
134
+ if (uncachedTerms.length > 0) {
135
+ doVolumeLookup(analysisResult, uncachedTerms);
136
+ }
137
+ })
138
+ .catch((err) => {
139
+ if (!cancelled) {
140
+ setError(err.message);
141
+ setIsLoading(false);
142
+ }
143
+ });
144
+
145
+ return () => {
146
+ cancelled = true;
147
+ };
148
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary]);
149
+
150
+ const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, terms?: string[]) => {
151
+ setIsVolumesLoading(true);
152
+
153
+ const lookupTerms = terms || (() => {
154
+ const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
155
+ return [
156
+ ...new Set([
157
+ ...candidateTerms,
158
+ analysisResult.primaryKeyword.term,
159
+ ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
160
+ ...analysisResult.missingKeywords.map((kw) => kw.term),
161
+ ]),
162
+ ];
163
+ })();
164
+
165
+ if (lookupTerms.length === 0) {
166
+ setIsVolumesLoading(false);
167
+ return;
168
+ }
169
+
170
+ lookupKeywords(apiUrl, lookupTerms)
171
+ .then(({ results }) => {
172
+ // Add new results to persistent cache
173
+ results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
174
+ // Re-apply all cached volumes to current analysis
175
+ const current = lastAnalysisRef.current || analysisResult;
176
+ const merged = mergeVolumes(current, volumeMapRef.current);
177
+ lastAnalysisRef.current = merged;
178
+ setAnalysisRaw(merged);
179
+ try {
180
+ const prev = loadCached();
181
+ sessionStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: merged }));
182
+ } catch { /* ignore */ }
183
+ setIsVolumesLoading(false);
184
+ })
185
+ .catch(() => {
186
+ setIsVolumesLoading(false);
187
+ });
188
+ }, [apiUrl, cacheKey]);
189
+
190
+ const refreshVolumes = useCallback(() => {
191
+ const current = lastAnalysisRef.current || analysis;
192
+ if (!current) return;
193
+ doVolumeLookup(current);
194
+ }, [analysis, doVolumeLookup]);
195
+
196
+ const runDeepAnalysis = useCallback(() => {
197
+ if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) return;
198
+
199
+ setIsDeepLoading(true);
200
+ setError(null);
201
+ setAeoContentChanged(false);
202
+ setAeoTextSnapshot(text);
203
+
204
+ fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary)
205
+ .then((result) => {
206
+ setDeepAnalysis(result as DeepAnalysis);
207
+ setIsDeepLoading(false);
208
+ })
209
+ .catch((err) => {
210
+ setError(err.message);
211
+ setIsDeepLoading(false);
212
+ });
213
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields]);
214
+
215
+ return {
216
+ analysis,
217
+ isLoading,
218
+ isVolumesLoading,
219
+ error,
220
+ deepAnalysis,
221
+ isDeepLoading,
222
+ runDeepAnalysis,
223
+ refreshVolumes,
224
+ aeoContentChanged,
225
+ };
226
+ }