sanity-plugin-seo-copilot 0.2.14 → 0.2.16

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