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,1234 +0,0 @@
1
- import { useState, useEffect, useRef, useCallback } from "react";
2
- import { useConfig } from "./ConfigContext";
3
- import { PlacementIndicators } from "./PlacementIndicators";
4
- import { SeedKeywordInput } from "./SeedKeywordInput";
5
- import { FeedbackButton } from "./FeedbackButton";
6
- import { LoadingBars } from "./SEOCopilotPanel";
7
- import { MJH_GOLD, MJH_BLUE } from "./styles";
8
- import { usePersistentState, loadLocal } from "../lib/persistence";
9
- import type { PrimaryKeywordCandidate, DocumentFields } from "../lib/types";
10
- import { jsonHeaders } from "../lib/apiKey";
11
-
12
- function loadLocalArray<T>(key: string): T[] {
13
- return loadLocal<T[]>(key, []);
14
- }
15
-
16
- interface KeywordPanelProps {
17
- text: string;
18
- publication?: string;
19
- seedKeywords?: string[];
20
- onSeedsChange?: (seeds: string[]) => void;
21
- onSelectPrimary?: (term: string) => void;
22
- // Optional secondary/supporting target keyword. Audits check the article against
23
- // BOTH the primary and this secondary keyword. "" / undefined = none selected.
24
- secondaryKeyword?: string;
25
- onSelectSecondary?: (term: string) => void;
26
- documentFields?: DocumentFields;
27
- // Used as key for SuggestedKeywordsCard to remount on doc change (resets manualKeywords/extraKeywords/helpData)
28
- documentId?: string;
29
- // Required: keyword analysis state lifted to parent (SEOCopilotInner) to avoid duplicate API calls
30
- externalAnalysis: {
31
- analysis: import("../lib/types").SEOAnalysis | null;
32
- isLoading: boolean;
33
- isVolumesLoading: boolean;
34
- error: string | null;
35
- deepAnalysis: import("../lib/types").DeepAnalysis | null;
36
- isDeepLoading: boolean;
37
- runDeepAnalysis: () => void;
38
- refreshVolumes?: () => void;
39
- aeoContentChanged?: boolean;
40
- };
41
- }
42
-
43
- interface SuggestedKeyword {
44
- term: string;
45
- volume: number;
46
- inContent: boolean;
47
- reason?: string;
48
- placement?: import("../lib/types").KeywordPlacement;
49
- }
50
-
51
- function SectionHeader({ label, iconColor, actionButton }: { label: string; iconColor: string; actionButton?: React.ReactNode }) {
52
- return (
53
- <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 10 }}>
54
- <div style={{ width: 7, height: 7, borderRadius: "50%", background: iconColor, flexShrink: 0 }} />
55
- <span style={{ fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", color: "#4b5563", fontWeight: 600, flex: 1 }}>
56
- {label}
57
- </span>
58
- {actionButton}
59
- </div>
60
- );
61
- }
62
-
63
- const cardStyle = {
64
- borderRadius: 14,
65
- background: "rgba(255,255,255,0.55)",
66
- backdropFilter: "blur(16px) saturate(170%)",
67
- WebkitBackdropFilter: "blur(16px) saturate(170%)",
68
- boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.85), inset 1.5px 2px 1px -1px rgba(255,255,255,1), inset -2px -3px 2px -1px rgba(255,255,255,0.6), 0 2px 6px rgba(0,0,0,0.07), 0 10px 26px rgba(0,0,0,0.08)",
69
- padding: "14px",
70
- };
71
-
72
- interface KeywordHelpSuggestion {
73
- type: "change" | "add";
74
- original?: string;
75
- revised?: string;
76
- sentence?: string;
77
- where?: string;
78
- }
79
-
80
- function abbrevVol(v: number | null | undefined): string {
81
- if (v == null) return "";
82
- if (v === 0) return "N/A";
83
- if (v >= 10000) return Math.round(v / 1000) + "K";
84
- if (v >= 1000) return (v / 1000).toFixed(1) + "K";
85
- return String(v);
86
- }
87
-
88
- function placementCount(p?: import("../lib/types").KeywordPlacement): number {
89
- if (!p) return 0;
90
- return [p.inBody, p.inTitle, p.inMetaDescription, p.inImages, p.inUrl].filter(Boolean).length;
91
- }
92
-
93
- type PlacementKey = "inBody" | "inTitle" | "inMetaDescription" | "inImages" | "inUrl" | "none";
94
-
95
- /** Merge supporting + missing into one list, sorted by placement count then volume desc.
96
- * Note: 0-volume terms are intentionally KEPT - niche clinical long-tail terms often
97
- * have no SEMrush data but are still worth targeting for topical authority. */
98
- function buildSuggestedKeywords(
99
- supporting: { term: string; volume: number | null; inContent: boolean; placement?: import("../lib/types").KeywordPlacement }[],
100
- missing: { term: string; volume: number | null; reason: string; placement?: import("../lib/types").KeywordPlacement }[],
101
- documentText: string,
102
- documentFields?: import("../lib/types").DocumentFields
103
- ): SuggestedKeyword[] {
104
- const merged: SuggestedKeyword[] = [];
105
- const lowerText = documentText.toLowerCase();
106
-
107
- for (const kw of supporting) {
108
- if (kw == null || typeof kw.term !== "string") continue;
109
- const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
110
- const livePlacement = computePlacementClient(kw.term, documentText, documentFields);
111
- merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, placement: livePlacement });
112
- }
113
-
114
- for (const kw of missing) {
115
- if (kw == null || typeof kw.term !== "string") continue;
116
- const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
117
- const livePlacement = computePlacementClient(kw.term, documentText, documentFields);
118
- merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, reason: kw.reason, placement: livePlacement });
119
- }
120
-
121
- // Default sort: most placements first, then volume desc within same placement count
122
- merged.sort((a, b) => {
123
- const pDiff = placementCount(b.placement) - placementCount(a.placement);
124
- if (pDiff !== 0) return pDiff;
125
- return b.volume - a.volume;
126
- });
127
- return merged;
128
- }
129
-
130
- function LightbulbButton({ onClick, isLoading }: { onClick: () => void; isLoading: boolean }) {
131
- const [hovered, setHovered] = useState(false);
132
-
133
- return (
134
- <span
135
- onClick={(e) => { e.stopPropagation(); onClick(); }}
136
- onMouseEnter={() => setHovered(true)}
137
- onMouseLeave={() => setHovered(false)}
138
- style={{
139
- position: "relative",
140
- cursor: isLoading ? "wait" : "pointer",
141
- lineHeight: 1,
142
- opacity: isLoading ? 0.5 : 1,
143
- flexShrink: 0,
144
- display: "inline-flex",
145
- alignItems: "center",
146
- color: hovered ? MJH_GOLD : "#9ca3af",
147
- transition: "color 150ms",
148
- }}
149
- title="Show how to use this keyword"
150
- >
151
- {isLoading ? (
152
- <LoadingBars size="xs" color={MJH_GOLD} />
153
- ) : (
154
- <svg width="13" height="13" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
155
- <path fillRule="evenodd" d="M10 1a6 6 0 00-3.815 10.631C7.001 12.097 7.5 12.93 7.5 13.875V15a2.5 2.5 0 002.5 2.5h0a2.5 2.5 0 002.5-2.5v-1.125c0-.945.498-1.778 1.315-2.244A6 6 0 0010 1zM8.025 13H9.5v-2.077a.75.75 0 011.5 0V13h1.475A4.5 4.5 0 0011.5 9.86V5.75a.75.75 0 00-1.5 0v4.11a4.5 4.5 0 00-1.975 3.14z" clipRule="evenodd" />
156
- </svg>
157
- )}
158
- {hovered && !isLoading && (
159
- <span style={{
160
- position: "absolute",
161
- bottom: "100%",
162
- left: "50%",
163
- transform: "translateX(-50%)",
164
- marginBottom: 4,
165
- padding: "2px 6px",
166
- borderRadius: 4,
167
- background: "#1f2937",
168
- color: "#ffffff",
169
- fontSize: 10,
170
- whiteSpace: "nowrap",
171
- pointerEvents: "none",
172
- zIndex: 10,
173
- }}>
174
- See suggestion
175
- </span>
176
- )}
177
- </span>
178
- );
179
- }
180
-
181
- /** Highlights all occurrences of `keyword` in `text` with a yellow background */
182
- function HighlightKeyword({ text, keyword }: { text: string; keyword: string }) {
183
- if (!keyword || !text) return <>{text}</>;
184
- const regex = new RegExp(`(${keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`, "gi");
185
- const parts = text.split(regex);
186
- return (
187
- <>
188
- {parts.map((part, i) =>
189
- regex.test(part) ? (
190
- <span key={i} style={{ background: "#FEF08A", fontWeight: 600, borderRadius: 2, padding: "0 1px" }}>{part}</span>
191
- ) : (
192
- <span key={i}>{part}</span>
193
- )
194
- )}
195
- </>
196
- );
197
- }
198
-
199
- function KeywordHelpDisplay({ suggestions, onRegenerate, isRegenerating, term, publication }: {
200
- suggestions: KeywordHelpSuggestion[];
201
- onRegenerate: () => void;
202
- isRegenerating: boolean;
203
- term: string;
204
- publication?: string;
205
- }) {
206
- return (
207
- <div style={{ paddingLeft: 8, paddingTop: 4, paddingBottom: 4, display: "flex", flexDirection: "column", gap: 6 }}>
208
- {suggestions.map((s, i) => (
209
- <div key={i} style={{ fontSize: 11, lineHeight: 1.5, padding: "6px 8px", background: "rgba(0,93,172,0.05)", borderRadius: 6, borderLeft: `2px solid ${MJH_BLUE}` }}>
210
- <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
211
- <div style={{ flex: 1 }}>
212
- {s.type === "change" ? (
213
- <>
214
- <div style={{ color: "#4b5563", fontWeight: 600, fontSize: 10, textTransform: "uppercase", marginBottom: 2 }}>Change</div>
215
- <div style={{ color: "#991b1b", textDecoration: "line-through", marginBottom: 2 }}>{s.original}</div>
216
- <div style={{ color: "#166534" }}><HighlightKeyword text={s.revised || ""} keyword={term} /></div>
217
- </>
218
- ) : (
219
- <>
220
- <div style={{ color: "#4b5563", fontWeight: 600, fontSize: 10, textTransform: "uppercase", marginBottom: 2 }}>Add{s.where ? ` - ${s.where}` : ""}</div>
221
- <div style={{ color: "#1f2937" }}><HighlightKeyword text={s.sentence || ""} keyword={term} /></div>
222
- </>
223
- )}
224
- </div>
225
- <FeedbackButton
226
- suggestionType="keyword_help"
227
- suggestionText={`${term}: ${s.type === "change" ? s.revised : s.sentence}`}
228
- publication={publication}
229
- />
230
- </div>
231
- </div>
232
- ))}
233
- {/* Regenerate button */}
234
- <button
235
- onClick={onRegenerate}
236
- disabled={isRegenerating}
237
- style={{
238
- display: "flex",
239
- alignItems: "center",
240
- gap: 4,
241
- padding: "4px 8px",
242
- fontSize: 10,
243
- color: isRegenerating ? "#9ca3af" : MJH_BLUE,
244
- background: "none",
245
- border: "none",
246
- cursor: isRegenerating ? "wait" : "pointer",
247
- alignSelf: "flex-start",
248
- transition: "color 150ms",
249
- }}
250
- title="Regenerate suggestions"
251
- >
252
- <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor" style={{ animation: isRegenerating ? "spin 1s linear infinite" : "none" }}>
253
- <path fillRule="evenodd" d="M15.312 11.424a5.5 5.5 0 01-9.201 2.466l-.312-.311h2.433a.75.75 0 000-1.5H4.598a.75.75 0 00-.75.75v3.634a.75.75 0 001.5 0v-2.033l.312.311a7 7 0 0011.712-3.138.75.75 0 00-1.449-.39zm-10.624-2.85a5.5 5.5 0 019.201-2.466l.312.311h-2.433a.75.75 0 000 1.5h3.634a.75.75 0 00.75-.75V3.535a.75.75 0 00-1.5 0v2.033l-.312-.311A7 7 0 002.628 8.395a.75.75 0 001.449.39z" clipRule="evenodd" />
254
- </svg>
255
- {isRegenerating ? "Regenerating..." : "Regenerate"}
256
- </button>
257
- </div>
258
- );
259
- }
260
-
261
- function PencilButton({ onClick, active }: { onClick: () => void; active: boolean }) {
262
- return (
263
- <button
264
- onClick={onClick}
265
- style={{
266
- background: "none",
267
- border: "none",
268
- cursor: "pointer",
269
- padding: 2,
270
- display: "flex",
271
- alignItems: "center",
272
- color: active ? MJH_GOLD : "#9ca3af",
273
- transition: "color 150ms",
274
- flexShrink: 0,
275
- }}
276
- title="Add custom keyword"
277
- >
278
- <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor">
279
- <path d="M2.695 14.763l-1.262 3.154a.5.5 0 00.65.65l3.155-1.262a4 4 0 001.343-.885L17.5 5.5a2.121 2.121 0 00-3-3L3.58 13.42a4 4 0 00-.885 1.343z" />
280
- </svg>
281
- </button>
282
- );
283
- }
284
-
285
- function PrimaryKeywordSelector({
286
- candidates,
287
- selectedTerm,
288
- onSelect,
289
- publication,
290
- documentId,
291
- }: {
292
- candidates: PrimaryKeywordCandidate[];
293
- selectedTerm: string;
294
- onSelect: (term: string) => void;
295
- publication?: string;
296
- documentId?: string;
297
- }) {
298
- const [customInputOpen, setCustomInputOpen] = useState(false);
299
- const [customValue, setCustomValue] = useState("");
300
-
301
- const handleCustomSubmit = () => {
302
- const trimmed = customValue.trim();
303
- if (trimmed) {
304
- onSelect(trimmed);
305
- setCustomValue("");
306
- setCustomInputOpen(false);
307
- }
308
- };
309
-
310
- return (
311
- <div style={cardStyle}>
312
- <SectionHeader
313
- label="Primary Keyword"
314
- iconColor="#16a34a"
315
- actionButton={
316
- <PencilButton onClick={() => setCustomInputOpen(!customInputOpen)} active={customInputOpen} />
317
- }
318
- />
319
-
320
- {customInputOpen && (
321
- <div style={{ marginBottom: 8, display: "flex", gap: 6 }}>
322
- <input
323
- type="text"
324
- value={customValue}
325
- onChange={(e) => setCustomValue(e.target.value)}
326
- onKeyDown={(e) => { if (e.key === "Enter") handleCustomSubmit(); }}
327
- placeholder="Type a custom primary keyword"
328
- autoFocus
329
- style={{
330
- flex: 1,
331
- padding: "5px 8px",
332
- fontSize: 12,
333
- borderRadius: 8,
334
- border: "1px solid #e5e7eb",
335
- outline: "none",
336
- fontFamily: "inherit",
337
- }}
338
- />
339
- <button
340
- onClick={handleCustomSubmit}
341
- disabled={!customValue.trim()}
342
- style={{
343
- padding: "5px 10px",
344
- fontSize: 11,
345
- fontWeight: 600,
346
- borderRadius: 6,
347
- border: "none",
348
- background: customValue.trim() ? MJH_GOLD : "#e5e7eb",
349
- color: customValue.trim() ? "#ffffff" : "#9ca3af",
350
- cursor: customValue.trim() ? "pointer" : "not-allowed",
351
- }}
352
- >
353
- Set
354
- </button>
355
- </div>
356
- )}
357
-
358
- <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
359
- {candidates.map((candidate) => {
360
- const isSelected = candidate.term === selectedTerm;
361
- return (
362
- <div
363
- key={candidate.term}
364
- onClick={() => onSelect(candidate.term)}
365
- style={{
366
- display: "flex",
367
- alignItems: "center",
368
- gap: 8,
369
- padding: "6px 8px",
370
- borderRadius: 8,
371
- cursor: "pointer",
372
- background: isSelected ? "rgba(22,163,74,0.06)" : "transparent",
373
- border: isSelected ? "1px solid rgba(22,163,74,0.2)" : "1px solid transparent",
374
- transition: "all 150ms",
375
- }}
376
- >
377
- {/* Radio dot */}
378
- <div style={{
379
- width: 14,
380
- height: 14,
381
- borderRadius: "50%",
382
- border: isSelected ? "none" : "2px solid #d1d5db",
383
- background: isSelected ? "#16a34a" : "transparent",
384
- flexShrink: 0,
385
- display: "flex",
386
- alignItems: "center",
387
- justifyContent: "center",
388
- }}>
389
- {isSelected && (
390
- <div style={{ width: 6, height: 6, borderRadius: "50%", background: "#ffffff" }} />
391
- )}
392
- </div>
393
-
394
- <div style={{ flex: 1, minWidth: 0 }}>
395
- <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
396
- <span style={{
397
- fontSize: 12,
398
- fontWeight: isSelected ? 600 : 400,
399
- color: isSelected ? "#166534" : "#374151",
400
- }}>
401
- {candidate.term}
402
- </span>
403
- {candidate.volume != null && (
404
- <span style={{ fontSize: 11, fontWeight: 600, color: "#1f2937" }}>{candidate.volume === 0 ? "N/A" : `${abbrevVol(candidate.volume)}/mo`}</span>
405
- )}
406
- <span style={{ fontSize: 10, color: "#1f2937" }}>
407
- {Math.round((candidate.confidence ?? 0) * 100)}% confidence
408
- </span>
409
- </div>
410
- {candidate.placement && (
411
- <div style={{ marginTop: 3 }}>
412
- <PlacementIndicators placement={candidate.placement} />
413
- </div>
414
- )}
415
- </div>
416
-
417
- </div>
418
- );
419
- })}
420
- </div>
421
- </div>
422
- );
423
- }
424
-
425
- const PLACEMENT_FILTERS: { key: PlacementKey; label: string; letter: string }[] = [
426
- { key: "inBody", label: "Body", letter: "B" },
427
- { key: "inTitle", label: "Title", letter: "T" },
428
- { key: "inMetaDescription", label: "Description", letter: "D" },
429
- { key: "inImages", label: "Images", letter: "I" },
430
- { key: "inUrl", label: "URL", letter: "U" },
431
- ];
432
-
433
- const INITIAL_SHOW = 8;
434
-
435
- function computePlacementClient(term: string, content: string, fields?: DocumentFields): import("../lib/types").KeywordPlacement {
436
- const lower = term.toLowerCase();
437
- return {
438
- inBody: content.toLowerCase().includes(lower),
439
- inTitle: typeof fields?.title === 'string' ? fields.title.toLowerCase().includes(lower) : false,
440
- inMetaDescription: typeof fields?.metaDescription === 'string' ? fields.metaDescription.toLowerCase().includes(lower) : false,
441
- inImages: fields?.imageNames?.some((name: string) => name.toLowerCase().includes(lower)) ?? false,
442
- inUrl: fields?.slug?.toLowerCase().includes(lower) ?? false,
443
- };
444
- }
445
-
446
- // Colorblind-safe purple (matches the ScoreDonut section-fit slice). Used as the
447
- // distinct accent for the secondary-keyword chooser folded into Supporting Keywords.
448
- const SECONDARY_PURPLE = "#9B59B6";
449
- // Darker purple for small (<=12px) text so it clears WCAG AA 4.5:1 on the light panel.
450
- // Circles, dots and borders keep the brighter brand purple above.
451
- const SECONDARY_PURPLE_TEXT = "#7D3C98";
452
-
453
- function SuggestedKeywordsCard({
454
- keywords,
455
- text,
456
- apiUrl,
457
- publication,
458
- documentFields,
459
- refreshVolumes,
460
- isVolumesLoading,
461
- documentId,
462
- secondaryKeyword,
463
- onSelectSecondary,
464
- primaryTerm,
465
- }: {
466
- keywords: SuggestedKeyword[];
467
- text: string;
468
- apiUrl: string;
469
- publication?: string;
470
- documentFields?: DocumentFields;
471
- refreshVolumes?: () => void;
472
- isVolumesLoading?: boolean;
473
- documentId?: string;
474
- secondaryKeyword?: string;
475
- onSelectSecondary?: (term: string) => void;
476
- primaryTerm?: string;
477
- }) {
478
- // Per-doc persistence: manual keywords, generated "more" keywords, and cached
479
- // AI keyword help survive dock/undock and full page reload.
480
- const docScope = documentId || "default";
481
- const [helpData, setHelpData] = usePersistentState<Record<string, KeywordHelpSuggestion[]>>(
482
- `seo-copilot-help-data-${docScope}`,
483
- {}
484
- );
485
- const [loadingTerm, setLoadingTerm] = useState<string | null>(null);
486
- const [regeneratingTerm, setRegeneratingTerm] = useState<string | null>(null);
487
- const [manualInputOpen, setManualInputOpen] = useState(false);
488
- const [manualInputValue, setManualInputValue] = useState("");
489
- const [manualKeywords, setManualKeywords] = usePersistentState<string[]>(
490
- `seo-copilot-manual-keywords-${docScope}`,
491
- []
492
- );
493
- const [expanded, setExpanded] = usePersistentState<boolean>("seo-copilot-ui-keywords-expanded", false);
494
- const [extraKeywords, setExtraKeywords] = usePersistentState<SuggestedKeyword[]>(
495
- `seo-copilot-extra-keywords-${docScope}`,
496
- []
497
- );
498
- const [isGeneratingMore, setIsGeneratingMore] = useState(false);
499
- // Secondary-keyword selection mode: when on, supporting rows swap their status dot
500
- // for a clickable purple circle so the editor can pick one as the secondary target.
501
- const [secSelecting, setSecSelecting] = useState(false);
502
- // Entering selection mode expands the list so a circle appears next to EVERY supporting
503
- // keyword (spec), not just the first INITIAL_SHOW rows visible while collapsed.
504
- const startSecSelecting = () => { setExpanded(true); setSecSelecting(true); };
505
- const [sortAsc, setSortAsc] = usePersistentState<boolean>("seo-copilot-ui-keywords-sort-asc", false);
506
- // Active filters - persist as array since JSON.stringify can't round-trip a Set.
507
- const filtersKey = `seo-copilot-ui-keywords-filters-${docScope}`;
508
- const [activeFilters, setActiveFiltersRaw] = useState<Set<PlacementKey>>(
509
- () => new Set(loadLocalArray<PlacementKey>(filtersKey))
510
- );
511
- const [showFilterDropdown, setShowFilterDropdown] = useState(false);
512
- const setActiveFilters = useCallback(
513
- (updater: Set<PlacementKey> | ((prev: Set<PlacementKey>) => Set<PlacementKey>)) => {
514
- setActiveFiltersRaw((prev) => {
515
- const next = typeof updater === "function" ? updater(prev) : updater;
516
- try {
517
- localStorage.setItem(filtersKey, JSON.stringify(Array.from(next)));
518
- } catch {
519
- /* silent */
520
- }
521
- return next;
522
- });
523
- },
524
- [filtersKey]
525
- );
526
-
527
- const fetchHelp = async (term: string, forceRegenerate = false) => {
528
- if (helpData[term] && !forceRegenerate) {
529
- const next = { ...helpData };
530
- delete next[term];
531
- setHelpData(next);
532
- return;
533
- }
534
- if (forceRegenerate) { setRegeneratingTerm(term); } else { setLoadingTerm(term); }
535
- try {
536
- // Pass previous suggestions when regenerating so API avoids repeating them
537
- const previousSuggestions = forceRegenerate && helpData[term]
538
- ? helpData[term].map((s) => s.revised || s.sentence || "").filter(Boolean)
539
- : undefined;
540
- const res = await fetch(`${apiUrl}/api/seo-copilot/keyword-help`, {
541
- method: "POST",
542
- headers: jsonHeaders(),
543
- // Clip to 5,000 chars: the backend only reads the first 4,000 anyway, so sending
544
- // the full article needlessly bloats the request on long pieces.
545
- body: JSON.stringify({ keyword: term, content: text.slice(0, 5000), publication, previousSuggestions }),
546
- });
547
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
548
- const data = await res.json();
549
- setHelpData((prev) => ({ ...prev, [term]: data.suggestions || [] }));
550
- } catch {
551
- setHelpData((prev) => ({ ...prev, [term]: [{ type: "add", sentence: "Failed to generate suggestions. Try again.", where: "" }] }));
552
- }
553
- setLoadingTerm(null);
554
- setRegeneratingTerm(null);
555
- };
556
-
557
- const [enrichingTerms, setEnrichingTerms] = useState<Set<string>>(new Set());
558
-
559
- const handleAddManual = async () => {
560
- const trimmed = manualInputValue.trim();
561
- if (!trimmed) return;
562
- // Skip if already exists
563
- if (manualKeywords.includes(trimmed) || allKeywords.some((kw) => kw.term.toLowerCase() === trimmed.toLowerCase())) return;
564
-
565
- setManualKeywords((prev) => [...prev, trimmed]);
566
- setManualInputValue("");
567
-
568
- // Immediately add to extraKeywords with placeholder data + compute placement
569
- const placement = computePlacementClient(trimmed, text, documentFields);
570
- const inContent = text.toLowerCase().includes(trimmed.toLowerCase());
571
- setExtraKeywords((prev) => [...prev, { term: trimmed, volume: 0, inContent, placement }]);
572
- setEnrichingTerms((prev) => new Set(prev).add(trimmed));
573
-
574
- // Fetch volume from SEMrush
575
- try {
576
- const res = await fetch(`${apiUrl}/api/seo-copilot/keywords`, {
577
- method: "POST",
578
- headers: jsonHeaders(),
579
- body: JSON.stringify({ keywords: [trimmed] }),
580
- });
581
- if (res.ok) {
582
- const data = await res.json();
583
- const match = (data.results || []).find((r: { keyword: string }) => r.keyword.toLowerCase() === trimmed.toLowerCase());
584
- if (match) {
585
- setExtraKeywords((prev) => prev.map((kw) =>
586
- kw.term.toLowerCase() === trimmed.toLowerCase()
587
- ? { ...kw, volume: match.volume ?? 0 }
588
- : kw
589
- ));
590
- }
591
- }
592
- } catch { /* silent */ }
593
- setEnrichingTerms((prev) => { const next = new Set(prev); next.delete(trimmed); return next; });
594
-
595
- // Auto-trigger lightbulb help
596
- fetchHelp(trimmed);
597
- };
598
-
599
- const toggleFilter = (key: PlacementKey) => {
600
- setActiveFilters((prev) => {
601
- if (key === "none") {
602
- // "None" deselects all placement filters
603
- return prev.has("none") ? new Set() : new Set(["none"] as PlacementKey[]);
604
- }
605
- // Any placement filter deselects "none"
606
- const next = new Set(prev);
607
- next.delete("none");
608
- if (next.has(key)) { next.delete(key); } else { next.add(key); }
609
- return next;
610
- });
611
- };
612
-
613
- // Apply filters
614
- let filtered = keywords;
615
- if (activeFilters.size > 0) {
616
- const hasNoneFilter = activeFilters.has("none");
617
- const placementFilters = [...activeFilters].filter((f) => f !== "none") as PlacementKey[];
618
-
619
- filtered = keywords.filter((kw) => {
620
- if (hasNoneFilter) {
621
- // "None" = show keywords with zero placements
622
- return placementCount(kw.placement) === 0;
623
- }
624
- if (placementFilters.length === 0) return true;
625
- if (!kw.placement) return false;
626
- for (const f of placementFilters) {
627
- if (f === "none") continue;
628
- if (!kw.placement[f as keyof import("../lib/types").KeywordPlacement]) return false;
629
- }
630
- return true;
631
- });
632
- }
633
-
634
- // Apply sort
635
- const sorted = [...filtered].sort((a, b) => {
636
- const pA = placementCount(a.placement);
637
- const pB = placementCount(b.placement);
638
- if (sortAsc) {
639
- if (pA !== pB) return pA - pB;
640
- return a.volume - b.volume;
641
- }
642
- if (pA !== pB) return pB - pA;
643
- return b.volume - a.volume;
644
- });
645
-
646
- // Merge extra generated keywords into the list
647
- const merged = [...sorted, ...extraKeywords.filter((ek) => !sorted.some((s) => s.term.toLowerCase() === ek.term.toLowerCase()))];
648
- // Hide N/A (no-search-volume) keywords entirely - editors only want terms with real volume.
649
- // Two guards stop this from ever flashing an empty list: (1) while volumes are still loading
650
- // every term reads as 0, so keep showing them until the lookup settles; (2) if NOTHING has
651
- // volume (e.g. SEMrush failed, or a very niche topic) fall back to showing all of them.
652
- const hasVol = (k: SuggestedKeyword) => k.volume != null && k.volume > 0;
653
- const withVol = merged.filter(hasVol);
654
- const allKeywords = isVolumesLoading || withVol.length === 0 ? merged : withVol;
655
- const visible = expanded ? allKeywords : allKeywords.slice(0, INITIAL_SHOW);
656
- const hiddenCount = allKeywords.length - INITIAL_SHOW;
657
- const missingCount = keywords.filter((kw) => !kw.inContent).length;
658
- // Secondary-keyword matching is case-insensitive so a stored secondary still highlights
659
- // its row after re-analysis re-cases the term. `secondaryInList` flags an orphan secondary
660
- // (set but no longer present in the list) so the banner can say so. `isPrimaryRow` stops the
661
- // active primary from being offered as its own secondary.
662
- const secLower = (secondaryKeyword || "").toLowerCase();
663
- const primaryLower = (primaryTerm || "").toLowerCase();
664
- const isSecondaryRow = (term: string) => secLower !== "" && term.toLowerCase() === secLower;
665
- const isPrimaryRow = (term: string) => primaryLower !== "" && term.toLowerCase() === primaryLower;
666
- const secondaryInList = secLower !== "" && allKeywords.some((k) => k.term.toLowerCase() === secLower);
667
-
668
- const generateMoreKeywords = async () => {
669
- setIsGeneratingMore(true);
670
- try {
671
- const existingTerms = allKeywords.map((kw) => kw.term);
672
- const res = await fetch(`${apiUrl}/api/seo-copilot/more-keywords`, {
673
- method: "POST",
674
- headers: jsonHeaders(),
675
- body: JSON.stringify({ content: text, existingKeywords: existingTerms, publication }),
676
- });
677
- if (res.ok) {
678
- const data = await res.json();
679
- const newKws: SuggestedKeyword[] = (data.keywords || []).map((kw: { term: string; volume: number | null; inContent: boolean }) => ({
680
- term: kw.term,
681
- volume: kw.volume ?? 0,
682
- inContent: kw.inContent,
683
- }));
684
- setExtraKeywords((prev) => [...prev, ...newKws]);
685
- }
686
- } catch { /* silent */ }
687
- setIsGeneratingMore(false);
688
- };
689
-
690
- // Auto-backfill ONCE per document: if, after volumes settle, the list is thin on real-volume
691
- // terms, pull more keywords a single time so the editor sees a full list. Bounded to one
692
- // backfill per document open (the card remounts per document) so it never loops or burns the
693
- // keyword API on every keystroke or secondary change.
694
- const didBackfillRef = useRef(false);
695
- useEffect(() => {
696
- if (didBackfillRef.current) return;
697
- if (isVolumesLoading || isGeneratingMore || keywords.length === 0) return;
698
- didBackfillRef.current = true;
699
- const volCount = [...keywords, ...extraKeywords].filter((k) => k.volume != null && k.volume > 0).length;
700
- if (volCount < 8) generateMoreKeywords();
701
- // eslint-disable-next-line react-hooks/exhaustive-deps
702
- }, [keywords, isVolumesLoading]);
703
-
704
- return (
705
- <div style={secSelecting
706
- ? { ...cardStyle, border: `1.5px solid ${SECONDARY_PURPLE}`, boxShadow: [cardStyle.boxShadow, `0 0 0 1px rgba(155,89,182,0.25)`].filter(Boolean).join(", ") }
707
- : cardStyle}>
708
- {/* Header row with count, sort, filter, pencil */}
709
- <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
710
- <div style={{ width: 6, height: 6, borderRadius: "50%", background: MJH_BLUE, flexShrink: 0 }} />
711
- <span style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em", color: "#4b5563", fontWeight: 600, flex: 1 }}>
712
- Supporting Keywords
713
- </span>
714
- {/* Refresh volumes */}
715
- {refreshVolumes && (
716
- <button
717
- onClick={refreshVolumes}
718
- disabled={isVolumesLoading}
719
- style={{ background: "none", border: "none", cursor: isVolumesLoading ? "wait" : "pointer", padding: 2, display: "flex", color: isVolumesLoading ? "#d1d5db" : "#9ca3af", fontSize: 10 }}
720
- title="Refresh keyword volumes"
721
- >
722
- {isVolumesLoading ? (
723
- <LoadingBars size="xs" color="#9ca3af" />
724
- ) : (
725
- <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor" style={{ transition: "transform 150ms" }}>
726
- <path fillRule="evenodd" d="M15.312 11.424a5.5 5.5 0 01-9.201 2.466l-.312-.311h2.433a.75.75 0 000-1.5H4.598a.75.75 0 00-.75.75v3.634a.75.75 0 001.5 0v-2.033l.312.311a7 7 0 0011.712-3.138.75.75 0 00-1.449-.39zm-10.624-2.85a5.5 5.5 0 019.201-2.466l.312.311h-2.433a.75.75 0 000 1.5h3.634a.75.75 0 00.75-.75V3.535a.75.75 0 00-1.5 0v2.033l-.312-.311A7 7 0 002.628 8.395a.75.75 0 001.449.39z" clipRule="evenodd" />
727
- </svg>
728
- )}
729
- </button>
730
- )}
731
- {/* Sort toggle */}
732
- <button
733
- onClick={() => setSortAsc(!sortAsc)}
734
- style={{ background: "none", border: "none", cursor: "pointer", padding: 2, display: "flex", color: "#1f2937", fontSize: 10 }}
735
- title={sortAsc ? "Sort: least placements first" : "Sort: most placements first"}
736
- >
737
- <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor" style={{ transform: sortAsc ? "rotate(180deg)" : "none", transition: "transform 150ms" }}>
738
- <path fillRule="evenodd" d="M10 3a.75.75 0 01.55.24l3.25 3.5a.75.75 0 11-1.1 1.02L10 4.852 7.3 7.76a.75.75 0 01-1.1-1.02l3.25-3.5A.75.75 0 0110 3zm-3.76 9.2a.75.75 0 011.06.04l2.7 2.908 2.7-2.908a.75.75 0 111.1 1.02l-3.25 3.5a.75.75 0 01-1.1 0l-3.25-3.5a.75.75 0 01.04-1.06z" clipRule="evenodd" />
739
- </svg>
740
- </button>
741
- {/* Filter dropdown */}
742
- <div style={{ position: "relative" }}>
743
- <button
744
- onClick={() => setShowFilterDropdown(!showFilterDropdown)}
745
- style={{
746
- background: activeFilters.size > 0 ? "rgba(0,93,172,0.1)" : "none",
747
- border: "none", cursor: "pointer", padding: "2px 4px", display: "flex", alignItems: "center", gap: 2,
748
- color: activeFilters.size > 0 ? MJH_BLUE : "#9ca3af", borderRadius: 4, fontSize: 10,
749
- }}
750
- title="Filter by placement"
751
- >
752
- <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor">
753
- <path fillRule="evenodd" d="M2.628 1.601C5.028 1.206 7.49 1 10 1s4.973.206 7.372.601a.75.75 0 01.628.74v2.288a2.25 2.25 0 01-.659 1.59l-4.682 4.683a2.25 2.25 0 00-.659 1.59v3.037c0 .684-.31 1.33-.844 1.757l-1.937 1.55A.75.75 0 018 18.25v-5.757a2.25 2.25 0 00-.659-1.591L2.659 6.22A2.25 2.25 0 012 4.629V2.34a.75.75 0 01.628-.74z" clipRule="evenodd" />
754
- </svg>
755
- {activeFilters.size > 0 && <span>{activeFilters.size}</span>}
756
- </button>
757
- {showFilterDropdown && (
758
- <div style={{
759
- position: "absolute", top: "100%", right: 0, marginTop: 4, width: 150,
760
- background: "#ffffff", borderRadius: 8, boxShadow: "0 4px 12px rgba(0,0,0,0.12)",
761
- border: "1px solid #e5e7eb", zIndex: 50, padding: "4px 0",
762
- }}>
763
- {PLACEMENT_FILTERS.map(({ key, label, letter }) => (
764
- <button
765
- key={key}
766
- onClick={() => toggleFilter(key)}
767
- style={{
768
- width: "100%", display: "flex", alignItems: "center", gap: 8,
769
- padding: "5px 10px", background: "none", border: "none", cursor: "pointer",
770
- fontSize: 11, color: "#1f2937", textAlign: "left",
771
- }}
772
- >
773
- <div style={{
774
- width: 14, height: 14, borderRadius: 3, border: "1.5px solid " + (activeFilters.has(key) ? MJH_BLUE : "#d1d5db"),
775
- background: activeFilters.has(key) ? MJH_BLUE : "transparent",
776
- display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
777
- }}>
778
- {activeFilters.has(key) && (
779
- <svg width="8" height="8" viewBox="0 0 12 12" fill="white"><path d="M10 3L4.5 8.5 2 6" stroke="white" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
780
- )}
781
- </div>
782
- <span style={{ fontWeight: 600, color: "#1f2937", width: 14 }}>{letter}</span>
783
- <span>{label}</span>
784
- </button>
785
- ))}
786
- {/* "None" option - show keywords with no placements */}
787
- <button
788
- onClick={() => toggleFilter("none")}
789
- style={{
790
- width: "100%", display: "flex", alignItems: "center", gap: 8,
791
- padding: "5px 10px", background: "none", border: "none", cursor: "pointer",
792
- fontSize: 11, color: "#1f2937", textAlign: "left",
793
- borderTop: "1px solid #f1f5f9",
794
- }}
795
- >
796
- <div style={{
797
- width: 14, height: 14, borderRadius: 3, border: "1.5px solid " + (activeFilters.has("none") ? MJH_BLUE : "#d1d5db"),
798
- background: activeFilters.has("none") ? MJH_BLUE : "transparent",
799
- display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
800
- }}>
801
- {activeFilters.has("none") && (
802
- <svg width="8" height="8" viewBox="0 0 12 12" fill="white"><path d="M10 3L4.5 8.5 2 6" stroke="white" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
803
- )}
804
- </div>
805
- <span style={{ fontWeight: 600, color: "#1f2937", width: 14 }}>-</span>
806
- <span>None (missing all)</span>
807
- </button>
808
- {activeFilters.size > 0 && (
809
- <button
810
- onClick={() => { setActiveFilters(new Set()); setShowFilterDropdown(false); }}
811
- style={{
812
- width: "100%", padding: "5px 10px", background: "none", border: "none",
813
- borderTop: "1px solid #f1f5f9", cursor: "pointer", fontSize: 10, color: "#dc2626", textAlign: "center",
814
- }}
815
- >
816
- Clear filters
817
- </button>
818
- )}
819
- </div>
820
- )}
821
- </div>
822
- <PencilButton onClick={() => setManualInputOpen(!manualInputOpen)} active={manualInputOpen} />
823
- </div>
824
-
825
- {/* Secondary-keyword chooser - folded into Supporting Keywords per spec.
826
- Idle: a clickable purple notice. Selecting: a hint + cancel. Chosen: the
827
- picked term in purple with Change / clear. */}
828
- {/* Screen-reader announcement when selection mode toggles on. */}
829
- <span aria-live="polite" style={{ position: "absolute", width: 1, height: 1, padding: 0, margin: -1, overflow: "hidden", clip: "rect(0 0 0 0)", whiteSpace: "nowrap", border: 0 }}>
830
- {secSelecting ? "Selection mode on. Pick a keyword below to set it as the secondary keyword." : ""}
831
- </span>
832
- {onSelectSecondary && (
833
- secSelecting ? (
834
- <div style={{
835
- display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8,
836
- marginBottom: 8, padding: "5px 10px", borderRadius: 8,
837
- background: "rgba(155,89,182,0.08)", border: `1px solid rgba(155,89,182,0.35)`,
838
- }}>
839
- <span style={{ fontSize: 11, fontWeight: 600, color: SECONDARY_PURPLE_TEXT }}>
840
- Pick a keyword below to set as secondary.
841
- </span>
842
- <button
843
- onClick={() => setSecSelecting(false)}
844
- style={{ background: "none", border: "none", cursor: "pointer", fontSize: 11, fontWeight: 600, color: "#6b7280", padding: 2, fontFamily: "inherit" }}
845
- >
846
- Cancel
847
- </button>
848
- </div>
849
- ) : secondaryKeyword ? (
850
- <div style={{
851
- display: "flex", alignItems: "center", gap: 8, marginBottom: 8,
852
- padding: "5px 10px", borderRadius: 8,
853
- background: "rgba(155,89,182,0.08)", border: `1px solid rgba(155,89,182,0.35)`,
854
- }}>
855
- <div style={{ width: 8, height: 8, borderRadius: "50%", background: SECONDARY_PURPLE, flexShrink: 0 }} />
856
- <span style={{ fontSize: 11, fontWeight: 600, color: SECONDARY_PURPLE_TEXT, flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
857
- Secondary: {secondaryKeyword}
858
- </span>
859
- {!secondaryInList && (
860
- <span title="This keyword is no longer in the list below - re-pick or clear it." style={{ fontSize: 9.5, fontWeight: 600, fontStyle: "italic", color: "#9ca3af", flexShrink: 0 }}>
861
- not in list
862
- </span>
863
- )}
864
- <button
865
- onClick={startSecSelecting}
866
- style={{ background: "none", border: "none", cursor: "pointer", fontSize: 11, fontWeight: 600, color: SECONDARY_PURPLE_TEXT, padding: 2, fontFamily: "inherit" }}
867
- >
868
- Change
869
- </button>
870
- <button
871
- onClick={() => onSelectSecondary("")}
872
- title="Clear secondary keyword"
873
- aria-label="Clear secondary keyword"
874
- style={{ background: "none", border: "none", cursor: "pointer", fontSize: 14, lineHeight: 1, color: "#9ca3af", padding: 2, fontFamily: "inherit" }}
875
- >
876
- ×
877
- </button>
878
- </div>
879
- ) : (
880
- <button
881
- onClick={startSecSelecting}
882
- style={{
883
- display: "inline-flex", alignItems: "center", gap: 6, marginBottom: 8,
884
- padding: "4px 10px", borderRadius: 8, cursor: "pointer",
885
- background: "rgba(155,89,182,0.08)", border: `1px solid rgba(155,89,182,0.4)`,
886
- color: SECONDARY_PURPLE_TEXT, fontSize: 11, fontWeight: 600, fontFamily: "inherit",
887
- }}
888
- >
889
- <div style={{ width: 11, height: 11, borderRadius: "50%", border: `2px solid ${SECONDARY_PURPLE}`, flexShrink: 0 }} />
890
- Click to choose a secondary keyword.
891
- </button>
892
- )
893
- )}
894
-
895
- {/* Manual keyword input */}
896
- {manualInputOpen && (
897
- <div style={{ marginBottom: 8, display: "flex", gap: 6 }}>
898
- <input
899
- type="text"
900
- value={manualInputValue}
901
- onChange={(e) => setManualInputValue(e.target.value)}
902
- onKeyDown={(e) => { if (e.key === "Enter") handleAddManual(); }}
903
- placeholder="Add a keyword manually"
904
- autoFocus
905
- style={{ flex: 1, padding: "5px 8px", fontSize: 12, borderRadius: 8, border: "1px solid #e5e7eb", outline: "none", fontFamily: "inherit" }}
906
- />
907
- <button
908
- onClick={handleAddManual}
909
- disabled={!manualInputValue.trim()}
910
- style={{
911
- padding: "5px 10px", fontSize: 11, fontWeight: 600, borderRadius: 6, border: "none",
912
- background: manualInputValue.trim() ? MJH_BLUE : "#e5e7eb",
913
- color: manualInputValue.trim() ? "#ffffff" : "#9ca3af",
914
- cursor: manualInputValue.trim() ? "pointer" : "not-allowed",
915
- }}
916
- >
917
- Add
918
- </button>
919
- </div>
920
- )}
921
-
922
- {/* Keyword rows - flat with status dot */}
923
- <div>
924
- {visible.map((kw, i) => (
925
- <div key={kw.term}>
926
- <div style={{
927
- display: "flex", alignItems: "center", gap: 8,
928
- padding: "5px 0",
929
- borderBottom: i < visible.length - 1 ? "1px solid #f3f4f6" : "none",
930
- minHeight: 28,
931
- }}>
932
- {/* Left indicator. Selection mode: a floating purple circle to pick this
933
- keyword as secondary. Otherwise: the chosen secondary shows a filled
934
- purple dot, the other keywords show nothing once a secondary is set,
935
- and with no secondary chosen the normal in-content status dot. */}
936
- {secSelecting && onSelectSecondary ? (
937
- isPrimaryRow(kw.term) ? (
938
- // The active primary keyword cannot also be the secondary - show a muted,
939
- // non-selectable marker instead of a pickable circle.
940
- <div title="Already your primary keyword" style={{ width: 14, height: 14, borderRadius: "50%", flexShrink: 0, border: "2px solid #e5e7eb", background: "transparent" }} />
941
- ) : (
942
- <button
943
- className="seo-copilot-sec-circle"
944
- onClick={() => { onSelectSecondary(kw.term); setSecSelecting(false); }}
945
- aria-label={`Set ${kw.term} as the secondary keyword`}
946
- title={`Set "${kw.term}" as the secondary keyword`}
947
- style={{
948
- width: 14, height: 14, borderRadius: "50%", flexShrink: 0, padding: 0,
949
- border: `2px solid ${SECONDARY_PURPLE}`, background: "transparent", cursor: "pointer",
950
- animation: "seo-copilot-sec-float 1.8s ease-in-out infinite",
951
- animationDelay: `${(i % 5) * 0.12}s`,
952
- }}
953
- />
954
- )
955
- ) : isSecondaryRow(kw.term) ? (
956
- <div style={{ width: 8, height: 8, borderRadius: "50%", background: SECONDARY_PURPLE, flexShrink: 0 }} />
957
- ) : secondaryKeyword ? (
958
- <div style={{ width: 8, height: 8, flexShrink: 0 }} />
959
- ) : (
960
- <div style={{
961
- width: 8, height: 8, borderRadius: "50%", flexShrink: 0,
962
- background: kw.inContent ? "#16a34a" : "#d1d5db",
963
- }} />
964
- )}
965
- {/* Term - dark gray normally; purple + bold when it is the chosen secondary. */}
966
- <span style={{
967
- fontSize: 12,
968
- fontWeight: isSecondaryRow(kw.term) ? 700 : kw.inContent ? 500 : 600,
969
- flexGrow: 1,
970
- color: !secSelecting && isSecondaryRow(kw.term) ? SECONDARY_PURPLE_TEXT : "#1f2937",
971
- }}>
972
- {kw.term}
973
- </span>
974
- {/* Loading indicator for enriching manual keywords */}
975
- {enrichingTerms.has(kw.term) && <LoadingBars size="xs" color="#6b7280" />}
976
- {/* Abbreviated monthly search volume - readable, not whisper-gray. */}
977
- {!enrichingTerms.has(kw.term) && kw.volume != null && (
978
- <span style={{ fontSize: 10.5, fontWeight: 600, color: "#1f2937", flexShrink: 0 }} title="Monthly searches">{kw.volume === 0 ? "N/A" : `${abbrevVol(kw.volume)}/mo`}</span>
979
- )}
980
- {/* Placement indicators */}
981
- {kw.placement && <PlacementIndicators placement={kw.placement} />}
982
- {/* Lightbulb for missing */}
983
- {!kw.inContent && (
984
- <LightbulbButton onClick={() => fetchHelp(kw.term)} isLoading={loadingTerm === kw.term} />
985
- )}
986
- </div>
987
- {/* Keyword help */}
988
- {helpData[kw.term] && (
989
- <KeywordHelpDisplay
990
- suggestions={helpData[kw.term]}
991
- onRegenerate={() => fetchHelp(kw.term, true)}
992
- isRegenerating={regeneratingTerm === kw.term}
993
- term={kw.term}
994
- publication={publication}
995
- />
996
- )}
997
- </div>
998
- ))}
999
-
1000
- </div>
1001
-
1002
- {/* Show more (first click reveals hidden), then Generate more (subsequent clicks call API) */}
1003
- {!expanded && hiddenCount > 0 && (
1004
- <button
1005
- onClick={() => setExpanded(true)}
1006
- style={{
1007
- marginTop: 6, width: "100%", padding: "4px 0", background: "none", border: "none",
1008
- cursor: "pointer", fontSize: 10, color: "#1f2937", display: "flex", alignItems: "center",
1009
- justifyContent: "center", gap: 4,
1010
- }}
1011
- >
1012
- <svg width="10" height="10" viewBox="0 0 20 20" fill="#9ca3af">
1013
- <path fillRule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" clipRule="evenodd" />
1014
- </svg>
1015
- Show more
1016
- </button>
1017
- )}
1018
- {expanded && (
1019
- <button
1020
- onClick={generateMoreKeywords}
1021
- disabled={isGeneratingMore}
1022
- style={{
1023
- marginTop: 6, width: "100%", padding: "5px 0", background: "none", border: "none",
1024
- cursor: isGeneratingMore ? "wait" : "pointer", fontSize: 10,
1025
- color: isGeneratingMore ? "#9ca3af" : MJH_BLUE,
1026
- display: "flex", alignItems: "center", justifyContent: "center", gap: 4, fontWeight: 500,
1027
- }}
1028
- >
1029
- {isGeneratingMore ? (
1030
- <>
1031
- <LoadingBars size="xs" color={MJH_BLUE} />
1032
- Generating...
1033
- </>
1034
- ) : (
1035
- <>
1036
- <svg width="10" height="10" viewBox="0 0 20 20" fill={MJH_BLUE}>
1037
- <path fillRule="evenodd" d="M15.312 11.424a5.5 5.5 0 01-9.201 2.466l-.312-.311h2.433a.75.75 0 000-1.5H4.598a.75.75 0 00-.75.75v3.634a.75.75 0 001.5 0v-2.033l.312.311a7 7 0 0011.712-3.138.75.75 0 00-1.449-.39zm-10.624-2.85a5.5 5.5 0 019.201-2.466l.312.311h-2.433a.75.75 0 000 1.5h3.634a.75.75 0 00.75-.75V3.535a.75.75 0 00-1.5 0v2.033l-.312-.311A7 7 0 002.628 8.395a.75.75 0 001.449.39z" clipRule="evenodd" />
1038
- </svg>
1039
- Generate more
1040
- </>
1041
- )}
1042
- </button>
1043
- )}
1044
- </div>
1045
- );
1046
- }
1047
-
1048
-
1049
- export function KeywordPanel({
1050
- text,
1051
- publication,
1052
- seedKeywords = [],
1053
- onSeedsChange,
1054
- onSelectPrimary,
1055
- secondaryKeyword = "",
1056
- onSelectSecondary,
1057
- documentFields,
1058
- documentId,
1059
- externalAnalysis,
1060
- }: KeywordPanelProps) {
1061
- const { apiUrl } = useConfig();
1062
- const { analysis, isLoading, error, deepAnalysis, isDeepLoading, runDeepAnalysis } = externalAnalysis;
1063
- const isVolumesLoading = externalAnalysis.isVolumesLoading;
1064
- const refreshVolumes = externalAnalysis.refreshVolumes;
1065
-
1066
- // Auto-trigger AEO when analysis first loads (no button click needed)
1067
- // Auto-trigger AEO - always run deep analysis once keywords are ready
1068
- const [aeoTriggered, setAeoTriggered] = useState(false);
1069
- useEffect(() => {
1070
- // Only check V2 fields for AEO content. (FAQ output removed 2026-05.)
1071
- const hasV2Aeo = deepAnalysis?.aeo?.questionHeadings?.length;
1072
- if (analysis && !hasV2Aeo && !isDeepLoading && !aeoTriggered) {
1073
- setAeoTriggered(true);
1074
- // Start immediately - no delay
1075
- runDeepAnalysis();
1076
- }
1077
- }, [analysis, deepAnalysis, isDeepLoading, aeoTriggered, runDeepAnalysis]);
1078
-
1079
- // Reset AEO trigger when text changes significantly
1080
- useEffect(() => {
1081
- setAeoTriggered(false);
1082
- }, [text]);
1083
-
1084
- // Selected primary keyword term (user can override)
1085
- const defaultSelectedTerm = analysis?.primaryKeyword?.term ?? "";
1086
- const [selectedPrimaryTerm, setSelectedPrimaryTerm] = useState(defaultSelectedTerm);
1087
- const prevDefaultRef = useRef(defaultSelectedTerm);
1088
-
1089
- // Auto-update selected term when analysis refreshes (unless user manually picked a different one)
1090
- useEffect(() => {
1091
- if (defaultSelectedTerm && defaultSelectedTerm !== prevDefaultRef.current) {
1092
- // Only auto-update if the user's current selection was the old default (no manual override).
1093
- // Snapshot the old ref value BEFORE mutating it - the setState updater is queued and runs
1094
- // after this effect body, so it must compare against the old default, not the new one.
1095
- const oldDefault = prevDefaultRef.current;
1096
- prevDefaultRef.current = defaultSelectedTerm;
1097
- setSelectedPrimaryTerm((prev) => (prev === oldDefault ? defaultSelectedTerm : prev));
1098
- }
1099
- }, [defaultSelectedTerm]);
1100
-
1101
- if ((!text || text.trim().length < 20) && (!seedKeywords || seedKeywords.length === 0)) {
1102
- return (
1103
- <div style={{ padding: 24, textAlign: "center" }}>
1104
- <div style={{ fontSize: 14, color: "#1f2937", fontWeight: 500 }}>
1105
- Start writing to see keyword suggestions
1106
- </div>
1107
- <div style={{ fontSize: 12, color: "#4b5563", marginTop: 4 }}>
1108
- Need at least a few sentences
1109
- </div>
1110
- </div>
1111
- );
1112
- }
1113
-
1114
- if (isLoading && !analysis) {
1115
- return (
1116
- <div style={{ padding: 24, display: "flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
1117
- <LoadingBars />
1118
- <span style={{ fontSize: 12, color: "#4b5563" }}>Analyzing content...</span>
1119
- </div>
1120
- );
1121
- }
1122
-
1123
- if (error && !analysis) {
1124
- return (
1125
- <div style={{ ...cardStyle, margin: 12, background: "#fef2f2", color: "#dc2626" }}>
1126
- <span style={{ fontSize: 12 }}>Error: {error}</span>
1127
- </div>
1128
- );
1129
- }
1130
-
1131
- if (!analysis) return null;
1132
-
1133
- const suggestedKeywords = buildSuggestedKeywords(
1134
- analysis.supportingKeywords || [],
1135
- analysis.missingKeywords,
1136
- text,
1137
- documentFields
1138
- );
1139
-
1140
- // Build candidates list with live placement from current document state
1141
- const rawCandidates: PrimaryKeywordCandidate[] = analysis.primaryKeywordCandidates && analysis.primaryKeywordCandidates.length > 0
1142
- ? analysis.primaryKeywordCandidates
1143
- : [analysis.primaryKeyword];
1144
- const candidates = rawCandidates.map((c) => ({
1145
- ...c,
1146
- placement: computePlacementClient(c.term, text, documentFields),
1147
- }));
1148
- // Hide N/A (no-search-volume) primary candidates once volumes have loaded, same as the
1149
- // supporting list - but always keep at least one so the selector is never empty (while
1150
- // volumes load, or if every candidate is N/A, show them all).
1151
- const candHasVol = (c: { volume: number | null }) => c.volume != null && c.volume > 0;
1152
- const candWithVol = candidates.filter(candHasVol);
1153
- const visibleCandidates = isVolumesLoading || candWithVol.length === 0 ? candidates : candWithVol;
1154
-
1155
- // Ensure selectedPrimaryTerm is in the visible candidates, otherwise default to first
1156
- const activeTerm = visibleCandidates.find((c) => c.term === selectedPrimaryTerm)
1157
- ? selectedPrimaryTerm
1158
- : visibleCandidates[0]?.term ?? "";
1159
-
1160
- return (
1161
- <div style={{ padding: 12, display: "flex", flexDirection: "column", gap: 12 }}>
1162
- {/* On-page instructions: the two-keyword target process */}
1163
- <div style={{
1164
- ...cardStyle,
1165
- padding: "11px 13px",
1166
- background: "rgba(0,93,172,0.05)",
1167
- boxShadow: "inset 0 0 0 1px rgba(0,93,172,0.12)",
1168
- }}>
1169
- <div style={{ fontSize: 11.5, color: "#1f2937", lineHeight: 1.55 }}>
1170
- <strong style={{ color: "#00468a" }}>Choose your target keywords.</strong> Pick one <strong>Primary</strong> keyword (required) and, optionally, one <strong>Secondary</strong> keyword. Copilot then optimizes its recommendations toward both.
1171
- </div>
1172
- </div>
1173
-
1174
- {/* Desired Keywords */}
1175
- {onSeedsChange && (
1176
- <SeedKeywordInput seeds={seedKeywords} onSeedsChange={onSeedsChange} />
1177
- )}
1178
-
1179
- {/* Primary Keyword Selector */}
1180
- <PrimaryKeywordSelector
1181
- candidates={visibleCandidates}
1182
- selectedTerm={activeTerm}
1183
- onSelect={(term: string) => { setSelectedPrimaryTerm(term); onSelectPrimary?.(term); }}
1184
- publication={publication}
1185
- />
1186
-
1187
- {/* Supporting Keywords (the secondary-keyword chooser is folded into this card).
1188
- Render when there are supporting keywords OR when secondary selection is enabled,
1189
- so the secondary chooser stays reachable even before any supporting keyword exists
1190
- (the editor can pencil-add one, then pick it). */}
1191
- {(suggestedKeywords.length > 0 || !!onSelectSecondary) && (
1192
- <SuggestedKeywordsCard
1193
- key={documentId || "default"}
1194
- keywords={suggestedKeywords}
1195
- text={text}
1196
- apiUrl={apiUrl}
1197
- publication={publication}
1198
- documentFields={documentFields}
1199
- refreshVolumes={refreshVolumes}
1200
- isVolumesLoading={isVolumesLoading}
1201
- documentId={documentId}
1202
- secondaryKeyword={secondaryKeyword}
1203
- onSelectSecondary={onSelectSecondary}
1204
- primaryTerm={activeTerm}
1205
- />
1206
- )}
1207
-
1208
- {/* AEO insights moved to dedicated AEO/GEO tab in V3 - this panel is keywords only */}
1209
-
1210
- {/* Volumes loading indicator - shows while SEMrush data is being fetched */}
1211
- {isVolumesLoading && (
1212
- <div style={{ display: "flex", alignItems: "center", gap: 6, justifyContent: "center", padding: "4px 0" }}>
1213
- <LoadingBars size="xs" color={MJH_GOLD} />
1214
- <span style={{ fontSize: 10, color: "#4b5563" }}>Checking search volumes...</span>
1215
- </div>
1216
- )}
1217
-
1218
- {/* Background-refresh error banner - shown when a refresh fails but prior data still exists */}
1219
- {error && analysis && (
1220
- <div style={{ padding: "4px 12px", fontSize: 11, color: "#dc2626" }}>
1221
- Could not refresh analysis: {error}
1222
- </div>
1223
- )}
1224
-
1225
- {/* Updating indicator */}
1226
- {isLoading && analysis && (
1227
- <div style={{ display: "flex", alignItems: "center", gap: 6, justifyContent: "center" }}>
1228
- <LoadingBars size="xs" color="#9ca3af" />
1229
- <span style={{ fontSize: 10, color: "#4b5563" }}>Updating insights...</span>
1230
- </div>
1231
- )}
1232
- </div>
1233
- );
1234
- }