sanity-plugin-seo-copilot 0.2.7 → 0.2.11

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.
package/dist/index.mjs CHANGED
@@ -5,7 +5,7 @@ import { definePlugin } from "sanity";
5
5
  import { createElement } from "react";
6
6
 
7
7
  // src/components/SEOCopilotPanel.tsx
8
- import { useState as useState16, useRef as useRef10, useCallback as useCallback5, useEffect as useEffect10, useMemo as useMemo5, Suspense } from "react";
8
+ import { useState as useState16, useRef as useRef11, useCallback as useCallback5, useEffect as useEffect11, useMemo as useMemo5, Suspense } from "react";
9
9
  import { useWorkspace } from "sanity";
10
10
  import { createPortal } from "react-dom";
11
11
 
@@ -134,8 +134,8 @@ function detectAuthor(val) {
134
134
  }
135
135
  if (typeof first === "object" && first !== null) {
136
136
  const o = first;
137
- const name = o.name || o.fullName || o.displayName;
138
- const creds = o.credentials || o.title || o.suffix;
137
+ const name = [o.name, o.fullName, o.displayName].find((v) => typeof v === "string" && v.trim().length > 0);
138
+ const creds = [o.credentials, o.title, o.suffix].find((v) => typeof v === "string" && v.trim().length > 0);
139
139
  const slug = o.slug?.current;
140
140
  const bio = o.bioUrl || (slug ? `/author/${slug}` : void 0);
141
141
  if (name) {
@@ -183,14 +183,14 @@ function extractImageMeta(value) {
183
183
  }
184
184
  function buildDocumentFields(value) {
185
185
  const val = value;
186
- const title = val?.title;
186
+ const title = typeof val?.title === "string" ? val.title : void 0;
187
187
  const body = val?.body;
188
188
  const { authorName, authorCredentials, authorBioUrl, authorIsReference } = detectAuthor(val);
189
189
  const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
190
190
  return {
191
191
  title: title || void 0,
192
192
  // MJH uses `summary`; standard Sanity SEO plugins use `metaDescription`
193
- metaDescription: val?.metaDescription || val?.summary || val?.description || val?.seoDescription,
193
+ metaDescription: [val?.metaDescription, val?.summary, val?.description, val?.seoDescription].find((v) => typeof v === "string" && v.trim().length > 0),
194
194
  slug: detectSlug(val),
195
195
  imageNames: imageMeta.names,
196
196
  imageTitles: imageMeta.titles,
@@ -198,18 +198,18 @@ function buildDocumentFields(value) {
198
198
  headings: extractHeadings(body),
199
199
  headingsDetailed: extractHeadingsDetailed(body),
200
200
  bodyLinks: extractBodyLinks(body),
201
- contentCategory: val?.contentCategory || val?.category,
201
+ contentCategory: typeof val?.contentCategory === "string" ? val.contentCategory : typeof val?.category === "string" ? val.category : void 0,
202
202
  contentPlacement: Array.isArray(val?.contentPlacement) ? val.contentPlacement : void 0,
203
203
  authorName,
204
204
  authorCredentials,
205
205
  authorBioUrl,
206
206
  authorIsReference,
207
207
  // `published` is MJH's date field; `publishedAt`/`publishDate` cover other schemas
208
- publishedAt: val?.published || val?.publishedAt || val?.publishDate || val?._createdAt,
208
+ publishedAt: [val?.publishedAt, val?.publishDate, val?.published, val?._createdAt].find((v) => typeof v === "string" && v.trim().length > 0),
209
209
  // `updatedOn` is MJH's "Updated On" field. `updatedAt` is the standard Sanity convention.
210
210
  // `_updatedAt` is the Sanity-managed timestamp as a final fallback.
211
- updatedAt: val?.updatedOn || val?.updatedAt || val?._updatedAt,
212
- lastReviewedAt: val?.lastReviewedAt || val?.lastReviewed || val?.medicallyReviewedAt
211
+ updatedAt: [val?.updatedOn, val?.updatedAt, val?._updatedAt].find((v) => typeof v === "string" && v.trim().length > 0),
212
+ lastReviewedAt: [val?.lastReviewedAt, val?.lastReviewed, val?.medicallyReviewedAt].find((v) => typeof v === "string" && v.trim().length > 0)
213
213
  };
214
214
  }
215
215
 
@@ -278,7 +278,6 @@ async function fetchAnalysis(apiUrl, content, mode, publication, seedKeywords, d
278
278
  const text = await response.text();
279
279
  if (!response.ok) {
280
280
  const err = safeParseJson(text);
281
- console.error("[seo-copilot] analyze error", response.status, err.error);
282
281
  if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
283
282
  if (response.status >= 500) throw new Error("Could not reach the SEO service.");
284
283
  throw new Error("Something went wrong analyzing this document.");
@@ -294,7 +293,6 @@ async function fetchChatStream(apiUrl, messages, documentContext, publication, k
294
293
  });
295
294
  if (!response.ok) {
296
295
  const err = await response.json().catch(() => ({ error: "Request failed" }));
297
- console.error("[seo-copilot] chat error", response.status, err.error);
298
296
  if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
299
297
  if (response.status >= 500) throw new Error("Could not reach the SEO service.");
300
298
  throw new Error("Something went wrong. Please try again.");
@@ -317,7 +315,6 @@ async function lookupKeywords(apiUrl, keywords, signal) {
317
315
  });
318
316
  if (!response.ok) {
319
317
  const err = await response.json().catch(() => ({ error: "Request failed" }));
320
- console.error("[seo-copilot] keywords error", response.status, err.error);
321
318
  if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
322
319
  if (response.status >= 500) throw new Error("Could not reach the SEO service.");
323
320
  throw new Error("Something went wrong. Please try again.");
@@ -336,13 +333,14 @@ async function loadChatHistory(apiUrl, userId, documentId) {
336
333
  return [];
337
334
  }
338
335
  }
339
- async function fetchContentSuggestions(apiUrl, content, primaryKeyword, publication) {
336
+ async function fetchContentSuggestions(apiUrl, content, primaryKeyword, publication, signal) {
340
337
  const empty = { keyTakeaways: [], infographicOpportunities: [], bulletListItems: [] };
341
338
  try {
342
339
  const res = await fetch(`${apiUrl}/api/seo-copilot/content-suggestions`, {
343
340
  method: "POST",
344
341
  headers: { "Content-Type": "application/json" },
345
- body: JSON.stringify({ content, primaryKeyword, publication })
342
+ body: JSON.stringify({ content, primaryKeyword, publication }),
343
+ signal
346
344
  });
347
345
  if (!res.ok) return empty;
348
346
  const data = await res.json().catch(() => null);
@@ -356,13 +354,14 @@ async function fetchContentSuggestions(apiUrl, content, primaryKeyword, publicat
356
354
  return empty;
357
355
  }
358
356
  }
359
- async function fetchLinkingSuggestions(apiUrl, content, primaryKeyword, supportingKeywords, currentDocumentId, publication) {
357
+ async function fetchLinkingSuggestions(apiUrl, content, primaryKeyword, supportingKeywords, currentDocumentId, publication, signal) {
360
358
  if (!content || content.trim().length < 50) return [];
361
359
  try {
362
360
  const res = await fetch(`${apiUrl}/api/seo-copilot/linking-suggestions`, {
363
361
  method: "POST",
364
362
  headers: { "Content-Type": "application/json" },
365
- body: JSON.stringify({ content, primaryKeyword, supportingKeywords, currentDocumentId, publication })
363
+ body: JSON.stringify({ content, primaryKeyword, supportingKeywords, currentDocumentId, publication }),
364
+ signal
366
365
  });
367
366
  if (!res.ok) return [];
368
367
  const data = await res.json().catch(() => null);
@@ -459,6 +458,8 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
459
458
  docVersionRef.current += 1;
460
459
  volumeAbortRef.current?.abort();
461
460
  volumeAbortRef.current = null;
461
+ deepAbortRef.current?.abort();
462
+ deepAbortRef.current = null;
462
463
  const fresh = loadCached();
463
464
  cached.current = fresh;
464
465
  setAnalysisRaw(fresh.analysis);
@@ -497,46 +498,11 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
497
498
  const lastAnalysisRef = useRef2(null);
498
499
  const docVersionRef = useRef2(0);
499
500
  const volumeAbortRef = useRef2(null);
500
- useEffect2(() => {
501
- if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
502
- setAnalysis(null);
503
- return;
504
- }
505
- let cancelled = false;
506
- const controller = new AbortController();
507
- setIsLoading(true);
508
- setError(null);
509
- fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary, controller.signal).then((result) => {
510
- if (cancelled) return;
511
- const analysisResult = result;
512
- lastAnalysisRef.current = analysisResult;
513
- setAnalysis(analysisResult);
514
- setIsLoading(false);
515
- const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
516
- const allTerms = [
517
- .../* @__PURE__ */ new Set([
518
- ...candidateTerms,
519
- analysisResult.primaryKeyword.term,
520
- ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
521
- ...analysisResult.missingKeywords.map((kw) => kw.term)
522
- ])
523
- ];
524
- const uncachedTerms = allTerms.filter((t) => !volumeMapRef.current.has(t.toLowerCase()));
525
- if (uncachedTerms.length > 0) {
526
- doVolumeLookup(analysisResult, uncachedTerms);
527
- }
528
- }).catch((err) => {
529
- if (err instanceof Error && err.name === "AbortError") return;
530
- if (!cancelled) {
531
- setError(err.message);
532
- setIsLoading(false);
533
- }
534
- });
535
- return () => {
536
- cancelled = true;
537
- controller.abort();
538
- };
539
- }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, JSON.stringify(documentFields)]);
501
+ const deepAbortRef = useRef2(null);
502
+ useEffect2(() => () => {
503
+ volumeAbortRef.current?.abort();
504
+ deepAbortRef.current?.abort();
505
+ }, []);
540
506
  const doVolumeLookup = useCallback((analysisResult, terms) => {
541
507
  setIsVolumesLoading(true);
542
508
  const myVersion = docVersionRef.current;
@@ -577,6 +543,50 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
577
543
  setIsVolumesLoading(false);
578
544
  });
579
545
  }, [apiUrl, cacheKey]);
546
+ const doVolumeLookupRef = useRef2(doVolumeLookup);
547
+ useEffect2(() => {
548
+ doVolumeLookupRef.current = doVolumeLookup;
549
+ }, [doVolumeLookup]);
550
+ useEffect2(() => {
551
+ if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
552
+ setAnalysis(null);
553
+ return;
554
+ }
555
+ let cancelled = false;
556
+ const controller = new AbortController();
557
+ setIsLoading(true);
558
+ setError(null);
559
+ fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary, controller.signal).then((result) => {
560
+ if (cancelled) return;
561
+ const analysisResult = result;
562
+ lastAnalysisRef.current = analysisResult;
563
+ setAnalysis(analysisResult);
564
+ setIsLoading(false);
565
+ const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
566
+ const allTerms = [
567
+ .../* @__PURE__ */ new Set([
568
+ ...candidateTerms,
569
+ analysisResult.primaryKeyword.term,
570
+ ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
571
+ ...analysisResult.missingKeywords.map((kw) => kw.term)
572
+ ])
573
+ ];
574
+ const uncachedTerms = allTerms.filter((t) => !volumeMapRef.current.has(t.toLowerCase()));
575
+ if (uncachedTerms.length > 0) {
576
+ doVolumeLookupRef.current(analysisResult, uncachedTerms);
577
+ }
578
+ }).catch((err) => {
579
+ if (err instanceof Error && err.name === "AbortError") return;
580
+ if (!cancelled) {
581
+ setError(err.message);
582
+ setIsLoading(false);
583
+ }
584
+ });
585
+ return () => {
586
+ cancelled = true;
587
+ controller.abort();
588
+ };
589
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, JSON.stringify(documentFields)]);
580
590
  const refreshVolumes = useCallback(() => {
581
591
  const current = lastAnalysisRef.current || analysis;
582
592
  if (!current) return;
@@ -589,16 +599,20 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
589
599
  setAeoContentChanged(false);
590
600
  setAeoTextSnapshot(text);
591
601
  const myVersion = docVersionRef.current;
592
- fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary).then((result) => {
602
+ deepAbortRef.current?.abort();
603
+ const deepController = new AbortController();
604
+ deepAbortRef.current = deepController;
605
+ fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary, deepController.signal).then((result) => {
593
606
  if (docVersionRef.current !== myVersion) return;
594
607
  setDeepAnalysis(result);
595
608
  setIsDeepLoading(false);
596
609
  }).catch((err) => {
610
+ if (deepController.signal.aborted || err?.name === "AbortError") return;
597
611
  if (docVersionRef.current !== myVersion) return;
598
612
  setError(err.message);
599
613
  setIsDeepLoading(false);
600
614
  });
601
- }, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields]);
615
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields, focusPrimary]);
602
616
  return {
603
617
  analysis,
604
618
  isLoading,
@@ -616,6 +630,7 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
616
630
  import { useState as useState3, useCallback as useCallback2, useEffect as useEffect3, useRef as useRef3 } from "react";
617
631
  import { useCurrentUser } from "sanity";
618
632
  function getLocalUserId() {
633
+ if (typeof window === "undefined") return "anonymous";
619
634
  const key = "seo-copilot-user-id";
620
635
  try {
621
636
  let id = localStorage.getItem(key);
@@ -668,6 +683,7 @@ function useSEOChat(apiUrl, documentText, publication, keywordPanelData, documen
668
683
  useEffect3(() => {
669
684
  return () => {
670
685
  streamAbortRef.current?.abort();
686
+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
671
687
  };
672
688
  }, []);
673
689
  const saveTimerRef = useRef3(null);
@@ -1152,6 +1168,12 @@ function FeedbackButton({ suggestionType, suggestionText, documentId, publicatio
1152
1168
  const [submitted, setSubmitted] = useState6(false);
1153
1169
  const popupRef = useRef5(null);
1154
1170
  const inputRef = useRef5(null);
1171
+ const submitTimerRef = useRef5(null);
1172
+ useEffect4(() => {
1173
+ return () => {
1174
+ if (submitTimerRef.current) clearTimeout(submitTimerRef.current);
1175
+ };
1176
+ }, []);
1155
1177
  useEffect4(() => {
1156
1178
  if (!showReasonPopup) return;
1157
1179
  const handler = (e) => {
@@ -1218,7 +1240,7 @@ function FeedbackButton({ suggestionType, suggestionText, documentId, publicatio
1218
1240
  }
1219
1241
  }
1220
1242
  setSubmitted(true);
1221
- setTimeout(() => {
1243
+ submitTimerRef.current = setTimeout(() => {
1222
1244
  setShowReasonPopup(false);
1223
1245
  setReason("");
1224
1246
  }, 1e3);
@@ -1424,11 +1446,13 @@ function buildSuggestedKeywords(supporting, missing, documentText, documentField
1424
1446
  const merged = [];
1425
1447
  const lowerText = documentText.toLowerCase();
1426
1448
  for (const kw of supporting) {
1449
+ if (kw == null || typeof kw.term !== "string") continue;
1427
1450
  const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
1428
1451
  const livePlacement = computePlacementClient(kw.term, documentText, documentFields);
1429
1452
  merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, placement: livePlacement });
1430
1453
  }
1431
1454
  for (const kw of missing) {
1455
+ if (kw == null || typeof kw.term !== "string") continue;
1432
1456
  const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
1433
1457
  const livePlacement = computePlacementClient(kw.term, documentText, documentFields);
1434
1458
  merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, reason: kw.reason, placement: livePlacement });
@@ -1697,7 +1721,7 @@ function SecondaryKeywordSelector({
1697
1721
  setCustomInputOpen(false);
1698
1722
  }
1699
1723
  };
1700
- const opts = selectedTerm && !options.some((o) => o.term === selectedTerm) ? [...options, { term: selectedTerm, volume: null }] : options;
1724
+ const opts = selectedTerm && !options.some((o) => o.term.toLowerCase() === selectedTerm.toLowerCase()) ? [...options, { term: selectedTerm, volume: null }] : options;
1701
1725
  return /* @__PURE__ */ jsxs4("div", { style: cardStyle, children: [
1702
1726
  /* @__PURE__ */ jsx5(
1703
1727
  SectionHeader,
@@ -1807,8 +1831,8 @@ function computePlacementClient(term, content, fields) {
1807
1831
  const lower = term.toLowerCase();
1808
1832
  return {
1809
1833
  inBody: content.toLowerCase().includes(lower),
1810
- inTitle: fields?.title?.toLowerCase().includes(lower) ?? false,
1811
- inMetaDescription: fields?.metaDescription?.toLowerCase().includes(lower) ?? false,
1834
+ inTitle: typeof fields?.title === "string" ? fields.title.toLowerCase().includes(lower) : false,
1835
+ inMetaDescription: typeof fields?.metaDescription === "string" ? fields.metaDescription.toLowerCase().includes(lower) : false,
1812
1836
  inImages: fields?.imageNames?.some((name) => name.toLowerCase().includes(lower)) ?? false,
1813
1837
  inUrl: fields?.slug?.toLowerCase().includes(lower) ?? false
1814
1838
  };
@@ -1878,7 +1902,9 @@ function SuggestedKeywordsCard({
1878
1902
  const res = await fetch(`${apiUrl}/api/seo-copilot/keyword-help`, {
1879
1903
  method: "POST",
1880
1904
  headers: { "Content-Type": "application/json" },
1881
- body: JSON.stringify({ keyword: term, content: text, publication, previousSuggestions })
1905
+ // Clip to 5,000 chars: the backend only reads the first 4,000 anyway, so sending
1906
+ // the full article needlessly bloats the request on long pieces.
1907
+ body: JSON.stringify({ keyword: term, content: text.slice(0, 5e3), publication, previousSuggestions })
1882
1908
  });
1883
1909
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
1884
1910
  const data = await res.json();
@@ -2301,8 +2327,9 @@ function KeywordPanel({
2301
2327
  const prevDefaultRef = useRef7(defaultSelectedTerm);
2302
2328
  useEffect6(() => {
2303
2329
  if (defaultSelectedTerm && defaultSelectedTerm !== prevDefaultRef.current) {
2304
- setSelectedPrimaryTerm((prev) => prev === prevDefaultRef.current ? defaultSelectedTerm : prev);
2330
+ const oldDefault = prevDefaultRef.current;
2305
2331
  prevDefaultRef.current = defaultSelectedTerm;
2332
+ setSelectedPrimaryTerm((prev) => prev === oldDefault ? defaultSelectedTerm : prev);
2306
2333
  }
2307
2334
  }, [defaultSelectedTerm]);
2308
2335
  if ((!text || text.trim().length < 20) && (!seedKeywords || seedKeywords.length === 0)) {
@@ -2336,10 +2363,12 @@ function KeywordPanel({
2336
2363
  placement: computePlacementClient(c.term, text, documentFields)
2337
2364
  }));
2338
2365
  const activeTerm = candidates.find((c) => c.term === selectedPrimaryTerm) ? selectedPrimaryTerm : candidates[0]?.term ?? "";
2366
+ const activeTermLower = activeTerm.toLowerCase();
2339
2367
  const secondaryOptions = [];
2340
2368
  const seenSecondary = /* @__PURE__ */ new Set();
2341
2369
  for (const c of candidates) {
2342
2370
  const key = c.term.toLowerCase();
2371
+ if (key === activeTermLower) continue;
2343
2372
  if (!seenSecondary.has(key)) {
2344
2373
  seenSecondary.add(key);
2345
2374
  secondaryOptions.push({ term: c.term, volume: c.volume });
@@ -2347,6 +2376,7 @@ function KeywordPanel({
2347
2376
  }
2348
2377
  for (const kw of suggestedKeywords) {
2349
2378
  const key = kw.term.toLowerCase();
2379
+ if (key === activeTermLower) continue;
2350
2380
  if (!seenSecondary.has(key)) {
2351
2381
  seenSecondary.add(key);
2352
2382
  secondaryOptions.push({ term: kw.term, volume: kw.volume });
@@ -2591,20 +2621,22 @@ function ChatPanel({ messages, isStreaming, sendMessage, clearChat, documentId }
2591
2621
  "button",
2592
2622
  {
2593
2623
  onClick: clearChat,
2594
- onMouseEnter: () => setClearHovered(true),
2624
+ onMouseEnter: () => !isStreaming && setClearHovered(true),
2595
2625
  onMouseLeave: () => setClearHovered(false),
2596
2626
  title: "Clear conversation",
2597
2627
  "aria-label": "Clear conversation",
2628
+ disabled: isStreaming,
2598
2629
  style: {
2599
2630
  background: "none",
2600
2631
  border: "none",
2601
- cursor: "pointer",
2632
+ cursor: isStreaming ? "not-allowed" : "pointer",
2602
2633
  padding: 4,
2603
2634
  display: "flex",
2604
2635
  alignItems: "center",
2605
- color: clearHovered ? "#ef4444" : "#9ca3af",
2636
+ color: isStreaming ? "#d1d5db" : clearHovered ? "#ef4444" : "#9ca3af",
2606
2637
  transition: "color 150ms",
2607
- flexShrink: 0
2638
+ flexShrink: 0,
2639
+ opacity: isStreaming ? 0.4 : 1
2608
2640
  },
2609
2641
  children: /* @__PURE__ */ jsx6("svg", { width: "14", height: "14", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx6("path", { fillRule: "evenodd", d: "M8.75 1A2.75 2.75 0 006 3.75v.443c-.795.077-1.584.176-2.365.298a.75.75 0 10.23 1.482l.149-.022.841 10.518A2.75 2.75 0 007.596 19h4.807a2.75 2.75 0 002.742-2.53l.841-10.519.149.023a.75.75 0 00.23-1.482A41.03 41.03 0 0014 4.193V3.75A2.75 2.75 0 0011.25 1h-2.5zM10 4c.84 0 1.673.025 2.5.075V3.75c0-.69-.56-1.25-1.25-1.25h-2.5c-.69 0-1.25.56-1.25 1.25v.325C8.327 4.025 9.16 4 10 4zM8.58 7.72a.75.75 0 00-1.5.06l.3 7.5a.75.75 0 101.5-.06l-.3-7.5zm4.34.06a.75.75 0 10-1.5-.06l-.3 7.5a.75.75 0 101.5.06l.3-7.5z", clipRule: "evenodd" }) })
2610
2642
  }
@@ -2783,6 +2815,9 @@ function TabBar({ tabs, activeTab, onTabChange }) {
2783
2815
  const duration = Math.min(560, Math.max(280, Math.round(250 + dist * 0.6)));
2784
2816
  return { ...next, ready: true, duration };
2785
2817
  });
2818
+ return () => {
2819
+ if (clickTimerRef.current) clearTimeout(clickTimerRef.current);
2820
+ };
2786
2821
  }, [activeTab, signature]);
2787
2822
  useEffect8(() => {
2788
2823
  const bar = barRef.current;
@@ -3022,7 +3057,7 @@ function OnboardingCard({ onDismiss, closing }) {
3022
3057
  backdropFilter: "blur(20px) saturate(170%)",
3023
3058
  WebkitBackdropFilter: "blur(20px) saturate(170%)",
3024
3059
  boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.55), inset 1.5px 2px 1px -1px rgba(255,255,255,0.9), 0 10px 30px rgba(0,93,172,0.22), 0 2px 8px rgba(0,0,0,0.12)",
3025
- animation: `${closing ? "onboard-out" : "onboard-in"} ${closing ? 180 : 240}ms ease-out forwards`
3060
+ animation: `${closing ? "onboard-out" : "onboard-in"} ${closing ? 200 : 240}ms ease-out forwards`
3026
3061
  },
3027
3062
  children: [
3028
3063
  /* @__PURE__ */ jsxs7("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 6 }, children: [
@@ -3031,7 +3066,7 @@ function OnboardingCard({ onDismiss, closing }) {
3031
3066
  "button",
3032
3067
  {
3033
3068
  onClick: onDismiss,
3034
- style: { background: "none", border: "none", cursor: "pointer", padding: 2, display: "flex", color: "#00468a", opacity: 0.7 },
3069
+ style: { background: "none", border: "none", cursor: "pointer", padding: 2, display: "flex", color: "#00468a", opacity: 1 },
3035
3070
  title: "Dismiss",
3036
3071
  "aria-label": "Dismiss",
3037
3072
  children: /* @__PURE__ */ jsx8("svg", { width: "14", height: "14", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ jsx8("path", { d: "M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z" }) })
@@ -3045,7 +3080,7 @@ function OnboardingCard({ onDismiss, closing }) {
3045
3080
  /* @__PURE__ */ jsx8("strong", { children: "Primary" }),
3046
3081
  " keyword (required) and, optionally, one ",
3047
3082
  /* @__PURE__ */ jsx8("strong", { children: "Secondary" }),
3048
- " keyword. Copilot then optimizes the whole article - title, meta, URL, headings, and images - toward both."
3083
+ " keyword. Copilot then optimizes its recommendations toward both."
3049
3084
  ] }),
3050
3085
  /* @__PURE__ */ jsx8(
3051
3086
  "button",
@@ -3122,6 +3157,13 @@ function ShimmerLoader({
3122
3157
  style.dataset.seoCopilotKeyframes = "1";
3123
3158
  style.innerHTML = KEYFRAMES;
3124
3159
  document.head.appendChild(style);
3160
+ return () => {
3161
+ try {
3162
+ document.head.removeChild(style);
3163
+ } catch {
3164
+ }
3165
+ keyframesInjected = false;
3166
+ };
3125
3167
  }
3126
3168
  }, []);
3127
3169
  useEffect9(() => {
@@ -3229,7 +3271,7 @@ function calculateContentScoreDetailed(content, analysis, documentFields) {
3229
3271
  }
3230
3272
  const supportingKws = analysis.supportingKeywords || [];
3231
3273
  if (supportingKws.length > 0) {
3232
- const inContentCount = supportingKws.filter((kw) => lowerContent.includes(kw.term.toLowerCase())).length;
3274
+ const inContentCount = supportingKws.filter((kw) => kw != null && typeof kw.term === "string" && lowerContent.includes(kw.term.toLowerCase())).length;
3233
3275
  const coverageRatio = inContentCount / supportingKws.length;
3234
3276
  const pts = Math.round(coverageRatio * 25);
3235
3277
  components.push({
@@ -3302,8 +3344,8 @@ function calculateContentScoreDetailed(content, analysis, documentFields) {
3302
3344
  return { total: Math.min(100, Math.max(0, total)), components };
3303
3345
  }
3304
3346
 
3305
- // src/lib/summary.ts
3306
- function tokensContain(haystack, needle) {
3347
+ // src/lib/utils.ts
3348
+ function containsKeywordTokens(haystack, needle) {
3307
3349
  if (!needle) return true;
3308
3350
  const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
3309
3351
  if (tokens.length === 0) return true;
@@ -3311,6 +3353,7 @@ function tokensContain(haystack, needle) {
3311
3353
  return tokens.every((t) => lower.includes(t));
3312
3354
  }
3313
3355
  function keywordLeadsSlug(slug, primaryKeyword) {
3356
+ if (!primaryKeyword) return true;
3314
3357
  const slugWords = slug.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);
3315
3358
  const tokens = primaryKeyword.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
3316
3359
  if (tokens.length === 0 || slugWords.length === 0) return true;
@@ -3321,6 +3364,15 @@ function keywordLeadsSlug(slug, primaryKeyword) {
3321
3364
  }
3322
3365
  return earliest <= 2;
3323
3366
  }
3367
+ var KNOWN_MJH_PUBLICATIONS = /* @__PURE__ */ new Set([
3368
+ "onclive",
3369
+ "hcplive",
3370
+ "ajmc",
3371
+ "pharmacytimes",
3372
+ "cancernetwork"
3373
+ ]);
3374
+
3375
+ // src/lib/summary.ts
3324
3376
  function isShortFormContent(documentFields, title) {
3325
3377
  const cat = (documentFields?.contentCategory || "").toLowerCase().trim();
3326
3378
  if (/^(videos?|podcasts?|episodes?|webinars?|video series|peer exchange)$/.test(cat)) return true;
@@ -3337,6 +3389,13 @@ function buildSummaryItems(input) {
3337
3389
  const { analysis, deepAnalysis, documentFields, linkingSuggestions, linkCheckResults, text } = input;
3338
3390
  const primaryKeyword = input.primaryKeyword || analysis?.primaryKeyword?.term;
3339
3391
  const secondaryKeyword = input.secondaryKeyword || "";
3392
+ const bodyText = (() => {
3393
+ if (!documentFields?.title) return text;
3394
+ if (!text.startsWith(documentFields.title)) return text;
3395
+ const rest = text.slice(documentFields.title.length);
3396
+ if (rest === "" || /^\s/.test(rest)) return rest.trimStart();
3397
+ return text;
3398
+ })();
3340
3399
  const title = documentFields?.title;
3341
3400
  if (!title) {
3342
3401
  items.push({
@@ -3349,7 +3408,7 @@ function buildSummaryItems(input) {
3349
3408
  jumpTo: { tab: "meta", anchorId: "anchor-meta-title" }
3350
3409
  });
3351
3410
  } else if (primaryKeyword) {
3352
- if (!tokensContain(title, primaryKeyword)) {
3411
+ if (!containsKeywordTokens(title, primaryKeyword)) {
3353
3412
  items.push({
3354
3413
  id: "meta-title-no-keyword",
3355
3414
  category: "meta",
@@ -3415,7 +3474,7 @@ function buildSummaryItems(input) {
3415
3474
  jumpTo: { tab: "meta", anchorId: "anchor-meta-description" }
3416
3475
  });
3417
3476
  }
3418
- if (primaryKeyword && !tokensContain(meta, primaryKeyword)) {
3477
+ if (primaryKeyword && !containsKeywordTokens(meta, primaryKeyword)) {
3419
3478
  items.push({
3420
3479
  id: "meta-desc-no-keyword",
3421
3480
  category: "meta",
@@ -3440,7 +3499,7 @@ function buildSummaryItems(input) {
3440
3499
  });
3441
3500
  } else {
3442
3501
  const slugAsWords = slug.replace(/-/g, " ");
3443
- if (primaryKeyword && !tokensContain(slugAsWords, primaryKeyword)) {
3502
+ if (primaryKeyword && !containsKeywordTokens(slugAsWords, primaryKeyword)) {
3444
3503
  items.push({
3445
3504
  id: "meta-slug-no-keyword",
3446
3505
  category: "meta",
@@ -3462,7 +3521,7 @@ function buildSummaryItems(input) {
3462
3521
  });
3463
3522
  }
3464
3523
  }
3465
- const wordCount2 = text ? text.trim().split(/\s+/).filter(Boolean).length : 0;
3524
+ const wordCount2 = bodyText ? bodyText.trim().split(/\s+/).filter(Boolean).length : 0;
3466
3525
  const isShortForm = isShortFormContent(documentFields, title);
3467
3526
  if (wordCount2 === 0) {
3468
3527
  } else if (wordCount2 < 450 && !isShortForm) {
@@ -3489,7 +3548,7 @@ function buildSummaryItems(input) {
3489
3548
  const headings = documentFields?.headings || [];
3490
3549
  const headingsDetailed = documentFields?.headingsDetailed;
3491
3550
  const h2Count = headingsDetailed ? headingsDetailed.filter((h) => h.level === 2 || h.level === 3).length : headings.length;
3492
- if (headings.length === 0 && wordCount2 > 200 && wordCount2 < 1e3) {
3551
+ if (h2Count === 0 && wordCount2 > 200 && wordCount2 < 1e3) {
3493
3552
  items.push({
3494
3553
  id: "headings-missing",
3495
3554
  category: "headings",
@@ -3595,7 +3654,7 @@ function buildSummaryItems(input) {
3595
3654
  if (GENERIC_FN_RE.test(base)) return true;
3596
3655
  if (/_/.test(base) || /\s/.test(base)) return true;
3597
3656
  const words = base.split("-").filter(Boolean);
3598
- return words.length < 2 || words.length > 7;
3657
+ return words.length < 2 || words.length > 5;
3599
3658
  });
3600
3659
  if (badFilenames.length > 0) {
3601
3660
  items.push({
@@ -3613,7 +3672,7 @@ function buildSummaryItems(input) {
3613
3672
  if (!trimmed) return false;
3614
3673
  const len = trimmed.length;
3615
3674
  const wc = trimmed.split(/\s+/).filter(Boolean).length;
3616
- return len > 125 || wc < 2;
3675
+ return len >= 125 || wc < 2;
3617
3676
  });
3618
3677
  if (badAlts.length > 0) {
3619
3678
  items.push({
@@ -3642,7 +3701,7 @@ function buildSummaryItems(input) {
3642
3701
  }
3643
3702
  if (!primaryKeyword) {
3644
3703
  } else {
3645
- if (text && !tokensContain(text, primaryKeyword)) {
3704
+ if (bodyText && !containsKeywordTokens(bodyText, primaryKeyword)) {
3646
3705
  items.push({
3647
3706
  id: "keywords-primary-not-in-body",
3648
3707
  category: "keywords",
@@ -3667,7 +3726,7 @@ function buildSummaryItems(input) {
3667
3726
  }
3668
3727
  }
3669
3728
  if (secondaryKeyword) {
3670
- if (text && !tokensContain(text, secondaryKeyword)) {
3729
+ if (bodyText && !containsKeywordTokens(bodyText, secondaryKeyword)) {
3671
3730
  items.push({
3672
3731
  id: "secondary-not-in-body",
3673
3732
  category: "keywords",
@@ -3679,19 +3738,19 @@ function buildSummaryItems(input) {
3679
3738
  });
3680
3739
  }
3681
3740
  const titleVal = documentFields?.title;
3682
- if (titleVal && !tokensContain(titleVal, secondaryKeyword)) {
3741
+ if (titleVal && !containsKeywordTokens(titleVal, secondaryKeyword)) {
3683
3742
  items.push({
3684
3743
  id: "secondary-not-in-title",
3685
3744
  category: "meta",
3686
3745
  severity: "opportunity",
3687
3746
  label: "Secondary keyword not in title",
3688
- description: `The title leads with the primary keyword but doesn't include "${secondaryKeyword}".`,
3747
+ description: `The title doesn't include your secondary keyword "${secondaryKeyword}".`,
3689
3748
  howToFix: "If it fits naturally, include the secondary keyword in the title too - but never at the cost of the primary leading.",
3690
3749
  jumpTo: { tab: "meta", anchorId: "anchor-meta-title" }
3691
3750
  });
3692
3751
  }
3693
3752
  const metaVal = documentFields?.metaDescription;
3694
- if (metaVal && !tokensContain(metaVal, secondaryKeyword)) {
3753
+ if (metaVal && !containsKeywordTokens(metaVal, secondaryKeyword)) {
3695
3754
  items.push({
3696
3755
  id: "secondary-not-in-meta",
3697
3756
  category: "meta",
@@ -3703,7 +3762,7 @@ function buildSummaryItems(input) {
3703
3762
  });
3704
3763
  }
3705
3764
  const slugVal = documentFields?.slug;
3706
- if (slugVal && !tokensContain(slugVal.replace(/-/g, " "), secondaryKeyword)) {
3765
+ if (slugVal && !containsKeywordTokens(slugVal.replace(/-/g, " "), secondaryKeyword)) {
3707
3766
  items.push({
3708
3767
  id: "secondary-not-in-url",
3709
3768
  category: "meta",
@@ -4014,7 +4073,7 @@ function SummaryTab({
4014
4073
  }) {
4015
4074
  const scoreDetail = useMemo(() => {
4016
4075
  if (!analysis) return null;
4017
- const scored = primaryKeyword && primaryKeyword !== analysis.primaryKeyword?.term ? { ...analysis, primaryKeyword: { ...analysis.primaryKeyword, term: primaryKeyword } } : analysis;
4076
+ const scored = primaryKeyword && analysis.primaryKeyword && primaryKeyword !== analysis.primaryKeyword.term ? { ...analysis, primaryKeyword: { ...analysis.primaryKeyword, term: primaryKeyword } } : analysis;
4018
4077
  return calculateContentScoreDetailed(text, scored, documentFields);
4019
4078
  }, [text, analysis, documentFields, primaryKeyword]);
4020
4079
  const score = scoreDetail?.total ?? null;
@@ -4124,7 +4183,7 @@ function SummaryTab({
4124
4183
  }
4125
4184
 
4126
4185
  // src/components/tabs/AEOTab.tsx
4127
- import { useMemo as useMemo2, useState as useState13 } from "react";
4186
+ import { useEffect as useEffect10, useMemo as useMemo2, useRef as useRef10, useState as useState13 } from "react";
4128
4187
 
4129
4188
  // src/lib/geoAnalysis.ts
4130
4189
  var FACT_PATTERN = /\d+(?:\.\d+)?\s*%|\b\d{1,3}(?:,\d{3})+\b|\bn\s*=\s*\d+\b|\bp\s*[<=]\s*0?\.\d+\b|\b\d+(?:\.\d+)?\s*(?:patients|participants|subjects|cases|deaths|adverse events|mg|mcg|hours|days|weeks|months|years|fold|x)\b|\b(?:NEJM|JAMA|FDA|EMA|CDC|WHO|NIH|ACC|ASCO|ASH|ESMO|AHA|ACS)\b|\bet al\.?\b|\b(?:phase|stage)\s+(?:I{1,3}V?|1|2|3|4)\b/i;
@@ -4237,11 +4296,17 @@ function SectionHeader2({ label, iconColor, ai }) {
4237
4296
  }
4238
4297
  function CopyButton({ text }) {
4239
4298
  const [copied, setCopied] = useState13(false);
4299
+ const copyTimerRef = useRef10(null);
4300
+ useEffect10(() => {
4301
+ return () => {
4302
+ if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
4303
+ };
4304
+ }, []);
4240
4305
  const handleCopy = async () => {
4241
4306
  try {
4242
4307
  await navigator.clipboard.writeText(text);
4243
4308
  setCopied(true);
4244
- setTimeout(() => setCopied(false), 1500);
4309
+ copyTimerRef.current = setTimeout(() => setCopied(false), 1500);
4245
4310
  } catch {
4246
4311
  }
4247
4312
  };
@@ -4800,8 +4865,8 @@ import { Fragment as Fragment6, jsx as jsx13, jsxs as jsxs12 } from "react/jsx-r
4800
4865
  function buildLiveUrl(publication, slug) {
4801
4866
  if (!slug) return null;
4802
4867
  const pub = (publication || "").trim().toLowerCase();
4803
- if (!/^[a-z0-9-]+$/.test(pub)) return null;
4804
- const cleanSlug = slug.replace(/^\/+/, "");
4868
+ if (!KNOWN_MJH_PUBLICATIONS.has(pub)) return null;
4869
+ const cleanSlug = slug.replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
4805
4870
  return `https://www.${pub}.com/view/${cleanSlug}`;
4806
4871
  }
4807
4872
  function buildSanityUrl(baseUrl, id, type) {
@@ -4898,6 +4963,7 @@ function freshnessChip(label, score) {
4898
4963
  "very-old": { bg: "rgba(220,38,38,0.1)", color: "#dc2626", text: "Very old" }
4899
4964
  };
4900
4965
  const c = map[label];
4966
+ if (!c) return null;
4901
4967
  return /* @__PURE__ */ jsx13(
4902
4968
  "span",
4903
4969
  {
@@ -4999,7 +5065,15 @@ function LinkingTab({
4999
5065
  isStale && suggestions.length > 0 && !isLoading && /* @__PURE__ */ jsxs12(
5000
5066
  "div",
5001
5067
  {
5068
+ role: "button",
5069
+ tabIndex: 0,
5002
5070
  onClick: onRefresh,
5071
+ onKeyDown: (e) => {
5072
+ if (e.key === "Enter" || e.key === " ") {
5073
+ e.preventDefault();
5074
+ onRefresh();
5075
+ }
5076
+ },
5003
5077
  style: {
5004
5078
  display: "flex",
5005
5079
  alignItems: "center",
@@ -5076,10 +5150,10 @@ function LinkingTab({
5076
5150
  ScoreDonut,
5077
5151
  {
5078
5152
  size: 64,
5079
- topic: s.topicScore,
5080
- freshness: s.freshnessScore,
5081
- sectionFit: s.sectionFitScore,
5082
- composite: s.compositeScore
5153
+ topic: Math.max(0, Math.min(100, s.topicScore)),
5154
+ freshness: Math.max(0, Math.min(100, s.freshnessScore)),
5155
+ sectionFit: Math.max(0, Math.min(100, s.sectionFitScore)),
5156
+ composite: Math.max(0, Math.min(100, s.compositeScore))
5083
5157
  }
5084
5158
  ),
5085
5159
  /* @__PURE__ */ jsxs12("div", { style: { flex: 1, minWidth: 0 }, children: [
@@ -5094,7 +5168,7 @@ function LinkingTab({
5094
5168
  ] }),
5095
5169
  (() => {
5096
5170
  const liveUrl = buildLiveUrl(publication, s.slug);
5097
- const sanityUrl = buildSanityUrl(sanityBaseUrl, s._id, documentType);
5171
+ const sanityUrl = buildSanityUrl(sanityBaseUrl, s._id);
5098
5172
  if (!liveUrl && !sanityUrl) return null;
5099
5173
  return /* @__PURE__ */ jsxs12("div", { style: { display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 6 }, children: [
5100
5174
  sanityUrl && /* @__PURE__ */ jsx13(LinkChip, { href: sanityUrl, label: "Inside Sanity", color: MJH_BLUE }),
@@ -5153,13 +5227,6 @@ function LinkingTab({
5153
5227
  // src/components/tabs/MetaTab.tsx
5154
5228
  import { useMemo as useMemo3 } from "react";
5155
5229
  import { Fragment as Fragment7, jsx as jsx14, jsxs as jsxs13 } from "react/jsx-runtime";
5156
- function containsKeywordTokens(haystack, needle) {
5157
- if (!needle) return true;
5158
- const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
5159
- if (tokens.length === 0) return true;
5160
- const lower = haystack.toLowerCase();
5161
- return tokens.every((t) => lower.includes(t));
5162
- }
5163
5230
  var cardStyle5 = {
5164
5231
  borderRadius: 14,
5165
5232
  background: "rgba(255,255,255,0.55)",
@@ -5241,7 +5308,7 @@ function keywordCoverageNote(haystack, primaryKeyword, secondaryKeyword) {
5241
5308
  return `Your primary keyword "${primaryKeyword}" isn't included${secondaryKeyword ? ` (secondary keyword "${secondaryKeyword}" ${hasSecondary ? "is" : "isn't"}).` : "."}`;
5242
5309
  }
5243
5310
  if (secondaryKeyword && !hasSecondary) {
5244
- return `Your primary keyword "${primaryKeyword}" is included, but your secondary keyword "${secondaryKeyword}" is not. Work it in if it reads naturally.`;
5311
+ return `Your secondary keyword "${secondaryKeyword}" isn't included${primaryKeyword && hasPrimary ? ` (primary keyword "${primaryKeyword}" is present)` : ""}. Work it in if it reads naturally.`;
5245
5312
  }
5246
5313
  return "";
5247
5314
  }
@@ -5430,25 +5497,6 @@ function MetaTab({ documentFields, primaryKeyword, secondaryKeyword, isLoading }
5430
5497
  // src/components/tabs/TechnicalTab.tsx
5431
5498
  import { useMemo as useMemo4, useState as useState15 } from "react";
5432
5499
  import { Fragment as Fragment8, jsx as jsx15, jsxs as jsxs14 } from "react/jsx-runtime";
5433
- function containsKeywordTokens2(haystack, needle) {
5434
- if (!needle) return true;
5435
- const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
5436
- if (tokens.length === 0) return true;
5437
- const lower = haystack.toLowerCase();
5438
- return tokens.every((t) => lower.includes(t));
5439
- }
5440
- function keywordLeadsUrl(slug, primaryKeyword) {
5441
- if (!primaryKeyword) return true;
5442
- const slugWords = slug.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);
5443
- const tokens = primaryKeyword.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
5444
- if (tokens.length === 0 || slugWords.length === 0) return true;
5445
- let earliest = Infinity;
5446
- for (const t of tokens) {
5447
- const idx = slugWords.findIndex((w) => w.includes(t));
5448
- if (idx >= 0) earliest = Math.min(earliest, idx);
5449
- }
5450
- return earliest <= 2;
5451
- }
5452
5500
  function urlAudit(slug, primaryKeyword, secondaryKeyword) {
5453
5501
  const SHORT_DESC = "Keep the URL short and descriptive - concise URLs are easier to read - and avoid trailing, duplicate, or excessive spaces.";
5454
5502
  if (!slug) {
@@ -5460,9 +5508,9 @@ function urlAudit(slug, primaryKeyword, secondaryKeyword) {
5460
5508
  };
5461
5509
  }
5462
5510
  const slugAsWords = slug.replace(/-/g, " ");
5463
- const hasPrimary = primaryKeyword ? containsKeywordTokens2(slugAsWords, primaryKeyword) : true;
5464
- const leads = primaryKeyword ? keywordLeadsUrl(slug, primaryKeyword) : true;
5465
- const hasSecondary = secondaryKeyword ? containsKeywordTokens2(slugAsWords, secondaryKeyword) : true;
5511
+ const hasPrimary = primaryKeyword ? containsKeywordTokens(slugAsWords, primaryKeyword) : true;
5512
+ const leads = primaryKeyword ? keywordLeadsSlug(slug, primaryKeyword) : true;
5513
+ const hasSecondary = secondaryKeyword ? containsKeywordTokens(slugAsWords, secondaryKeyword) : true;
5466
5514
  if (primaryKeyword && !hasPrimary) {
5467
5515
  const secNote = secondaryKeyword && !hasSecondary ? ` Your secondary keyword "${secondaryKeyword}" could follow it.` : "";
5468
5516
  return {
@@ -5617,7 +5665,7 @@ function imageFilenameAudit(filenames) {
5617
5665
  const words = base.split("-").filter(Boolean);
5618
5666
  if (words.length < 2) {
5619
5667
  issues.push({ filename: f, reason: "single word - use 2-3 descriptive hyphenated words" });
5620
- } else if (words.length > 7) {
5668
+ } else if (words.length > 5) {
5621
5669
  issues.push({ filename: f, reason: "too many words - keep to 3-5" });
5622
5670
  }
5623
5671
  }
@@ -5646,7 +5694,7 @@ function imageAltTextAudit(altTexts) {
5646
5694
  audited++;
5647
5695
  const len = trimmed.length;
5648
5696
  const wc = trimmed.split(/\s+/).filter(Boolean).length;
5649
- if (len > 125) {
5697
+ if (len >= 125) {
5650
5698
  issues.push({ alt: trimmed, reason: `${len} chars - shorten to under 125` });
5651
5699
  } else if (wc < 2) {
5652
5700
  issues.push({ alt: trimmed, reason: "just one word - use 2-5 descriptive keywords" });
@@ -6059,7 +6107,10 @@ function TechnicalTab({
6059
6107
  );
6060
6108
  const headings = documentFields?.headings || [];
6061
6109
  const headingsDetailed = documentFields?.headingsDetailed;
6062
- const headingsForStructure = headingsDetailed ? headingsDetailed : headings.map((text2) => ({ text: text2, level: 2 }));
6110
+ const headingsForStructure = useMemo4(
6111
+ () => headingsDetailed ? headingsDetailed : headings.map((text2) => ({ text: text2, level: 2 })),
6112
+ [headingsDetailed, headings]
6113
+ );
6063
6114
  const wordCount2 = text ? text.split(/\s+/).filter(Boolean).length : 0;
6064
6115
  const structureAudits = useMemo4(
6065
6116
  () => computeHeadingStructureAudits(headingsForStructure, wordCount2),
@@ -6167,9 +6218,9 @@ function TechnicalTab({
6167
6218
  },
6168
6219
  i
6169
6220
  )),
6170
- headings.length > 12 && /* @__PURE__ */ jsxs14("div", { style: { fontSize: 10, color: "#4b5563" }, children: [
6221
+ (headingsDetailed ?? headings).length > 12 && /* @__PURE__ */ jsxs14("div", { style: { fontSize: 10, color: "#4b5563" }, children: [
6171
6222
  "+ ",
6172
- headings.length - 12,
6223
+ (headingsDetailed ?? headings).length - 12,
6173
6224
  " more"
6174
6225
  ] })
6175
6226
  ] })
@@ -6276,14 +6327,14 @@ function PanelContent({
6276
6327
  const keywordAnalysisState = externalAnalysis;
6277
6328
  const effectivePrimary = selectedPrimary || externalAnalysis.analysis?.primaryKeyword?.term || "";
6278
6329
  const effectiveSecondary = selectedSecondary || "";
6279
- const containerRef = useRef10(null);
6280
- const dragging = useRef10(false);
6330
+ const containerRef = useRef11(null);
6331
+ const dragging = useRef11(false);
6281
6332
  const onMouseDown = useCallback5(() => {
6282
6333
  dragging.current = true;
6283
6334
  document.body.style.cursor = "row-resize";
6284
6335
  document.body.style.userSelect = "none";
6285
6336
  }, []);
6286
- useEffect10(() => {
6337
+ useEffect11(() => {
6287
6338
  const onMouseMove = (e) => {
6288
6339
  if (!dragging.current || !containerRef.current) return;
6289
6340
  const rect = containerRef.current.getBoundingClientRect();
@@ -6308,8 +6359,9 @@ function PanelContent({
6308
6359
  const onboardSessionKey = `seo-copilot-onboard-shown-${onboardSite}`;
6309
6360
  const [popupMode, setPopupMode] = useState16("hidden");
6310
6361
  const [popupClosing, setPopupClosing] = useState16(false);
6311
- const onboardTimerRef = useRef10(null);
6312
- useEffect10(() => {
6362
+ const onboardTimerRef = useRef11(null);
6363
+ const onboardFadeRef = useRef11(null);
6364
+ useEffect11(() => {
6313
6365
  let onboarded = false;
6314
6366
  let shownThisSession = false;
6315
6367
  try {
@@ -6328,14 +6380,15 @@ function PanelContent({
6328
6380
  }
6329
6381
  onboardTimerRef.current = setTimeout(() => {
6330
6382
  setPopupClosing(true);
6331
- setTimeout(() => {
6383
+ onboardFadeRef.current = setTimeout(() => {
6332
6384
  setPopupMode("hidden");
6333
6385
  setPopupClosing(false);
6334
6386
  }, 180);
6335
- }, 5e3);
6387
+ }, 8e3);
6336
6388
  }
6337
6389
  return () => {
6338
6390
  if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
6391
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
6339
6392
  };
6340
6393
  }, [onboardKey, onboardSessionKey]);
6341
6394
  const markOnboarded = useCallback5(() => {
@@ -6346,15 +6399,17 @@ function PanelContent({
6346
6399
  }, [onboardKey]);
6347
6400
  const dismissPopup = useCallback5(() => {
6348
6401
  if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
6402
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
6349
6403
  markOnboarded();
6350
6404
  setPopupClosing(true);
6351
- setTimeout(() => {
6405
+ onboardFadeRef.current = setTimeout(() => {
6352
6406
  setPopupMode("hidden");
6353
6407
  setPopupClosing(false);
6354
6408
  }, 180);
6355
6409
  }, [markOnboarded]);
6356
6410
  const openPopupPersistent = useCallback5(() => {
6357
6411
  if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
6412
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
6358
6413
  markOnboarded();
6359
6414
  setPopupClosing(false);
6360
6415
  setPopupMode("persistent");
@@ -6362,7 +6417,12 @@ function PanelContent({
6362
6417
  const handleTabChange = useCallback5((id) => {
6363
6418
  markOnboarded();
6364
6419
  if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
6365
- setPopupMode((m) => m === "hidden" ? m : "hidden");
6420
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
6421
+ setPopupClosing(true);
6422
+ onboardFadeRef.current = setTimeout(() => {
6423
+ setPopupMode("hidden");
6424
+ setPopupClosing(false);
6425
+ }, 120);
6366
6426
  onActiveTabChange(id);
6367
6427
  }, [markOnboarded, onActiveTabChange]);
6368
6428
  const tabDefs = [
@@ -6800,8 +6860,10 @@ function SEOCopilotInner({ config, onClose }) {
6800
6860
  "seo-copilot-ui-float-size",
6801
6861
  { width: 380, height: typeof window !== "undefined" ? Math.round(window.innerHeight * 0.8) : 600 }
6802
6862
  );
6803
- const dragOffset = useRef10(null);
6804
- const resizeStart = useRef10(null);
6863
+ const dragOffset = useRef11(null);
6864
+ const resizeStart = useRef11(null);
6865
+ const activeDragCleanupRef = useRef11(null);
6866
+ const activeResizeCleanupRef = useRef11(null);
6805
6867
  const { text, isLoading: docLoading, documentFields, documentId, documentType } = useDocumentContent();
6806
6868
  const { apiUrl } = useConfig();
6807
6869
  const workspace = useWorkspace();
@@ -6836,8 +6898,8 @@ function SEOCopilotInner({ config, onClose }) {
6836
6898
  const [selectedPrimary, setSelectedPrimary] = usePersistentState(selectedPrimaryKey, void 0);
6837
6899
  const selectedSecondaryKey = documentId ? `seo-copilot-secondary-${documentId}` : "seo-copilot-secondary-default";
6838
6900
  const [selectedSecondary, setSelectedSecondary] = usePersistentState(selectedSecondaryKey, "");
6839
- const seedsInitializedRef = useRef10(false);
6840
- useEffect10(() => {
6901
+ const seedsInitializedRef = useRef11(false);
6902
+ useEffect11(() => {
6841
6903
  if (!seedsInitializedRef.current) {
6842
6904
  seedsInitializedRef.current = true;
6843
6905
  return;
@@ -6849,6 +6911,11 @@ function SEOCopilotInner({ config, onClose }) {
6849
6911
  const [splitPercent, setSplitPercent] = usePersistentState("seo-copilot-ui-split", 70);
6850
6912
  const keywordAnalysisState = useKeywordAnalysis(text, apiUrl, effectivePublication, seedKeywords, documentFields, selectedPrimary, documentId);
6851
6913
  const effectivePrimary = selectedPrimary || keywordAnalysisState.analysis?.primaryKeyword?.term || "";
6914
+ useEffect11(() => {
6915
+ if (selectedSecondary && effectivePrimary && selectedSecondary.toLowerCase() === effectivePrimary.toLowerCase()) {
6916
+ setSelectedSecondary("");
6917
+ }
6918
+ }, [effectivePrimary, selectedSecondary, setSelectedSecondary]);
6852
6919
  const keywordPanelData = useMemo5(() => {
6853
6920
  const analysis = keywordAnalysisState.analysis;
6854
6921
  if (!analysis) return void 0;
@@ -6869,9 +6936,10 @@ function SEOCopilotInner({ config, onClose }) {
6869
6936
  const [contentSuggestions, setContentSuggestions] = usePersistentState(contentSuggestionsKey, null);
6870
6937
  const [isCSLoading, setIsCSLoading] = useState16(false);
6871
6938
  const [csError, setCsError] = useState16(null);
6872
- const aeoOpVersionRef = useRef10(0);
6873
- const didInitAeoRef = useRef10(false);
6874
- useEffect10(() => {
6939
+ const aeoOpVersionRef = useRef11(0);
6940
+ const csAbortRef = useRef11(null);
6941
+ const didInitAeoRef = useRef11(false);
6942
+ useEffect11(() => {
6875
6943
  if (!didInitAeoRef.current) {
6876
6944
  didInitAeoRef.current = true;
6877
6945
  return;
@@ -6885,7 +6953,11 @@ function SEOCopilotInner({ config, onClose }) {
6885
6953
  setIsCSLoading(true);
6886
6954
  setCsError(null);
6887
6955
  try {
6888
- const data = await fetchContentSuggestions(apiUrl, text, effectivePrimary, effectivePublication);
6956
+ csAbortRef.current?.abort();
6957
+ const csController = new AbortController();
6958
+ csAbortRef.current = csController;
6959
+ const data = await fetchContentSuggestions(apiUrl, text, effectivePrimary, effectivePublication, csController.signal);
6960
+ if (csController.signal.aborted) return;
6889
6961
  if (aeoOpVersionRef.current !== myVersion) return;
6890
6962
  if (data.keyTakeaways.length === 0 && data.infographicOpportunities.length === 0 && data.bulletListItems.length === 0) {
6891
6963
  setCsError("No suggestions returned. Try again with more content.");
@@ -6904,10 +6976,11 @@ function SEOCopilotInner({ config, onClose }) {
6904
6976
  const [isLinkingLoading, setIsLinkingLoading] = useState16(false);
6905
6977
  const [linkingError, setLinkingError] = useState16(null);
6906
6978
  const [linkingFetchedText, setLinkingFetchedText] = useState16("");
6907
- const linkingVersionRef = useRef10(0);
6908
- const didInitLinkingRef = useRef10(false);
6909
- const lastLinkingFetchKey = useRef10("");
6910
- useEffect10(() => {
6979
+ const linkingVersionRef = useRef11(0);
6980
+ const linkingAbortRef = useRef11(null);
6981
+ const didInitLinkingRef = useRef11(false);
6982
+ const lastLinkingFetchKey = useRef11("");
6983
+ useEffect11(() => {
6911
6984
  if (!didInitLinkingRef.current) {
6912
6985
  didInitLinkingRef.current = true;
6913
6986
  return;
@@ -6929,14 +7002,19 @@ function SEOCopilotInner({ config, onClose }) {
6929
7002
  setIsLinkingLoading(true);
6930
7003
  setLinkingError(null);
6931
7004
  try {
7005
+ linkingAbortRef.current?.abort();
7006
+ const linkingController = new AbortController();
7007
+ linkingAbortRef.current = linkingController;
6932
7008
  const suggestions = await fetchLinkingSuggestions(
6933
7009
  apiUrl,
6934
7010
  text,
6935
7011
  effectivePrimary,
6936
7012
  supportingKeywordsForLinking,
6937
7013
  documentId,
6938
- effectivePublication
7014
+ effectivePublication,
7015
+ linkingController.signal
6939
7016
  );
7017
+ if (linkingController.signal.aborted) return;
6940
7018
  if (linkingVersionRef.current !== myVersion) return;
6941
7019
  setLinkingSuggestions(suggestions);
6942
7020
  setLinkingFetchedText(text);
@@ -6952,7 +7030,7 @@ function SEOCopilotInner({ config, onClose }) {
6952
7030
  if (Math.abs(text.length - linkingFetchedText.length) > 150) return true;
6953
7031
  return text.slice(0, 300) !== linkingFetchedText.slice(0, 300);
6954
7032
  }, [text, linkingFetchedText, linkingSuggestions.length]);
6955
- useEffect10(() => {
7033
+ useEffect11(() => {
6956
7034
  if (!text || text.trim().length < 50 || !effectivePrimary) return;
6957
7035
  const fetchKey = `${documentId || "_"}|${effectivePrimary}|${supportingKeywordsForLinking.join(",")}`;
6958
7036
  if (fetchKey === lastLinkingFetchKey.current) return;
@@ -6968,9 +7046,9 @@ function SEOCopilotInner({ config, onClose }) {
6968
7046
  const [hasRunLinkCheck, setHasRunLinkCheck] = usePersistentState(`${linkCheckKey}-ran`, false);
6969
7047
  const [isLinkCheckLoading, setIsLinkCheckLoading] = useState16(false);
6970
7048
  const [linkCheckError, setLinkCheckError] = useState16(null);
6971
- const linkCheckVersionRef = useRef10(0);
6972
- const didInitLinkCheckRef = useRef10(false);
6973
- useEffect10(() => {
7049
+ const linkCheckVersionRef = useRef11(0);
7050
+ const didInitLinkCheckRef = useRef11(false);
7051
+ useEffect11(() => {
6974
7052
  if (!didInitLinkCheckRef.current) {
6975
7053
  didInitLinkCheckRef.current = true;
6976
7054
  return;
@@ -7005,6 +7083,14 @@ function SEOCopilotInner({ config, onClose }) {
7005
7083
  if (linkCheckVersionRef.current !== myVersion) return;
7006
7084
  setIsLinkCheckLoading(false);
7007
7085
  }, [apiUrl, documentFields?.bodyLinks, setHasRunLinkCheck, setLinkCheckResults]);
7086
+ useEffect11(() => {
7087
+ return () => {
7088
+ activeDragCleanupRef.current?.();
7089
+ activeResizeCleanupRef.current?.();
7090
+ csAbortRef.current?.abort();
7091
+ linkingAbortRef.current?.abort();
7092
+ };
7093
+ }, []);
7008
7094
  const handleDragStart = useCallback5(
7009
7095
  (e) => {
7010
7096
  dragOffset.current = {
@@ -7019,6 +7105,7 @@ function SEOCopilotInner({ config, onClose }) {
7019
7105
  });
7020
7106
  };
7021
7107
  const onMouseUp = () => {
7108
+ activeDragCleanupRef.current = null;
7022
7109
  dragOffset.current = null;
7023
7110
  window.removeEventListener("mousemove", onMouseMove);
7024
7111
  window.removeEventListener("mouseup", onMouseUp);
@@ -7029,6 +7116,12 @@ function SEOCopilotInner({ config, onClose }) {
7029
7116
  document.body.style.userSelect = "none";
7030
7117
  window.addEventListener("mousemove", onMouseMove);
7031
7118
  window.addEventListener("mouseup", onMouseUp);
7119
+ activeDragCleanupRef.current = () => {
7120
+ window.removeEventListener("mousemove", onMouseMove);
7121
+ window.removeEventListener("mouseup", onMouseUp);
7122
+ document.body.style.cursor = "";
7123
+ document.body.style.userSelect = "";
7124
+ };
7032
7125
  },
7033
7126
  [floatPos]
7034
7127
  );
@@ -7046,6 +7139,7 @@ function SEOCopilotInner({ config, onClose }) {
7046
7139
  setFloatSize({ width: newW, height: newH });
7047
7140
  };
7048
7141
  const onMouseUp = () => {
7142
+ activeResizeCleanupRef.current = null;
7049
7143
  resizeStart.current = null;
7050
7144
  document.body.style.cursor = "";
7051
7145
  document.body.style.userSelect = "";
@@ -7054,6 +7148,12 @@ function SEOCopilotInner({ config, onClose }) {
7054
7148
  };
7055
7149
  window.addEventListener("mousemove", onMouseMove);
7056
7150
  window.addEventListener("mouseup", onMouseUp);
7151
+ activeResizeCleanupRef.current = () => {
7152
+ window.removeEventListener("mousemove", onMouseMove);
7153
+ window.removeEventListener("mouseup", onMouseUp);
7154
+ document.body.style.cursor = "";
7155
+ document.body.style.userSelect = "";
7156
+ };
7057
7157
  },
7058
7158
  [floatSize]
7059
7159
  );
@@ -7280,7 +7380,14 @@ function seoCopilotInspector(config) {
7280
7380
  useMenuItem: () => ({
7281
7381
  title: "SEO Copilot",
7282
7382
  icon: SEOIcon,
7283
- showAsAction: true
7383
+ // Toolbar placement test: showAsAction renders this as a button in the document
7384
+ // toolbar (where editors expect it). The original crash came from passing
7385
+ // showAsAction WITHOUT a tone; pairing it with a valid string tone is how Sanity's
7386
+ // own built-in inspectors (Validation, etc.) keep their toolbar button safely.
7387
+ // If this still crashes in Nick's studio, remove these two lines to fall back to
7388
+ // the "..." overflow menu (the known-safe placement).
7389
+ showAsAction: true,
7390
+ tone: "default"
7284
7391
  }),
7285
7392
  component: function SEOCopilotInspector(props) {
7286
7393
  return createElement(SEOCopilotPanel, { ...props, config });