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,169 +1,178 @@
1
- import { useState, useCallback, useEffect, useRef } from "react";
2
- import { fetchChatStream, loadChatHistory, saveChatHistory } from "../lib/api";
3
- import type { ChatMessage } from "../lib/types";
4
-
5
- interface KeywordPanelData {
6
- primaryKeyword?: { term: string; volume: number | null };
7
- supportingKeywords?: { term: string; volume: number | null }[];
8
- secondaryKeywords?: { term: string; volume: number | null }[];
9
- missingKeywords?: { term: string; volume: number | null }[];
10
- contentScore?: number;
11
- aeoData?: {
12
- questionHeadings: { suggestedHeading: string; rationale: string }[];
13
- faqSuggestions: { question: string; answer: string }[];
14
- };
15
- }
16
-
17
- function getUserId(): string {
18
- const key = "seo-copilot-user-id";
19
- try {
20
- let id = localStorage.getItem(key);
21
- if (!id) {
22
- id = `user-${Math.random().toString(36).slice(2)}-${Date.now()}`;
23
- localStorage.setItem(key, id);
24
- }
25
- return id;
26
- } catch {
27
- return "anonymous";
28
- }
29
- }
30
-
31
- export function useSEOChat(
32
- apiUrl: string,
33
- documentText: string,
34
- publication?: string,
35
- keywordPanelData?: KeywordPanelData,
36
- documentId?: string
37
- ) {
38
- // Chat messages cached in sessionStorage for persistence across close/reopen
39
- const chatCacheKey = documentId ? `seo-copilot-chat-${documentId}` : "seo-copilot-chat-default";
40
- const [messages, setMessagesRaw] = useState<ChatMessage[]>(() => {
41
- try {
42
- const cached = typeof window !== "undefined" ? sessionStorage.getItem(chatCacheKey) : null;
43
- return cached ? JSON.parse(cached) : [];
44
- } catch { return []; }
45
- });
46
- const setMessages = useCallback((msgs: ChatMessage[] | ((prev: ChatMessage[]) => ChatMessage[])) => {
47
- setMessagesRaw((prev) => {
48
- const next = typeof msgs === "function" ? msgs(prev) : msgs;
49
- try { sessionStorage.setItem(chatCacheKey, JSON.stringify(next)); } catch {}
50
- return next;
51
- });
52
- }, [chatCacheKey]);
53
-
54
- const [isStreaming, setIsStreaming] = useState(false);
55
- const [historyLoaded, setHistoryLoaded] = useState(false);
56
- const userId = useRef(getUserId());
57
- const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
58
-
59
- // Also try to load from server-side chat history on mount
60
- useEffect(() => {
61
- if (!documentId || historyLoaded) return;
62
- let cancelled = false;
63
- loadChatHistory(apiUrl, userId.current, documentId).then((loaded) => {
64
- if (!cancelled && loaded.length > 0 && messages.length === 0) {
65
- setMessages(loaded);
66
- }
67
- if (!cancelled) setHistoryLoaded(true);
68
- });
69
- return () => { cancelled = true; };
70
- }, [apiUrl, documentId, historyLoaded]);
71
-
72
- // Debounced save to server (best-effort, sessionStorage is the primary)
73
- const scheduleSave = useCallback((msgs: ChatMessage[]) => {
74
- if (!documentId) return;
75
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
76
- saveTimerRef.current = setTimeout(() => {
77
- saveChatHistory(apiUrl, userId.current, documentId, msgs, publication);
78
- }, 800);
79
- }, [apiUrl, documentId, publication]);
80
-
81
- const sendMessage = useCallback(
82
- async (text: string) => {
83
- const userMessage: ChatMessage = { role: "user", content: text };
84
- const updatedMessages = [...messages, userMessage];
85
- setMessages(updatedMessages);
86
- setIsStreaming(true);
87
-
88
- try {
89
- const stream = await fetchChatStream(
90
- apiUrl,
91
- updatedMessages,
92
- documentText,
93
- publication,
94
- keywordPanelData
95
- );
96
-
97
- if (!stream) {
98
- setIsStreaming(false);
99
- return;
100
- }
101
-
102
- const reader = stream.getReader();
103
- const decoder = new TextDecoder();
104
- let assistantContent = "";
105
-
106
- // Add empty assistant message that we'll update
107
- setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
108
-
109
- while (true) {
110
- const { done, value } = await reader.read();
111
- if (done) break;
112
-
113
- const chunk = decoder.decode(value, { stream: true });
114
- const lines = chunk.split("\n");
115
-
116
- for (const line of lines) {
117
- if (line.startsWith("data: ")) {
118
- const data = line.slice(6);
119
- if (data === "[DONE]") continue;
120
-
121
- try {
122
- const parsed = JSON.parse(data);
123
- if (parsed.text) {
124
- assistantContent += parsed.text;
125
- setMessages((prev) => {
126
- const updated = [...prev];
127
- updated[updated.length - 1] = {
128
- role: "assistant",
129
- content: assistantContent,
130
- };
131
- return updated;
132
- });
133
- }
134
- } catch {
135
- // Skip malformed JSON chunks
136
- }
137
- }
138
- }
139
- }
140
-
141
- // Save history after stream completes
142
- const finalMessages: ChatMessage[] = [
143
- ...updatedMessages,
144
- { role: "assistant", content: assistantContent },
145
- ];
146
- scheduleSave(finalMessages);
147
- } catch (err) {
148
- const errorMsg = err instanceof Error ? err.message : "Chat failed";
149
- setMessages((prev) => [
150
- ...prev,
151
- { role: "assistant", content: `Error: ${errorMsg}` },
152
- ]);
153
- }
154
-
155
- setIsStreaming(false);
156
- },
157
- [messages, apiUrl, documentText, publication, keywordPanelData, scheduleSave]
158
- );
159
-
160
- const clearChat = useCallback(() => {
161
- setMessages([]);
162
- // Save empty history to backend
163
- if (documentId) {
164
- saveChatHistory(apiUrl, userId.current, documentId, [], publication);
165
- }
166
- }, [apiUrl, documentId, publication]);
167
-
168
- return { messages, isStreaming, sendMessage, clearChat };
169
- }
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
+ faqSuggestions: { question: string; answer: string }[];
15
+ };
16
+ }
17
+
18
+ function getLocalUserId(): string {
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 sessionStorage for persistence across close/reopen
40
+ const chatCacheKey = documentId ? `seo-copilot-chat-${documentId}` : "seo-copilot-chat-default";
41
+ const [messages, setMessagesRaw] = useState<ChatMessage[]>(() => {
42
+ try {
43
+ const cached = typeof window !== "undefined" ? sessionStorage.getItem(chatCacheKey) : null;
44
+ return cached ? JSON.parse(cached) : [];
45
+ } catch { return []; }
46
+ });
47
+ const setMessages = useCallback((msgs: ChatMessage[] | ((prev: ChatMessage[]) => ChatMessage[])) => {
48
+ setMessagesRaw((prev) => {
49
+ const next = typeof msgs === "function" ? msgs(prev) : msgs;
50
+ try { sessionStorage.setItem(chatCacheKey, JSON.stringify(next)); } catch {}
51
+ return next;
52
+ });
53
+ }, [chatCacheKey]);
54
+
55
+ const [isStreaming, setIsStreaming] = useState(false);
56
+ const [historyLoaded, setHistoryLoaded] = useState(false);
57
+ // Use Sanity's logged-in user ID if available, fall back to localStorage ID
58
+ const sanityUser = useCurrentUser();
59
+ const userId = useRef(sanityUser?.id || getLocalUserId());
60
+ // Update ref if Sanity user loads after initial render
61
+ useEffect(() => {
62
+ if (sanityUser?.id && userId.current !== sanityUser.id) {
63
+ userId.current = sanityUser.id;
64
+ }
65
+ }, [sanityUser?.id]);
66
+ const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
67
+
68
+ // Also try to load from server-side chat history on mount
69
+ useEffect(() => {
70
+ if (!documentId || historyLoaded) return;
71
+ let cancelled = false;
72
+ loadChatHistory(apiUrl, userId.current, documentId).then((loaded) => {
73
+ if (!cancelled && loaded.length > 0 && messages.length === 0) {
74
+ setMessages(loaded);
75
+ }
76
+ if (!cancelled) setHistoryLoaded(true);
77
+ });
78
+ return () => { cancelled = true; };
79
+ }, [apiUrl, documentId, historyLoaded]);
80
+
81
+ // Debounced save to server (best-effort, sessionStorage is the primary)
82
+ const scheduleSave = useCallback((msgs: ChatMessage[]) => {
83
+ if (!documentId) return;
84
+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
85
+ saveTimerRef.current = setTimeout(() => {
86
+ saveChatHistory(apiUrl, userId.current, documentId, msgs, publication);
87
+ }, 800);
88
+ }, [apiUrl, documentId, publication]);
89
+
90
+ const sendMessage = useCallback(
91
+ async (text: string) => {
92
+ const userMessage: ChatMessage = { role: "user", content: text };
93
+ const updatedMessages = [...messages, userMessage];
94
+ setMessages(updatedMessages);
95
+ setIsStreaming(true);
96
+
97
+ try {
98
+ const stream = await fetchChatStream(
99
+ apiUrl,
100
+ updatedMessages,
101
+ documentText,
102
+ publication,
103
+ keywordPanelData
104
+ );
105
+
106
+ if (!stream) {
107
+ setIsStreaming(false);
108
+ return;
109
+ }
110
+
111
+ const reader = stream.getReader();
112
+ const decoder = new TextDecoder();
113
+ let assistantContent = "";
114
+
115
+ // Add empty assistant message that we'll update
116
+ setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
117
+
118
+ while (true) {
119
+ const { done, value } = await reader.read();
120
+ if (done) break;
121
+
122
+ const chunk = decoder.decode(value, { stream: true });
123
+ const lines = chunk.split("\n");
124
+
125
+ for (const line of lines) {
126
+ if (line.startsWith("data: ")) {
127
+ const data = line.slice(6);
128
+ if (data === "[DONE]") continue;
129
+
130
+ try {
131
+ const parsed = JSON.parse(data);
132
+ if (parsed.text) {
133
+ assistantContent += parsed.text;
134
+ setMessages((prev) => {
135
+ const updated = [...prev];
136
+ updated[updated.length - 1] = {
137
+ role: "assistant",
138
+ content: assistantContent,
139
+ };
140
+ return updated;
141
+ });
142
+ }
143
+ } catch {
144
+ // Skip malformed JSON chunks
145
+ }
146
+ }
147
+ }
148
+ }
149
+
150
+ // Save history after stream completes
151
+ const finalMessages: ChatMessage[] = [
152
+ ...updatedMessages,
153
+ { role: "assistant", content: assistantContent },
154
+ ];
155
+ scheduleSave(finalMessages);
156
+ } catch (err) {
157
+ const errorMsg = err instanceof Error ? err.message : "Chat failed";
158
+ setMessages((prev) => [
159
+ ...prev,
160
+ { role: "assistant", content: `Error: ${errorMsg}` },
161
+ ]);
162
+ }
163
+
164
+ setIsStreaming(false);
165
+ },
166
+ [messages, apiUrl, documentText, publication, keywordPanelData, scheduleSave]
167
+ );
168
+
169
+ const clearChat = useCallback(() => {
170
+ setMessages([]);
171
+ // Save empty history to backend
172
+ if (documentId) {
173
+ saveChatHistory(apiUrl, userId.current, documentId, [], publication);
174
+ }
175
+ }, [apiUrl, documentId, publication]);
176
+
177
+ return { messages, isStreaming, sendMessage, clearChat };
178
+ }
@@ -1,10 +1,10 @@
1
- const {showIncompatiblePluginDialog} = require('@sanity/incompatible-plugin')
2
- const {name, version} = require('./package.json')
3
-
4
- module.exports = showIncompatiblePluginDialog({
5
- name: name,
6
- versions: {
7
- v3: version,
8
- v2: undefined,
9
- },
10
- })
1
+ const {showIncompatiblePluginDialog} = require('@sanity/incompatible-plugin')
2
+ const {name, version} = require('./package.json')
3
+
4
+ module.exports = showIncompatiblePluginDialog({
5
+ name: name,
6
+ versions: {
7
+ v3: version,
8
+ v2: undefined,
9
+ },
10
+ })