sanity-plugin-seo-copilot 0.2.5 → 0.2.10

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.
@@ -8,6 +8,7 @@ import { useConfig, ConfigProvider } from "./ConfigContext";
8
8
  import { KeywordPanel } from "./KeywordPanel";
9
9
  import { ChatPanel } from "./ChatPanel";
10
10
  import { TabBar } from "./TabBar";
11
+ import { OnboardingInfoButton, OnboardingCard } from "./OnboardingPopup";
11
12
  import { SummaryTab } from "./tabs/SummaryTab";
12
13
  import { AEOTab } from "./tabs/AEOTab";
13
14
  import { LinkingTab } from "./tabs/LinkingTab";
@@ -49,8 +50,12 @@ interface PanelContentProps {
49
50
  docLoading: boolean;
50
51
  documentFields: import("../lib/types").DocumentFields;
51
52
  documentId?: string;
53
+ documentType?: string;
54
+ sanityBaseUrl?: string;
52
55
  selectedPrimary?: string;
53
56
  onSelectPrimary?: (term: string) => void;
57
+ selectedSecondary?: string;
58
+ onSelectSecondary?: (term: string) => void;
54
59
  // Lifted state - survives float/dock toggle (which remounts PanelContent)
55
60
  activeTab: TabId;
56
61
  onActiveTabChange: (id: TabId) => void;
@@ -117,8 +122,12 @@ function PanelContent({
117
122
  docLoading,
118
123
  documentFields,
119
124
  documentId,
125
+ documentType,
126
+ sanityBaseUrl,
120
127
  selectedPrimary,
121
128
  onSelectPrimary,
129
+ selectedSecondary,
130
+ onSelectSecondary,
122
131
  activeTab,
123
132
  onActiveTabChange,
124
133
  chatOpen,
@@ -141,6 +150,8 @@ function PanelContent({
141
150
  selectedPrimary ||
142
151
  externalAnalysis.analysis?.primaryKeyword?.term ||
143
152
  "";
153
+ // Effective secondary keyword - purely the user's optional choice (no auto-default).
154
+ const effectiveSecondary = selectedSecondary || "";
144
155
 
145
156
  // Draggable divider between tab content and chat - splitPercent is lifted to parent for persistence
146
157
  const containerRef = useRef<HTMLDivElement>(null);
@@ -174,6 +185,71 @@ function PanelContent({
174
185
 
175
186
  const headerCursor = isFloating ? "grab" : "default";
176
187
 
188
+ // ---- First-run onboarding popup --------------------------------------------
189
+ // Per-publication: shows the first time an editor opens Copilot for a site, then
190
+ // collapses to the (i) icon. We only mark the site "onboarded" once they actually
191
+ // engage (dismiss / open via the icon / switch a tab) - if they open and never
192
+ // touch it, it shows again next session. The 5s auto-fade alone does NOT onboard.
193
+ const onboardSite = publication || "default";
194
+ const onboardKey = `seo-copilot-onboarded-${onboardSite}`;
195
+ const onboardSessionKey = `seo-copilot-onboard-shown-${onboardSite}`;
196
+ const [popupMode, setPopupMode] = useState<"hidden" | "auto" | "persistent">("hidden");
197
+ const [popupClosing, setPopupClosing] = useState(false);
198
+ const onboardTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
199
+ const onboardFadeRef = useRef<ReturnType<typeof setTimeout> | null>(null);
200
+
201
+ useEffect(() => {
202
+ let onboarded = false;
203
+ let shownThisSession = false;
204
+ try { onboarded = localStorage.getItem(onboardKey) === "1"; } catch { /* ignore */ }
205
+ try { shownThisSession = sessionStorage.getItem(onboardSessionKey) === "1"; } catch { /* ignore */ }
206
+ if (!onboarded && !shownThisSession) {
207
+ setPopupMode("auto");
208
+ try { sessionStorage.setItem(onboardSessionKey, "1"); } catch { /* ignore */ }
209
+ onboardTimerRef.current = setTimeout(() => {
210
+ // Auto-fade to the (i) icon. Does NOT mark onboarded.
211
+ setPopupClosing(true);
212
+ onboardFadeRef.current = setTimeout(() => { setPopupMode("hidden"); setPopupClosing(false); }, 180);
213
+ }, 8000);
214
+ }
215
+ return () => {
216
+ if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
217
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
218
+ };
219
+ // Re-run only when the site changes.
220
+ // eslint-disable-next-line react-hooks/exhaustive-deps
221
+ }, [onboardKey, onboardSessionKey]);
222
+
223
+ const markOnboarded = useCallback(() => {
224
+ try { localStorage.setItem(onboardKey, "1"); } catch { /* ignore */ }
225
+ }, [onboardKey]);
226
+
227
+ const dismissPopup = useCallback(() => {
228
+ if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
229
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
230
+ markOnboarded();
231
+ setPopupClosing(true);
232
+ onboardFadeRef.current = setTimeout(() => { setPopupMode("hidden"); setPopupClosing(false); }, 180);
233
+ }, [markOnboarded]);
234
+
235
+ const openPopupPersistent = useCallback(() => {
236
+ if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
237
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
238
+ markOnboarded();
239
+ setPopupClosing(false);
240
+ setPopupMode("persistent");
241
+ }, [markOnboarded]);
242
+
243
+ // Switching tabs counts as engagement - onboard the site and clear the popup.
244
+ const handleTabChange = useCallback((id: TabId) => {
245
+ markOnboarded();
246
+ if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
247
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
248
+ setPopupClosing(true);
249
+ onboardFadeRef.current = setTimeout(() => { setPopupMode("hidden"); setPopupClosing(false); }, 120);
250
+ onActiveTabChange(id);
251
+ }, [markOnboarded, onActiveTabChange]);
252
+
177
253
  const tabDefs = [
178
254
  { id: "summary" as TabId, label: "Summary", isHub: true, loading: summaryOps.isAnyLoading },
179
255
  { id: "keywords" as TabId, label: "Keywords", loading: keywordAnalysisState.isLoading || keywordAnalysisState.isVolumesLoading },
@@ -194,10 +270,14 @@ function PanelContent({
194
270
  backgroundColor: PANEL_BG,
195
271
  fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif",
196
272
  opacity: 1,
273
+ position: "relative",
197
274
  }}
198
275
  >
199
276
  <style dangerouslySetInnerHTML={{ __html: INJECTED_CSS }} />
200
277
 
278
+ {/* First-run onboarding popup (collapses to the (i) icon in the header) */}
279
+ {popupMode !== "hidden" && <OnboardingCard onDismiss={dismissPopup} closing={popupClosing} />}
280
+
201
281
  {/* Header */}
202
282
  <div
203
283
  onMouseDown={isFloating ? onDragStart : undefined}
@@ -223,6 +303,7 @@ function PanelContent({
223
303
  </span>
224
304
  </div>
225
305
  <div style={{ display: "flex", alignItems: "center", gap: isFloating ? 4 : 6 }}>
306
+ <OnboardingInfoButton onClick={openPopupPersistent} />
226
307
  {isFloating && onToggleFullscreen && (
227
308
  <button
228
309
  onClick={(e) => {
@@ -372,7 +453,7 @@ function PanelContent({
372
453
  </div>
373
454
 
374
455
  {/* Tab Bar */}
375
- <TabBar tabs={tabDefs} activeTab={activeTab} onTabChange={onActiveTabChange} />
456
+ <TabBar tabs={tabDefs} activeTab={activeTab} onTabChange={handleTabChange} />
376
457
 
377
458
  {/* Universal AI disclaimer - lives once at the panel level so every tab
378
459
  inherits it. Subtle muted strip; the editor sees it on every screen. */}
@@ -414,6 +495,8 @@ function PanelContent({
414
495
  seedKeywords={seedKeywords}
415
496
  onSeedsChange={onSeedsChange}
416
497
  onSelectPrimary={onSelectPrimary}
498
+ secondaryKeyword={effectiveSecondary}
499
+ onSelectSecondary={onSelectSecondary}
417
500
  documentFields={documentFields}
418
501
  documentId={documentId}
419
502
  externalAnalysis={keywordAnalysisState}
@@ -425,6 +508,8 @@ function PanelContent({
425
508
  analysis={keywordAnalysisState.analysis}
426
509
  deepAnalysis={keywordAnalysisState.deepAnalysis}
427
510
  documentFields={documentFields}
511
+ primaryKeyword={effectivePrimary}
512
+ secondaryKeyword={effectiveSecondary}
428
513
  linkingSuggestions={linkingOps.suggestions}
429
514
  linkCheckResults={technicalOps.linkCheckResults}
430
515
  isAnyLoading={summaryOps.isAnyLoading}
@@ -459,16 +544,20 @@ function PanelContent({
459
544
  documentId={documentId}
460
545
  publication={publication}
461
546
  text={text}
547
+ sanityBaseUrl={sanityBaseUrl}
548
+ documentType={documentType}
462
549
  />
463
550
  </div>
464
551
  <div style={{ display: activeTab === "meta" ? "block" : "none" }}>
465
- <MetaTab documentFields={documentFields} primaryKeyword={effectivePrimary} isLoading={docLoading} />
552
+ <MetaTab documentFields={documentFields} primaryKeyword={effectivePrimary} secondaryKeyword={effectiveSecondary} isLoading={docLoading} />
466
553
  </div>
467
554
  <div style={{ display: activeTab === "technical" ? "block" : "none" }}>
468
555
  <TechnicalTab
469
556
  text={text}
470
557
  documentFields={documentFields}
471
558
  isLoading={docLoading}
559
+ primaryKeyword={effectivePrimary}
560
+ secondaryKeyword={effectiveSecondary}
472
561
  linkCheckResults={technicalOps.linkCheckResults}
473
562
  isLinkCheckLoading={technicalOps.isLinkCheckLoading}
474
563
  linkCheckError={technicalOps.linkCheckError}
@@ -595,8 +684,10 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
595
684
  );
596
685
  const dragOffset = useRef<{ dx: number; dy: number } | null>(null);
597
686
  const resizeStart = useRef<{ startX: number; startY: number; startW: number; startH: number } | null>(null);
687
+ const activeDragCleanupRef = useRef<(() => void) | null>(null);
688
+ const activeResizeCleanupRef = useRef<(() => void) | null>(null);
598
689
 
599
- const { text, isLoading: docLoading, documentFields, documentId } = useDocumentContent();
690
+ const { text, isLoading: docLoading, documentFields, documentId, documentType } = useDocumentContent();
600
691
  const { apiUrl } = useConfig();
601
692
 
602
693
  // Resolve which Sanity dataset (= MJH publication) to read from. Each Studio
@@ -609,6 +700,14 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
609
700
  const workspace = useWorkspace();
610
701
  const effectivePublication = config.publication || workspace?.dataset;
611
702
 
703
+ // Studio origin + basePath - used to build "Inside Sanity" links that open a
704
+ // suggested article in a NEW Studio tab (leaving the editor's current tab alone).
705
+ const sanityBaseUrl = useMemo(() => {
706
+ if (typeof window === "undefined") return undefined;
707
+ const basePath = (workspace?.basePath || "/").replace(/\/+$/, "");
708
+ return `${window.location.origin}${basePath}`;
709
+ }, [workspace?.basePath]);
710
+
612
711
  const seedCacheKey = documentId ? `seo-copilot-cache-${documentId}` : "seo-copilot-cache-v2";
613
712
  const loadSeedsFromCache = useCallback((): string[] => {
614
713
  try {
@@ -632,6 +731,9 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
632
731
  // Per-doc state - persisted under doc-scoped keys so a return to the doc restores everything
633
732
  const selectedPrimaryKey = documentId ? `seo-copilot-primary-${documentId}` : "seo-copilot-primary-default";
634
733
  const [selectedPrimary, setSelectedPrimary] = usePersistentState<string | undefined>(selectedPrimaryKey, undefined);
734
+ // Optional secondary target keyword - audits check the article against both.
735
+ const selectedSecondaryKey = documentId ? `seo-copilot-secondary-${documentId}` : "seo-copilot-secondary-default";
736
+ const [selectedSecondary, setSelectedSecondary] = usePersistentState<string>(selectedSecondaryKey, "");
635
737
 
636
738
  // Reload seed cache when documentId changes (Sanity may reuse the inspector instance)
637
739
  const seedsInitializedRef = useRef(false);
@@ -657,6 +759,14 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
657
759
  // Effective primary (matches PanelContent's resolution)
658
760
  const effectivePrimary = selectedPrimary || keywordAnalysisState.analysis?.primaryKeyword?.term || "";
659
761
 
762
+ // Clear the secondary keyword if the user promotes it to primary - otherwise both
763
+ // slots hold the same term and all secondary-coverage audits produce false positives.
764
+ useEffect(() => {
765
+ if (selectedSecondary && effectivePrimary && selectedSecondary.toLowerCase() === effectivePrimary.toLowerCase()) {
766
+ setSelectedSecondary("");
767
+ }
768
+ }, [effectivePrimary, selectedSecondary, setSelectedSecondary]);
769
+
660
770
  // Build keyword panel data (consumed by chat). Lifted here so chat hook lives at top level.
661
771
  const keywordPanelData = useMemo(() => {
662
772
  const analysis = keywordAnalysisState.analysis;
@@ -687,6 +797,7 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
687
797
  const [isCSLoading, setIsCSLoading] = useState(false);
688
798
  const [csError, setCsError] = useState<string | null>(null);
689
799
  const aeoOpVersionRef = useRef(0);
800
+ const csAbortRef = useRef<AbortController | null>(null);
690
801
  // Only reset *transient* state on doc change. Persisted state is reloaded automatically
691
802
  // by usePersistentState when its key changes.
692
803
  const didInitAeoRef = useRef(false);
@@ -705,7 +816,11 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
705
816
  setIsCSLoading(true);
706
817
  setCsError(null);
707
818
  try {
708
- const data = await fetchContentSuggestions(apiUrl, text, effectivePrimary, effectivePublication);
819
+ csAbortRef.current?.abort(); const csController = new AbortController(); csAbortRef.current = csController;
820
+ const data = await fetchContentSuggestions(apiUrl, text, effectivePrimary, effectivePublication, csController.signal);
821
+ // This call was superseded by a newer one (e.g. rapid re-click). Bail silently so the
822
+ // aborted call's empty result does not flash a false "No suggestions returned" error.
823
+ if (csController.signal.aborted) return;
709
824
  if (aeoOpVersionRef.current !== myVersion) return;
710
825
  if (
711
826
  data.keyTakeaways.length === 0 &&
@@ -733,6 +848,7 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
733
848
  // The article text at the moment we last fetched - used to flag stale suggestions.
734
849
  const [linkingFetchedText, setLinkingFetchedText] = useState("");
735
850
  const linkingVersionRef = useRef(0);
851
+ const linkingAbortRef = useRef<AbortController | null>(null);
736
852
  const didInitLinkingRef = useRef(false);
737
853
  // Tracks the keyword signature we last fetched for, so the auto-fetch effect can skip
738
854
  // re-fetching when persisted suggestions already cover the current doc. Declared here
@@ -752,11 +868,13 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
752
868
  }, [documentId]);
753
869
 
754
870
  const supportingKeywordsForLinking = useMemo(() => {
755
- return (keywordAnalysisState.analysis?.supportingKeywords || [])
871
+ const base = (keywordAnalysisState.analysis?.supportingKeywords || [])
756
872
  .map((kw) => kw.term)
757
- .filter(Boolean)
758
- .slice(0, 5);
759
- }, [keywordAnalysisState.analysis]);
873
+ .filter(Boolean);
874
+ // Lead with the user's chosen secondary keyword so Linking weights it too.
875
+ const merged = selectedSecondary ? [selectedSecondary, ...base.filter((t) => t.toLowerCase() !== selectedSecondary.toLowerCase())] : base;
876
+ return merged.slice(0, 5);
877
+ }, [keywordAnalysisState.analysis, selectedSecondary]);
760
878
 
761
879
  const refreshLinkingSuggestions = useCallback(async () => {
762
880
  if (!text || text.trim().length < 50) return;
@@ -765,14 +883,19 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
765
883
  setIsLinkingLoading(true);
766
884
  setLinkingError(null);
767
885
  try {
886
+ linkingAbortRef.current?.abort(); const linkingController = new AbortController(); linkingAbortRef.current = linkingController;
768
887
  const suggestions = await fetchLinkingSuggestions(
769
888
  apiUrl,
770
889
  text,
771
890
  effectivePrimary,
772
891
  supportingKeywordsForLinking,
773
892
  documentId,
774
- effectivePublication
893
+ effectivePublication,
894
+ linkingController.signal
775
895
  );
896
+ // Superseded by a newer fetch (e.g. rapid re-click). Bail before the aborted call's
897
+ // empty result overwrites the good persisted suggestions.
898
+ if (linkingController.signal.aborted) return;
776
899
  if (linkingVersionRef.current !== myVersion) return;
777
900
  setLinkingSuggestions(suggestions);
778
901
  setLinkingFetchedText(text);
@@ -853,6 +976,16 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
853
976
  setIsLinkCheckLoading(false);
854
977
  }, [apiUrl, documentFields?.bodyLinks, setHasRunLinkCheck, setLinkCheckResults]);
855
978
 
979
+ // Cleanup any active drag/resize listeners if the component unmounts mid-gesture.
980
+ useEffect(() => {
981
+ return () => {
982
+ activeDragCleanupRef.current?.();
983
+ activeResizeCleanupRef.current?.();
984
+ csAbortRef.current?.abort();
985
+ linkingAbortRef.current?.abort();
986
+ };
987
+ }, []);
988
+
856
989
  const handleDragStart = useCallback(
857
990
  (e: React.MouseEvent) => {
858
991
  dragOffset.current = {
@@ -868,6 +1001,7 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
868
1001
  });
869
1002
  };
870
1003
  const onMouseUp = () => {
1004
+ activeDragCleanupRef.current = null;
871
1005
  dragOffset.current = null;
872
1006
  window.removeEventListener("mousemove", onMouseMove);
873
1007
  window.removeEventListener("mouseup", onMouseUp);
@@ -878,6 +1012,12 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
878
1012
  document.body.style.userSelect = "none";
879
1013
  window.addEventListener("mousemove", onMouseMove);
880
1014
  window.addEventListener("mouseup", onMouseUp);
1015
+ activeDragCleanupRef.current = () => {
1016
+ window.removeEventListener("mousemove", onMouseMove);
1017
+ window.removeEventListener("mouseup", onMouseUp);
1018
+ document.body.style.cursor = "";
1019
+ document.body.style.userSelect = "";
1020
+ };
881
1021
  },
882
1022
  [floatPos]
883
1023
  );
@@ -896,6 +1036,7 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
896
1036
  setFloatSize({ width: newW, height: newH });
897
1037
  };
898
1038
  const onMouseUp = () => {
1039
+ activeResizeCleanupRef.current = null;
899
1040
  resizeStart.current = null;
900
1041
  document.body.style.cursor = "";
901
1042
  document.body.style.userSelect = "";
@@ -904,6 +1045,12 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
904
1045
  };
905
1046
  window.addEventListener("mousemove", onMouseMove);
906
1047
  window.addEventListener("mouseup", onMouseUp);
1048
+ activeResizeCleanupRef.current = () => {
1049
+ window.removeEventListener("mousemove", onMouseMove);
1050
+ window.removeEventListener("mouseup", onMouseUp);
1051
+ document.body.style.cursor = "";
1052
+ document.body.style.userSelect = "";
1053
+ };
907
1054
  },
908
1055
  [floatSize]
909
1056
  );
@@ -928,8 +1075,12 @@ function SEOCopilotInner({ config, onClose }: { config: SEOCopilotConfig; onClos
928
1075
  docLoading={docLoading}
929
1076
  documentFields={documentFields}
930
1077
  documentId={documentId}
1078
+ documentType={documentType}
1079
+ sanityBaseUrl={sanityBaseUrl}
931
1080
  selectedPrimary={selectedPrimary}
932
1081
  onSelectPrimary={setSelectedPrimary}
1082
+ selectedSecondary={selectedSecondary}
1083
+ onSelectSecondary={setSelectedSecondary}
933
1084
  activeTab={activeTab}
934
1085
  onActiveTabChange={setActiveTab}
935
1086
  chatOpen={chatOpen}
@@ -65,6 +65,10 @@ export function ShimmerLoader({
65
65
  style.dataset.seoCopilotKeyframes = "1";
66
66
  style.innerHTML = KEYFRAMES;
67
67
  document.head.appendChild(style);
68
+ return () => {
69
+ try { document.head.removeChild(style); } catch { /* already removed */ }
70
+ keyframesInjected = false;
71
+ };
68
72
  }
69
73
  }, []);
70
74
 
@@ -185,6 +185,9 @@ export function TabBar({ tabs, activeTab, onTabChange }: TabBarProps) {
185
185
  const duration = Math.min(560, Math.max(280, Math.round(250 + dist * 0.6)));
186
186
  return { ...next, ready: true, duration };
187
187
  });
188
+ return () => {
189
+ if (clickTimerRef.current) clearTimeout(clickTimerRef.current);
190
+ };
188
191
  }, [activeTab, signature]);
189
192
 
190
193
  // Re-measure when the bar resizes (panel resize -> tabs may reflow / wrap).
@@ -30,6 +30,14 @@ export const INJECTED_CSS = `
30
30
  0%, 100% { opacity: 0.5; }
31
31
  50% { opacity: 1; }
32
32
  }
33
+ @keyframes onboard-in {
34
+ from { opacity: 0; transform: translateY(-6px) scale(0.97); }
35
+ to { opacity: 1; transform: translateY(0) scale(1); }
36
+ }
37
+ @keyframes onboard-out {
38
+ from { opacity: 1; transform: translateY(0) scale(1); }
39
+ to { opacity: 0; transform: translateY(-6px) scale(0.97); }
40
+ }
33
41
  .prose-chat { font-size: 12.5px; line-height: 1.65; color: #475569; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif; }
34
42
  .prose-chat h1 { font-size: 14px; font-weight: 700; color: #1e293b; margin: 10px 0 5px 0; line-height: 1.35; }
35
43
  .prose-chat h2, .prose-chat h3 { font-size: 13px; font-weight: 700; color: #1e293b; margin: 10px 0 5px 0; line-height: 1.35; }
@@ -1,4 +1,4 @@
1
- import { useMemo, useState } from "react";
1
+ import { useEffect, useMemo, useRef, useState } from "react";
2
2
  import { LoadingBars } from "../SEOCopilotPanel";
3
3
  import { FeedbackButton } from "../FeedbackButton";
4
4
  import { analyzeGEO } from "../../lib/geoAnalysis";
@@ -67,11 +67,13 @@ function SectionHeader({ label, iconColor, ai }: { label: string; iconColor: str
67
67
 
68
68
  function CopyButton({ text }: { text: string }) {
69
69
  const [copied, setCopied] = useState(false);
70
+ const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
71
+ useEffect(() => { return () => { if (copyTimerRef.current) clearTimeout(copyTimerRef.current); }; }, []);
70
72
  const handleCopy = async () => {
71
73
  try {
72
74
  await navigator.clipboard.writeText(text);
73
75
  setCopied(true);
74
- setTimeout(() => setCopied(false), 1500);
76
+ copyTimerRef.current = setTimeout(() => setCopied(false), 1500);
75
77
  } catch {
76
78
  // silent
77
79
  }
@@ -3,6 +3,7 @@ import { FeedbackButton } from "../FeedbackButton";
3
3
  import { ScoreDonut, ScoreDonutLegend } from "../ScoreDonut";
4
4
  import { MJH_BLUE } from "../styles";
5
5
  import type { SEOAnalysis, LinkingSuggestion } from "../../lib/types";
6
+ import { KNOWN_MJH_PUBLICATIONS } from "../../lib/utils";
6
7
 
7
8
  interface LinkingTabProps {
8
9
  analysis: SEOAnalysis | null;
@@ -15,6 +16,65 @@ interface LinkingTabProps {
15
16
  text?: string;
16
17
  documentId?: string;
17
18
  publication?: string;
19
+ /** Studio origin + basePath (e.g. https://host/studio). When present, each suggestion
20
+ * gets an "Inside Sanity" link that opens that article in a new Studio tab. */
21
+ sanityBaseUrl?: string;
22
+ /** Schema type of the current document, used to build the Sanity edit-intent link. */
23
+ documentType?: string;
24
+ }
25
+
26
+ // Build the public, reader-facing URL for a suggested article. Only constructed for
27
+ // known MJH publications (verified via CDN probe to use www.{pub}.com/view/{slug}).
28
+ // Returns null for unknown publications rather than risking a broken link.
29
+ function buildLiveUrl(publication?: string, slug?: string): string | null {
30
+ if (!slug) return null;
31
+ const pub = (publication || "").trim().toLowerCase();
32
+ if (!KNOWN_MJH_PUBLICATIONS.has(pub)) return null;
33
+ const cleanSlug = slug.replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
34
+ return `https://www.${pub}.com/view/${cleanSlug}`;
35
+ }
36
+
37
+ // Build a Sanity Studio edit-intent URL that opens the article in a NEW Studio tab,
38
+ // leaving the editor's current tab undisturbed. id-only intent resolves the type
39
+ // itself, but we include type when we know it for a cleaner resolve.
40
+ function buildSanityUrl(baseUrl?: string, id?: string, type?: string): string | null {
41
+ if (!baseUrl || !id) return null;
42
+ const cleanId = id.replace(/^drafts\./, "");
43
+ const base = baseUrl.replace(/\/+$/, "");
44
+ const typePart = type ? `;type=${encodeURIComponent(type)}` : "";
45
+ return `${base}/intent/edit/id=${encodeURIComponent(cleanId)}${typePart}/`;
46
+ }
47
+
48
+ // Small outbound-link chip - both targets open in a new tab so the editor's current
49
+ // work is never disturbed.
50
+ function LinkChip({ href, label, color }: { href: string; label: string; color: string }) {
51
+ return (
52
+ <a
53
+ href={href}
54
+ target="_blank"
55
+ rel="noopener noreferrer"
56
+ style={{
57
+ display: "inline-flex",
58
+ alignItems: "center",
59
+ gap: 4,
60
+ padding: "3px 9px",
61
+ borderRadius: 99,
62
+ fontSize: 10.5,
63
+ fontWeight: 700,
64
+ color,
65
+ background: "rgba(255,255,255,0.7)",
66
+ border: `1px solid ${color}33`,
67
+ textDecoration: "none",
68
+ lineHeight: 1.2,
69
+ }}
70
+ >
71
+ {label}
72
+ <svg width="9" height="9" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
73
+ <path d="M12.5 2a.75.75 0 000 1.5h2.44l-6.97 6.97a.75.75 0 101.06 1.06L16 4.56V7a.75.75 0 001.5 0V2.75A.75.75 0 0016.75 2H12.5z" />
74
+ <path d="M4.75 4.5A2.75 2.75 0 002 7.25v8A2.75 2.75 0 004.75 18h8A2.75 2.75 0 0015.5 15.25v-3a.75.75 0 00-1.5 0v3c0 .69-.56 1.25-1.25 1.25h-8c-.69 0-1.25-.56-1.25-1.25v-8c0-.69.56-1.25 1.25-1.25h3a.75.75 0 000-1.5h-3z" />
75
+ </svg>
76
+ </a>
77
+ );
18
78
  }
19
79
 
20
80
  const cardStyle: React.CSSProperties = {
@@ -87,6 +147,7 @@ function freshnessChip(label: LinkingSuggestion["freshnessLabel"], score: number
87
147
  "very-old": { bg: "rgba(220,38,38,0.1)", color: "#dc2626", text: "Very old" },
88
148
  } as const;
89
149
  const c = map[label];
150
+ if (!c) return null;
90
151
  return (
91
152
  <span
92
153
  style={{
@@ -126,12 +187,14 @@ export function LinkingTab({
126
187
  text,
127
188
  documentId,
128
189
  publication,
190
+ sanityBaseUrl,
191
+ documentType,
129
192
  }: LinkingTabProps) {
130
193
  if (!analysis) {
131
194
  return (
132
195
  <div style={{ padding: 24, textAlign: "center" }}>
133
- <div style={{ fontSize: 13, color: "#4b5563", fontWeight: 500 }}>Run keyword analysis first</div>
134
- <div style={{ fontSize: 11, color: "#4b5563", marginTop: 4 }}>Internal link suggestions need keywords to start from</div>
196
+ <div style={{ fontSize: 13, color: "#4b5563", fontWeight: 500 }}>Waiting for keyword analysis</div>
197
+ <div style={{ fontSize: 11, color: "#4b5563", marginTop: 4 }}>Linking reads the article keywords and topic to find related published articles. It starts on its own once the Keywords tab finishes.</div>
135
198
  </div>
136
199
  );
137
200
  }
@@ -185,7 +248,10 @@ export function LinkingTab({
185
248
  {/* Stale banner - article changed since these were generated */}
186
249
  {isStale && suggestions.length > 0 && !isLoading && (
187
250
  <div
251
+ role="button"
252
+ tabIndex={0}
188
253
  onClick={onRefresh}
254
+ onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onRefresh(); } }}
189
255
  style={{
190
256
  display: "flex",
191
257
  alignItems: "center",
@@ -252,9 +318,9 @@ export function LinkingTab({
252
318
  {/* Empty - no error, just nothing matched. */}
253
319
  {!isLoading && !error && suggestions.length === 0 && (
254
320
  <div style={{ fontSize: 11, color: "#1f2937", padding: "10px 12px", lineHeight: 1.55, background: "rgba(0,93,172,0.04)", borderRadius: 8, border: "1px solid rgba(0,93,172,0.12)" }}>
255
- <div style={{ fontWeight: 700, marginBottom: 4, color: "#1f2937" }}>No related articles found yet.</div>
321
+ <div style={{ fontWeight: 700, marginBottom: 4, color: "#1f2937" }}>No closely related articles found.</div>
256
322
  <div style={{ color: "#4b5563" }}>
257
- Linking suggests published articles on closely related topics. As more related content is published, matches will appear here.
323
+ Linking searched your publication for articles on this topic and did not find a strong match. As more related content is published, suggestions will appear here.
258
324
  </div>
259
325
  </div>
260
326
  )}
@@ -276,10 +342,10 @@ export function LinkingTab({
276
342
  >
277
343
  <ScoreDonut
278
344
  size={64}
279
- topic={s.topicScore}
280
- freshness={s.freshnessScore}
281
- sectionFit={s.sectionFitScore}
282
- composite={s.compositeScore}
345
+ topic={Math.max(0, Math.min(100, s.topicScore))}
346
+ freshness={Math.max(0, Math.min(100, s.freshnessScore))}
347
+ sectionFit={Math.max(0, Math.min(100, s.sectionFitScore))}
348
+ composite={Math.max(0, Math.min(100, s.compositeScore))}
283
349
  />
284
350
  <div style={{ flex: 1, minWidth: 0 }}>
285
351
  <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 3, flexWrap: "wrap" }}>
@@ -294,6 +360,17 @@ export function LinkingTab({
294
360
  <div style={{ fontSize: 10, color: "#4b5563", fontFamily: "ui-monospace, SFMono-Regular, monospace", marginBottom: 6 }}>
295
361
  /{s.slug}
296
362
  </div>
363
+ {(() => {
364
+ const liveUrl = buildLiveUrl(publication, s.slug);
365
+ const sanityUrl = buildSanityUrl(sanityBaseUrl, s._id); // omit type - resolves by ID, suggested doc type differs from current
366
+ if (!liveUrl && !sanityUrl) return null;
367
+ return (
368
+ <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 6 }}>
369
+ {sanityUrl && <LinkChip href={sanityUrl} label="Inside Sanity" color={MJH_BLUE} />}
370
+ {liveUrl && <LinkChip href={liveUrl} label="Live site" color="#4b5563" />}
371
+ </div>
372
+ );
373
+ })()}
297
374
  {s.relevanceReason && (
298
375
  <div style={{ fontSize: 11, color: "#1f2937", marginBottom: 6, lineHeight: 1.45 }}>
299
376
  <span style={{ fontWeight: 700, color: "#4b5563" }}>Why it fits:</span>{" "}