sanity-plugin-seo-copilot 0.2.15 → 0.2.17

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 (43) hide show
  1. package/README.md +63 -50
  2. package/dist/index.d.mts +1 -0
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.js +898 -809
  5. package/dist/index.mjs +822 -733
  6. package/package.json +5 -7
  7. package/dist/index.js.map +0 -1
  8. package/dist/index.mjs.map +0 -1
  9. package/sanity.json +0 -3
  10. package/src/components/ChatPanel.tsx +0 -311
  11. package/src/components/ConfigContext.tsx +0 -22
  12. package/src/components/FeedbackButton.tsx +0 -218
  13. package/src/components/KeywordBadge.tsx +0 -50
  14. package/src/components/KeywordPanel.tsx +0 -1234
  15. package/src/components/OnboardingPopup.tsx +0 -108
  16. package/src/components/PlacementIndicators.tsx +0 -80
  17. package/src/components/ReportProblemButton.tsx +0 -212
  18. package/src/components/SEOCopilotPanel.tsx +0 -1287
  19. package/src/components/ScoreDonut.tsx +0 -158
  20. package/src/components/SeedKeywordInput.tsx +0 -128
  21. package/src/components/ShimmerLoader.tsx +0 -123
  22. package/src/components/TabBar.tsx +0 -373
  23. package/src/components/styles.ts +0 -158
  24. package/src/components/tabs/AEOTab.tsx +0 -585
  25. package/src/components/tabs/LinkingTab.tsx +0 -446
  26. package/src/components/tabs/MetaTab.tsx +0 -431
  27. package/src/components/tabs/SummaryTab.tsx +0 -405
  28. package/src/components/tabs/TechnicalTab.tsx +0 -933
  29. package/src/hooks/useDocumentContent.ts +0 -48
  30. package/src/hooks/useKeywordAnalysis.ts +0 -292
  31. package/src/hooks/useSEOChat.ts +0 -254
  32. package/src/index.ts +0 -18
  33. package/src/inspector.ts +0 -58
  34. package/src/lib/api.ts +0 -262
  35. package/src/lib/apiKey.ts +0 -30
  36. package/src/lib/documentExtract.ts +0 -422
  37. package/src/lib/geoAnalysis.ts +0 -122
  38. package/src/lib/persistence.ts +0 -69
  39. package/src/lib/scoring.ts +0 -197
  40. package/src/lib/summary.ts +0 -645
  41. package/src/lib/types.ts +0 -212
  42. package/src/lib/utils.ts +0 -35
  43. package/v2-incompatible.js +0 -10
@@ -1,48 +0,0 @@
1
- import { useState, useEffect, useRef } from "react";
2
- import { useDocumentPane } from "sanity/structure";
3
- import type { DocumentFields } from "../lib/types";
4
- import { extractText, buildDocumentFields } from "../lib/documentExtract";
5
-
6
- export function useDocumentContent(): { text: string; isLoading: boolean; documentFields: DocumentFields; documentId: string | undefined; documentType: string | undefined } {
7
- const { value, ready } = useDocumentPane();
8
- const documentId = (value?._id as string | undefined) || undefined;
9
- const documentType = (value?._type as string | undefined) || undefined;
10
- const title = value?.title as string | undefined;
11
- const body = value?.body;
12
- const [debouncedText, setDebouncedText] = useState("");
13
- const [isLoading, setIsLoading] = useState(!ready);
14
- const [documentFields, setDocumentFields] = useState<DocumentFields>({});
15
- const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
16
- const prevDocIdRef = useRef<string | undefined>(documentId);
17
-
18
- // Reset loading state on doc switch so downstream tabs can show their own loading UI
19
- // instead of flashing "Missing" cards based on the previous doc's data.
20
- useEffect(() => {
21
- if (prevDocIdRef.current !== documentId) {
22
- prevDocIdRef.current = documentId;
23
- setIsLoading(true);
24
- }
25
- }, [documentId]);
26
-
27
- useEffect(() => {
28
- const bodyText = extractText(body);
29
- const fullText = [title, bodyText].filter(Boolean).join("\n\n");
30
- const fields = buildDocumentFields(value as Record<string, unknown> | undefined);
31
-
32
- // documentFields are cheap and shown immediately so the Technical tab doesn't flash
33
- // "Missing" cards while the text debounce is pending. Only debounce text since that
34
- // drives the expensive AI analysis calls.
35
- setDocumentFields(fields);
36
-
37
- if (timerRef.current) clearTimeout(timerRef.current);
38
-
39
- timerRef.current = setTimeout(() => {
40
- setDebouncedText(fullText);
41
- setIsLoading(false);
42
- }, 2000);
43
-
44
- return () => { if (timerRef.current) clearTimeout(timerRef.current); };
45
- }, [title, body, value]);
46
-
47
- return { text: debouncedText, isLoading, documentFields, documentId, documentType };
48
- }
@@ -1,292 +0,0 @@
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
- focusSecondary?: string
51
- ) {
52
- const cacheKey = documentId ? `seo-copilot-cache-${documentId}` : "seo-copilot-cache-v2";
53
- const loadCached = useCallback((): { analysis: SEOAnalysis | null; deepAnalysis: DeepAnalysis | null; seeds: string[] } => {
54
- try {
55
- if (typeof window !== "undefined" && localStorage.getItem("seo-copilot-cache")) {
56
- localStorage.removeItem("seo-copilot-cache");
57
- }
58
- const raw = typeof window !== "undefined" ? localStorage.getItem(cacheKey) : null;
59
- if (raw) return JSON.parse(raw);
60
- } catch { /* ignore */ }
61
- return { analysis: null, deepAnalysis: null, seeds: [] };
62
- }, [cacheKey]);
63
- const cached = useRef(loadCached());
64
-
65
- const [analysis, setAnalysisRaw] = useState<SEOAnalysis | null>(cached.current.analysis);
66
- const [isLoading, setIsLoading] = useState(false);
67
- const [isVolumesLoading, setIsVolumesLoading] = useState(false);
68
- const [error, setError] = useState<string | null>(null);
69
-
70
- const [deepAnalysis, setDeepAnalysisRaw] = useState<DeepAnalysis | null>(cached.current.deepAnalysis);
71
- const [isDeepLoading, setIsDeepLoading] = useState(false);
72
- const [aeoTextSnapshot, setAeoTextSnapshot] = useState<string>("");
73
- const [aeoContentChanged, setAeoContentChanged] = useState(false);
74
-
75
- // Reload cached state when documentId (and therefore cacheKey) changes.
76
- // Skip the first invocation since useState above already initialized correctly.
77
- const cacheInitializedRef = useRef(false);
78
- useEffect(() => {
79
- if (!cacheInitializedRef.current) {
80
- cacheInitializedRef.current = true;
81
- return;
82
- }
83
- docVersionRef.current += 1;
84
- volumeAbortRef.current?.abort();
85
- volumeAbortRef.current = null;
86
- deepAbortRef.current?.abort();
87
- deepAbortRef.current = null;
88
- const fresh = loadCached();
89
- cached.current = fresh;
90
- setAnalysisRaw(fresh.analysis);
91
- setDeepAnalysisRaw(fresh.deepAnalysis);
92
- setError(null);
93
- setIsLoading(false);
94
- setIsVolumesLoading(false);
95
- setIsDeepLoading(false);
96
- setAeoTextSnapshot("");
97
- setAeoContentChanged(false);
98
- }, [cacheKey, loadCached]);
99
-
100
- // Persistent volume cache - survives analysis re-runs
101
- const volumeMapRef = useRef(new Map<string, { volume: number; cpc: number; competition: number }>());
102
-
103
- const setAnalysis = useCallback((val: SEOAnalysis | null) => {
104
- // Always re-apply cached volumes to any new analysis
105
- const withVolumes = val ? mergeVolumes(val, volumeMapRef.current) : null;
106
- setAnalysisRaw(withVolumes);
107
- try {
108
- const prev = loadCached();
109
- localStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: withVolumes }));
110
- } catch { /* ignore */ }
111
- }, [cacheKey, loadCached]);
112
- const setDeepAnalysis = useCallback((val: DeepAnalysis | null) => {
113
- setDeepAnalysisRaw(val);
114
- try {
115
- const prev = loadCached();
116
- localStorage.setItem(cacheKey, JSON.stringify({ ...prev, deepAnalysis: val }));
117
- } catch { /* ignore */ }
118
- }, [cacheKey, loadCached]);
119
-
120
- const effectiveSeeds = seedKeywords;
121
-
122
- useEffect(() => {
123
- if (deepAnalysis && aeoTextSnapshot && text !== aeoTextSnapshot) {
124
- setAeoContentChanged(true);
125
- }
126
- }, [text, deepAnalysis, aeoTextSnapshot]);
127
-
128
- const lastAnalysisRef = useRef<SEOAnalysis | null>(null);
129
- // Bumped on every document switch; the async resolvers below bail if their
130
- // captured version is stale, so a slow deep-analysis or volume lookup from a
131
- // previous document can't write its result onto the document the editor
132
- // switched to (the regular analysis effect already guards this via `cancelled`).
133
- const docVersionRef = useRef(0);
134
- // AbortController for the in-flight volume lookup. Cancelled on doc switch and
135
- // before each new lookup so only one lookup is ever outstanding at a time.
136
- const volumeAbortRef = useRef<AbortController | null>(null);
137
- const deepAbortRef = useRef<AbortController | null>(null);
138
-
139
- // Abort any in-flight volume lookup or deep analysis when the hook unmounts so a late
140
- // resolver can't run after teardown and we don't waste backend (Claude/SEMrush) spend.
141
- useEffect(() => () => {
142
- volumeAbortRef.current?.abort();
143
- deepAbortRef.current?.abort();
144
- }, []);
145
-
146
- const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, terms?: string[]) => {
147
- setIsVolumesLoading(true);
148
- const myVersion = docVersionRef.current;
149
-
150
- const lookupTerms = terms || (() => {
151
- const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
152
- return [
153
- ...new Set([
154
- ...candidateTerms,
155
- analysisResult.primaryKeyword.term,
156
- ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
157
- ...analysisResult.missingKeywords.map((kw) => kw.term),
158
- ]),
159
- ];
160
- })();
161
-
162
- if (lookupTerms.length === 0) {
163
- setIsVolumesLoading(false);
164
- return;
165
- }
166
-
167
- // Cancel any previous in-flight lookup before starting a new one
168
- volumeAbortRef.current?.abort();
169
- const controller = new AbortController();
170
- volumeAbortRef.current = controller;
171
-
172
- lookupKeywords(apiUrl, lookupTerms, controller.signal)
173
- .then(({ results }) => {
174
- if (docVersionRef.current !== myVersion) return; // document switched - drop stale volumes
175
- // Add new results to persistent cache
176
- results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
177
- // Re-apply all cached volumes to current analysis
178
- const current = lastAnalysisRef.current || analysisResult;
179
- const merged = mergeVolumes(current, volumeMapRef.current);
180
- lastAnalysisRef.current = merged;
181
- setAnalysisRaw(merged);
182
- try {
183
- const prev = loadCached();
184
- localStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: merged }));
185
- } catch { /* ignore */ }
186
- setIsVolumesLoading(false);
187
- })
188
- .catch((err) => {
189
- if (err instanceof Error && err.name === "AbortError") return;
190
- if (docVersionRef.current !== myVersion) return;
191
- setIsVolumesLoading(false);
192
- });
193
- }, [apiUrl, cacheKey]);
194
-
195
- const doVolumeLookupRef = useRef(doVolumeLookup);
196
- useEffect(() => { doVolumeLookupRef.current = doVolumeLookup; }, [doVolumeLookup]);
197
-
198
- useEffect(() => {
199
- if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
200
- setAnalysis(null);
201
- return;
202
- }
203
-
204
- let cancelled = false;
205
- const controller = new AbortController();
206
- setIsLoading(true);
207
- setError(null);
208
-
209
- fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary, focusSecondary, controller.signal)
210
- .then((result) => {
211
- if (cancelled) return;
212
- const analysisResult = result as SEOAnalysis;
213
- lastAnalysisRef.current = analysisResult;
214
- setAnalysis(analysisResult); // volumes auto-applied via setAnalysis wrapper
215
- setIsLoading(false);
216
-
217
- // Look up volumes for any NEW terms not already in the cache
218
- const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
219
- const allTerms = [
220
- ...new Set([
221
- ...candidateTerms,
222
- analysisResult.primaryKeyword.term,
223
- ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
224
- ...analysisResult.missingKeywords.map((kw) => kw.term),
225
- ]),
226
- ];
227
- const uncachedTerms = allTerms.filter((t) => !volumeMapRef.current.has(t.toLowerCase()));
228
-
229
- if (uncachedTerms.length > 0) {
230
- doVolumeLookupRef.current(analysisResult, uncachedTerms);
231
- }
232
- })
233
- .catch((err) => {
234
- if (err instanceof Error && err.name === "AbortError") return;
235
- if (!cancelled) {
236
- setError(err.message);
237
- setIsLoading(false);
238
- }
239
- });
240
-
241
- return () => {
242
- cancelled = true;
243
- controller.abort();
244
- };
245
- // JSON.stringify(documentFields) used instead of documentFields directly to avoid
246
- // re-running when the caller creates a new object reference with identical contents.
247
- // eslint-disable-next-line react-hooks/exhaustive-deps
248
- }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, focusSecondary, JSON.stringify(documentFields)]);
249
-
250
- const refreshVolumes = useCallback(() => {
251
- const current = lastAnalysisRef.current || analysis;
252
- if (!current) return;
253
- doVolumeLookup(current);
254
- }, [analysis, doVolumeLookup]);
255
-
256
- const runDeepAnalysis = useCallback(() => {
257
- if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) return;
258
-
259
- setIsDeepLoading(true);
260
- setError(null);
261
- setAeoContentChanged(false);
262
- setAeoTextSnapshot(text);
263
-
264
- const myVersion = docVersionRef.current;
265
- deepAbortRef.current?.abort(); const deepController = new AbortController(); deepAbortRef.current = deepController;
266
- fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary, focusSecondary, deepController.signal)
267
- .then((result) => {
268
- if (docVersionRef.current !== myVersion) return; // document switched - drop stale result
269
- setDeepAnalysis(result as DeepAnalysis);
270
- setIsDeepLoading(false);
271
- })
272
- .catch((err) => {
273
- // Aborted (doc switch or unmount) is normal teardown, not an error to surface.
274
- if (deepController.signal.aborted || err?.name === "AbortError") return;
275
- if (docVersionRef.current !== myVersion) return;
276
- setError(err.message);
277
- setIsDeepLoading(false);
278
- });
279
- }, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields, focusPrimary, focusSecondary]);
280
-
281
- return {
282
- analysis,
283
- isLoading,
284
- isVolumesLoading,
285
- error,
286
- deepAnalysis,
287
- isDeepLoading,
288
- runDeepAnalysis,
289
- refreshVolumes,
290
- aeoContentChanged,
291
- };
292
- }
@@ -1,254 +0,0 @@
1
- import { useState, useCallback, useEffect, useRef } from "react";
2
- import { useCurrentUser } from "sanity";
3
- import { fetchChatStream, loadChatHistory, saveChatHistory } from "../lib/api";
4
- import type { ChatMessage } from "../lib/types";
5
-
6
- interface KeywordPanelData {
7
- primaryKeyword?: { term: string; volume: number | null };
8
- supportingKeywords?: { term: string; volume: number | null }[];
9
- secondaryKeywords?: { term: string; volume: number | null }[];
10
- missingKeywords?: { term: string; volume: number | null }[];
11
- contentScore?: number;
12
- aeoData?: {
13
- questionHeadings: { suggestedHeading: string; rationale: string }[];
14
- };
15
- }
16
-
17
- function getLocalUserId(): string {
18
- if (typeof window === 'undefined') return 'anonymous';
19
- const key = "seo-copilot-user-id";
20
- try {
21
- let id = localStorage.getItem(key);
22
- if (!id) {
23
- id = `user-${Math.random().toString(36).slice(2)}-${Date.now()}`;
24
- localStorage.setItem(key, id);
25
- }
26
- return id;
27
- } catch {
28
- return "anonymous";
29
- }
30
- }
31
-
32
- export function useSEOChat(
33
- apiUrl: string,
34
- documentText: string,
35
- publication?: string,
36
- keywordPanelData?: KeywordPanelData,
37
- documentId?: string
38
- ) {
39
- // Chat messages cached in localStorage for persistence across close/reopen.
40
- // The cache key changes when documentId changes, so we must reload state on doc change.
41
- const chatCacheKey = documentId ? `seo-copilot-chat-${documentId}` : "seo-copilot-chat-default";
42
- const loadCachedMessages = useCallback((): ChatMessage[] => {
43
- try {
44
- const cached = typeof window !== "undefined" ? localStorage.getItem(chatCacheKey) : null;
45
- return cached ? JSON.parse(cached) : [];
46
- } catch { return []; }
47
- }, [chatCacheKey]);
48
-
49
- const [messages, setMessagesRaw] = useState<ChatMessage[]>(loadCachedMessages);
50
- // Ref always mirrors messages state so sendMessage doesn't need messages in its
51
- // dependency array (avoiding a re-creation on every streamed token).
52
- const messagesRef = useRef<ChatMessage[]>([]);
53
-
54
- // Simplified wrapper - localStorage persistence moved to a debounced useEffect
55
- // below so it doesn't fire on every individual token during streaming.
56
- const setMessages = useCallback((msgs: ChatMessage[] | ((prev: ChatMessage[]) => ChatMessage[])) => {
57
- setMessagesRaw(msgs);
58
- }, []);
59
-
60
- const [isStreaming, setIsStreaming] = useState(false);
61
- const [historyLoaded, setHistoryLoaded] = useState(false);
62
- // Use Sanity's logged-in user ID if available, fall back to localStorage ID
63
- const sanityUser = useCurrentUser();
64
- const userId = useRef(sanityUser?.id || getLocalUserId());
65
- // Update ref if Sanity user loads after initial render
66
- useEffect(() => {
67
- if (sanityUser?.id && userId.current !== sanityUser.id) {
68
- userId.current = sanityUser.id;
69
- }
70
- }, [sanityUser?.id]);
71
-
72
- // Keep messagesRef in sync with state so sendMessage can read current messages
73
- // without capturing a stale closure value.
74
- useEffect(() => {
75
- messagesRef.current = messages;
76
- }, [messages]);
77
-
78
- // Persist chat history to localStorage, debounced so we don't write on every
79
- // individual token during streaming (only once the stream settles).
80
- useEffect(() => {
81
- const timer = setTimeout(() => {
82
- try { localStorage.setItem(chatCacheKey, JSON.stringify(messages)); } catch {}
83
- }, 500);
84
- return () => clearTimeout(timer);
85
- }, [messages, chatCacheKey]);
86
-
87
- // AbortController for the in-flight chat stream. Aborted on doc switch and unmount.
88
- const streamAbortRef = useRef<AbortController | null>(null);
89
-
90
- // Abort any in-flight stream on unmount to prevent state updates on a dead component.
91
- useEffect(() => {
92
- return () => {
93
- streamAbortRef.current?.abort();
94
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
95
- };
96
- }, []);
97
-
98
- const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
99
-
100
- // Per-document operation version to invalidate stale in-flight loads
101
- const opVersionRef = useRef(0);
102
-
103
- // Reload state when document changes (Sanity inspector may reuse instance)
104
- // Use a ref to skip the very first effect run since useState already initialized correctly.
105
- const didInitRef = useRef(false);
106
- useEffect(() => {
107
- if (!didInitRef.current) {
108
- didInitRef.current = true;
109
- return;
110
- }
111
- opVersionRef.current += 1;
112
- streamAbortRef.current?.abort();
113
- streamAbortRef.current = null;
114
- setMessagesRaw(loadCachedMessages());
115
- setIsStreaming(false);
116
- setHistoryLoaded(false);
117
- if (saveTimerRef.current) {
118
- clearTimeout(saveTimerRef.current);
119
- saveTimerRef.current = null;
120
- }
121
- }, [documentId, loadCachedMessages]);
122
-
123
- // Load from server-side chat history on mount (and on doc change, since historyLoaded is reset above)
124
- useEffect(() => {
125
- if (!documentId || historyLoaded) return;
126
- const myVersion = opVersionRef.current;
127
- let cancelled = false;
128
- loadChatHistory(apiUrl, userId.current, documentId).then((loaded) => {
129
- if (cancelled || opVersionRef.current !== myVersion) return;
130
- if (loaded.length > 0) {
131
- // Functional update to avoid clobbering messages the user typed during the load
132
- setMessages((current) => (current.length === 0 ? loaded : current));
133
- }
134
- setHistoryLoaded(true);
135
- });
136
- return () => { cancelled = true; };
137
- // eslint-disable-next-line react-hooks/exhaustive-deps
138
- }, [apiUrl, documentId, historyLoaded]);
139
-
140
- // Debounced save to server (best-effort, localStorage is the primary)
141
- const scheduleSave = useCallback((msgs: ChatMessage[]) => {
142
- if (!documentId) return;
143
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
144
- saveTimerRef.current = setTimeout(() => {
145
- saveChatHistory(apiUrl, userId.current, documentId, msgs, publication);
146
- }, 800);
147
- }, [apiUrl, documentId, publication]);
148
-
149
- const sendMessage = useCallback(
150
- async (text: string) => {
151
- const myVersion = opVersionRef.current;
152
- const userMessage: ChatMessage = { role: "user", content: text };
153
- // Read from ref so messages is not needed in the dep array - prevents
154
- // sendMessage from being recreated on every streamed token.
155
- const updatedMessages = [...messagesRef.current, userMessage];
156
- setMessages(updatedMessages);
157
- setIsStreaming(true);
158
-
159
- const controller = new AbortController();
160
- streamAbortRef.current = controller;
161
-
162
- try {
163
- const stream = await fetchChatStream(
164
- apiUrl,
165
- updatedMessages,
166
- documentText,
167
- publication,
168
- keywordPanelData,
169
- controller.signal
170
- );
171
-
172
- if (!stream) {
173
- setIsStreaming(false);
174
- return;
175
- }
176
-
177
- const reader = stream.getReader();
178
- const decoder = new TextDecoder();
179
- let assistantContent = "";
180
-
181
- // If the editor switched documents while the request was in flight, stop -
182
- // don't inject this stream into the new document's chat.
183
- if (opVersionRef.current !== myVersion) { try { await reader.cancel(); } catch {} setIsStreaming(false); return; }
184
-
185
- // Add empty assistant message that we'll update
186
- setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
187
-
188
- while (true) {
189
- const { done, value } = await reader.read();
190
- if (done) break;
191
- if (opVersionRef.current !== myVersion) { try { await reader.cancel(); } catch {} break; } // doc switched mid-stream
192
-
193
- const chunk = decoder.decode(value, { stream: true });
194
- const lines = chunk.split("\n");
195
-
196
- for (const line of lines) {
197
- if (line.startsWith("data: ")) {
198
- const data = line.slice(6);
199
- if (data === "[DONE]") continue;
200
-
201
- try {
202
- const parsed = JSON.parse(data);
203
- if (parsed.text) {
204
- assistantContent += parsed.text;
205
- setMessages((prev) => {
206
- const updated = [...prev];
207
- updated[updated.length - 1] = {
208
- role: "assistant",
209
- content: assistantContent,
210
- };
211
- return updated;
212
- });
213
- }
214
- } catch {
215
- // Skip malformed JSON chunks
216
- }
217
- }
218
- }
219
- }
220
-
221
- // Save history after stream completes (skip if the doc was switched away).
222
- if (opVersionRef.current === myVersion) {
223
- const finalMessages: ChatMessage[] = [
224
- ...updatedMessages,
225
- { role: "assistant", content: assistantContent },
226
- ];
227
- scheduleSave(finalMessages);
228
- }
229
- } catch (err) {
230
- // Abort is silent - happens on doc switch or unmount, not an error for the editor.
231
- if (err instanceof Error && err.name === "AbortError") { setIsStreaming(false); return; }
232
- if (opVersionRef.current !== myVersion) { setIsStreaming(false); return; }
233
- const errorMsg = err instanceof Error ? err.message : "Chat failed";
234
- setMessages((prev) => [
235
- ...prev,
236
- { role: "assistant", content: `Error: ${errorMsg}` },
237
- ]);
238
- }
239
-
240
- if (opVersionRef.current === myVersion) setIsStreaming(false);
241
- },
242
- [apiUrl, documentText, publication, keywordPanelData, scheduleSave]
243
- );
244
-
245
- const clearChat = useCallback(() => {
246
- setMessages([]);
247
- // Save empty history to backend
248
- if (documentId) {
249
- saveChatHistory(apiUrl, userId.current, documentId, [], publication);
250
- }
251
- }, [apiUrl, documentId, publication]);
252
-
253
- return { messages, isStreaming, sendMessage, clearChat };
254
- }
package/src/index.ts DELETED
@@ -1,18 +0,0 @@
1
- import { definePlugin } from "sanity";
2
- import { seoCopilotInspector } from "./inspector";
3
-
4
- export interface SEOCopilotConfig {
5
- apiUrl: string;
6
- publication?: string;
7
- }
8
-
9
- export const seoCopilot = definePlugin<SEOCopilotConfig>((config) => {
10
- return {
11
- name: "seo-copilot",
12
- document: {
13
- inspectors: (prev) => {
14
- return [...prev, seoCopilotInspector(config)];
15
- },
16
- },
17
- };
18
- });
package/src/inspector.ts DELETED
@@ -1,58 +0,0 @@
1
- import { type DocumentInspector, type DocumentInspectorProps } from "sanity";
2
- import { createElement } from "react";
3
- import type { SEOCopilotConfig } from "./index";
4
- import SEOCopilotPanel from "./components/SEOCopilotPanel";
5
-
6
- function SEOIcon() {
7
- return createElement("svg", { viewBox: "0 0 25 25", width: "1em", height: "1em", fill: "none" },
8
- createElement("circle", { cx: "12.5", cy: "12.5", r: "11.5", fill: "#E6C01B" }),
9
- createElement("text", {
10
- x: "12.5", y: "7.5",
11
- textAnchor: "middle",
12
- dominantBaseline: "central",
13
- fill: "white",
14
- fontSize: "7",
15
- fontWeight: "900",
16
- fontFamily: "Arial Black, Impact, sans-serif",
17
- }, "S"),
18
- createElement("text", {
19
- x: "12.5", y: "12.8",
20
- textAnchor: "middle",
21
- dominantBaseline: "central",
22
- fill: "white",
23
- fontSize: "7",
24
- fontWeight: "900",
25
- fontFamily: "Arial Black, Impact, sans-serif",
26
- }, "E"),
27
- createElement("text", {
28
- x: "12.5", y: "18",
29
- textAnchor: "middle",
30
- dominantBaseline: "central",
31
- fill: "white",
32
- fontSize: "7",
33
- fontWeight: "900",
34
- fontFamily: "Arial Black, Impact, sans-serif",
35
- }, "O")
36
- );
37
- }
38
-
39
- export function seoCopilotInspector(config: SEOCopilotConfig): DocumentInspector {
40
- return {
41
- name: "seo-copilot",
42
- useMenuItem: () => ({
43
- title: "SEO Copilot",
44
- icon: SEOIcon,
45
- // Toolbar placement test: showAsAction renders this as a button in the document
46
- // toolbar (where editors expect it). The original crash came from passing
47
- // showAsAction WITHOUT a tone; pairing it with a valid string tone is how Sanity's
48
- // own built-in inspectors (Validation, etc.) keep their toolbar button safely.
49
- // If this still crashes in Nick's studio, remove these two lines to fall back to
50
- // the "..." overflow menu (the known-safe placement).
51
- showAsAction: true,
52
- tone: "default",
53
- }),
54
- component: function SEOCopilotInspector(props: DocumentInspectorProps) {
55
- return createElement(SEOCopilotPanel, { ...props, config });
56
- },
57
- };
58
- }