sanity-plugin-seo-copilot 0.2.7 → 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.
package/dist/index.js CHANGED
@@ -168,8 +168,8 @@ function detectAuthor(val) {
168
168
  }
169
169
  if (typeof first === "object" && first !== null) {
170
170
  const o = first;
171
- const name = o.name || o.fullName || o.displayName;
172
- const creds = o.credentials || o.title || o.suffix;
171
+ const name = [o.name, o.fullName, o.displayName].find((v) => typeof v === "string" && v.trim().length > 0);
172
+ const creds = [o.credentials, o.title, o.suffix].find((v) => typeof v === "string" && v.trim().length > 0);
173
173
  const slug = o.slug?.current;
174
174
  const bio = o.bioUrl || (slug ? `/author/${slug}` : void 0);
175
175
  if (name) {
@@ -217,14 +217,14 @@ function extractImageMeta(value) {
217
217
  }
218
218
  function buildDocumentFields(value) {
219
219
  const val = value;
220
- const title = val?.title;
220
+ const title = typeof val?.title === "string" ? val.title : void 0;
221
221
  const body = val?.body;
222
222
  const { authorName, authorCredentials, authorBioUrl, authorIsReference } = detectAuthor(val);
223
223
  const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
224
224
  return {
225
225
  title: title || void 0,
226
226
  // MJH uses `summary`; standard Sanity SEO plugins use `metaDescription`
227
- metaDescription: val?.metaDescription || val?.summary || val?.description || val?.seoDescription,
227
+ metaDescription: [val?.metaDescription, val?.summary, val?.description, val?.seoDescription].find((v) => typeof v === "string" && v.trim().length > 0),
228
228
  slug: detectSlug(val),
229
229
  imageNames: imageMeta.names,
230
230
  imageTitles: imageMeta.titles,
@@ -232,18 +232,18 @@ function buildDocumentFields(value) {
232
232
  headings: extractHeadings(body),
233
233
  headingsDetailed: extractHeadingsDetailed(body),
234
234
  bodyLinks: extractBodyLinks(body),
235
- contentCategory: val?.contentCategory || val?.category,
235
+ contentCategory: typeof val?.contentCategory === "string" ? val.contentCategory : typeof val?.category === "string" ? val.category : void 0,
236
236
  contentPlacement: Array.isArray(val?.contentPlacement) ? val.contentPlacement : void 0,
237
237
  authorName,
238
238
  authorCredentials,
239
239
  authorBioUrl,
240
240
  authorIsReference,
241
241
  // `published` is MJH's date field; `publishedAt`/`publishDate` cover other schemas
242
- publishedAt: val?.published || val?.publishedAt || val?.publishDate || val?._createdAt,
242
+ publishedAt: [val?.publishedAt, val?.publishDate, val?.published, val?._createdAt].find((v) => typeof v === "string" && v.trim().length > 0),
243
243
  // `updatedOn` is MJH's "Updated On" field. `updatedAt` is the standard Sanity convention.
244
244
  // `_updatedAt` is the Sanity-managed timestamp as a final fallback.
245
- updatedAt: val?.updatedOn || val?.updatedAt || val?._updatedAt,
246
- lastReviewedAt: val?.lastReviewedAt || val?.lastReviewed || val?.medicallyReviewedAt
245
+ updatedAt: [val?.updatedOn, val?.updatedAt, val?._updatedAt].find((v) => typeof v === "string" && v.trim().length > 0),
246
+ lastReviewedAt: [val?.lastReviewedAt, val?.lastReviewed, val?.medicallyReviewedAt].find((v) => typeof v === "string" && v.trim().length > 0)
247
247
  };
248
248
  }
249
249
 
@@ -312,7 +312,6 @@ async function fetchAnalysis(apiUrl, content, mode, publication, seedKeywords, d
312
312
  const text = await response.text();
313
313
  if (!response.ok) {
314
314
  const err = safeParseJson(text);
315
- console.error("[seo-copilot] analyze error", response.status, err.error);
316
315
  if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
317
316
  if (response.status >= 500) throw new Error("Could not reach the SEO service.");
318
317
  throw new Error("Something went wrong analyzing this document.");
@@ -328,7 +327,6 @@ async function fetchChatStream(apiUrl, messages, documentContext, publication, k
328
327
  });
329
328
  if (!response.ok) {
330
329
  const err = await response.json().catch(() => ({ error: "Request failed" }));
331
- console.error("[seo-copilot] chat error", response.status, err.error);
332
330
  if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
333
331
  if (response.status >= 500) throw new Error("Could not reach the SEO service.");
334
332
  throw new Error("Something went wrong. Please try again.");
@@ -351,7 +349,6 @@ async function lookupKeywords(apiUrl, keywords, signal) {
351
349
  });
352
350
  if (!response.ok) {
353
351
  const err = await response.json().catch(() => ({ error: "Request failed" }));
354
- console.error("[seo-copilot] keywords error", response.status, err.error);
355
352
  if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
356
353
  if (response.status >= 500) throw new Error("Could not reach the SEO service.");
357
354
  throw new Error("Something went wrong. Please try again.");
@@ -370,13 +367,14 @@ async function loadChatHistory(apiUrl, userId, documentId) {
370
367
  return [];
371
368
  }
372
369
  }
373
- async function fetchContentSuggestions(apiUrl, content, primaryKeyword, publication) {
370
+ async function fetchContentSuggestions(apiUrl, content, primaryKeyword, publication, signal) {
374
371
  const empty = { keyTakeaways: [], infographicOpportunities: [], bulletListItems: [] };
375
372
  try {
376
373
  const res = await fetch(`${apiUrl}/api/seo-copilot/content-suggestions`, {
377
374
  method: "POST",
378
375
  headers: { "Content-Type": "application/json" },
379
- body: JSON.stringify({ content, primaryKeyword, publication })
376
+ body: JSON.stringify({ content, primaryKeyword, publication }),
377
+ signal
380
378
  });
381
379
  if (!res.ok) return empty;
382
380
  const data = await res.json().catch(() => null);
@@ -390,13 +388,14 @@ async function fetchContentSuggestions(apiUrl, content, primaryKeyword, publicat
390
388
  return empty;
391
389
  }
392
390
  }
393
- async function fetchLinkingSuggestions(apiUrl, content, primaryKeyword, supportingKeywords, currentDocumentId, publication) {
391
+ async function fetchLinkingSuggestions(apiUrl, content, primaryKeyword, supportingKeywords, currentDocumentId, publication, signal) {
394
392
  if (!content || content.trim().length < 50) return [];
395
393
  try {
396
394
  const res = await fetch(`${apiUrl}/api/seo-copilot/linking-suggestions`, {
397
395
  method: "POST",
398
396
  headers: { "Content-Type": "application/json" },
399
- body: JSON.stringify({ content, primaryKeyword, supportingKeywords, currentDocumentId, publication })
397
+ body: JSON.stringify({ content, primaryKeyword, supportingKeywords, currentDocumentId, publication }),
398
+ signal
400
399
  });
401
400
  if (!res.ok) return [];
402
401
  const data = await res.json().catch(() => null);
@@ -493,6 +492,8 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
493
492
  docVersionRef.current += 1;
494
493
  volumeAbortRef.current?.abort();
495
494
  volumeAbortRef.current = null;
495
+ deepAbortRef.current?.abort();
496
+ deepAbortRef.current = null;
496
497
  const fresh = loadCached();
497
498
  cached.current = fresh;
498
499
  setAnalysisRaw(fresh.analysis);
@@ -531,46 +532,11 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
531
532
  const lastAnalysisRef = (0, import_react2.useRef)(null);
532
533
  const docVersionRef = (0, import_react2.useRef)(0);
533
534
  const volumeAbortRef = (0, import_react2.useRef)(null);
534
- (0, import_react2.useEffect)(() => {
535
- if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
536
- setAnalysis(null);
537
- return;
538
- }
539
- let cancelled = false;
540
- const controller = new AbortController();
541
- setIsLoading(true);
542
- setError(null);
543
- fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary, controller.signal).then((result) => {
544
- if (cancelled) return;
545
- const analysisResult = result;
546
- lastAnalysisRef.current = analysisResult;
547
- setAnalysis(analysisResult);
548
- setIsLoading(false);
549
- const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
550
- const allTerms = [
551
- .../* @__PURE__ */ new Set([
552
- ...candidateTerms,
553
- analysisResult.primaryKeyword.term,
554
- ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
555
- ...analysisResult.missingKeywords.map((kw) => kw.term)
556
- ])
557
- ];
558
- const uncachedTerms = allTerms.filter((t) => !volumeMapRef.current.has(t.toLowerCase()));
559
- if (uncachedTerms.length > 0) {
560
- doVolumeLookup(analysisResult, uncachedTerms);
561
- }
562
- }).catch((err) => {
563
- if (err instanceof Error && err.name === "AbortError") return;
564
- if (!cancelled) {
565
- setError(err.message);
566
- setIsLoading(false);
567
- }
568
- });
569
- return () => {
570
- cancelled = true;
571
- controller.abort();
572
- };
573
- }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, JSON.stringify(documentFields)]);
535
+ const deepAbortRef = (0, import_react2.useRef)(null);
536
+ (0, import_react2.useEffect)(() => () => {
537
+ volumeAbortRef.current?.abort();
538
+ deepAbortRef.current?.abort();
539
+ }, []);
574
540
  const doVolumeLookup = (0, import_react2.useCallback)((analysisResult, terms) => {
575
541
  setIsVolumesLoading(true);
576
542
  const myVersion = docVersionRef.current;
@@ -611,6 +577,50 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
611
577
  setIsVolumesLoading(false);
612
578
  });
613
579
  }, [apiUrl, cacheKey]);
580
+ const doVolumeLookupRef = (0, import_react2.useRef)(doVolumeLookup);
581
+ (0, import_react2.useEffect)(() => {
582
+ doVolumeLookupRef.current = doVolumeLookup;
583
+ }, [doVolumeLookup]);
584
+ (0, import_react2.useEffect)(() => {
585
+ if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
586
+ setAnalysis(null);
587
+ return;
588
+ }
589
+ let cancelled = false;
590
+ const controller = new AbortController();
591
+ setIsLoading(true);
592
+ setError(null);
593
+ fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary, controller.signal).then((result) => {
594
+ if (cancelled) return;
595
+ const analysisResult = result;
596
+ lastAnalysisRef.current = analysisResult;
597
+ setAnalysis(analysisResult);
598
+ setIsLoading(false);
599
+ const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
600
+ const allTerms = [
601
+ .../* @__PURE__ */ new Set([
602
+ ...candidateTerms,
603
+ analysisResult.primaryKeyword.term,
604
+ ...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
605
+ ...analysisResult.missingKeywords.map((kw) => kw.term)
606
+ ])
607
+ ];
608
+ const uncachedTerms = allTerms.filter((t) => !volumeMapRef.current.has(t.toLowerCase()));
609
+ if (uncachedTerms.length > 0) {
610
+ doVolumeLookupRef.current(analysisResult, uncachedTerms);
611
+ }
612
+ }).catch((err) => {
613
+ if (err instanceof Error && err.name === "AbortError") return;
614
+ if (!cancelled) {
615
+ setError(err.message);
616
+ setIsLoading(false);
617
+ }
618
+ });
619
+ return () => {
620
+ cancelled = true;
621
+ controller.abort();
622
+ };
623
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, JSON.stringify(documentFields)]);
614
624
  const refreshVolumes = (0, import_react2.useCallback)(() => {
615
625
  const current = lastAnalysisRef.current || analysis;
616
626
  if (!current) return;
@@ -623,16 +633,20 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
623
633
  setAeoContentChanged(false);
624
634
  setAeoTextSnapshot(text);
625
635
  const myVersion = docVersionRef.current;
626
- fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary).then((result) => {
636
+ deepAbortRef.current?.abort();
637
+ const deepController = new AbortController();
638
+ deepAbortRef.current = deepController;
639
+ fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary, deepController.signal).then((result) => {
627
640
  if (docVersionRef.current !== myVersion) return;
628
641
  setDeepAnalysis(result);
629
642
  setIsDeepLoading(false);
630
643
  }).catch((err) => {
644
+ if (deepController.signal.aborted || err?.name === "AbortError") return;
631
645
  if (docVersionRef.current !== myVersion) return;
632
646
  setError(err.message);
633
647
  setIsDeepLoading(false);
634
648
  });
635
- }, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields]);
649
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields, focusPrimary]);
636
650
  return {
637
651
  analysis,
638
652
  isLoading,
@@ -650,6 +664,7 @@ function useKeywordAnalysis(text, apiUrl, publication, seedKeywords, documentFie
650
664
  var import_react3 = require("react");
651
665
  var import_sanity = require("sanity");
652
666
  function getLocalUserId() {
667
+ if (typeof window === "undefined") return "anonymous";
653
668
  const key = "seo-copilot-user-id";
654
669
  try {
655
670
  let id = localStorage.getItem(key);
@@ -702,6 +717,7 @@ function useSEOChat(apiUrl, documentText, publication, keywordPanelData, documen
702
717
  (0, import_react3.useEffect)(() => {
703
718
  return () => {
704
719
  streamAbortRef.current?.abort();
720
+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
705
721
  };
706
722
  }, []);
707
723
  const saveTimerRef = (0, import_react3.useRef)(null);
@@ -1186,6 +1202,12 @@ function FeedbackButton({ suggestionType, suggestionText, documentId, publicatio
1186
1202
  const [submitted, setSubmitted] = (0, import_react7.useState)(false);
1187
1203
  const popupRef = (0, import_react7.useRef)(null);
1188
1204
  const inputRef = (0, import_react7.useRef)(null);
1205
+ const submitTimerRef = (0, import_react7.useRef)(null);
1206
+ (0, import_react7.useEffect)(() => {
1207
+ return () => {
1208
+ if (submitTimerRef.current) clearTimeout(submitTimerRef.current);
1209
+ };
1210
+ }, []);
1189
1211
  (0, import_react7.useEffect)(() => {
1190
1212
  if (!showReasonPopup) return;
1191
1213
  const handler = (e) => {
@@ -1252,7 +1274,7 @@ function FeedbackButton({ suggestionType, suggestionText, documentId, publicatio
1252
1274
  }
1253
1275
  }
1254
1276
  setSubmitted(true);
1255
- setTimeout(() => {
1277
+ submitTimerRef.current = setTimeout(() => {
1256
1278
  setShowReasonPopup(false);
1257
1279
  setReason("");
1258
1280
  }, 1e3);
@@ -1458,11 +1480,13 @@ function buildSuggestedKeywords(supporting, missing, documentText, documentField
1458
1480
  const merged = [];
1459
1481
  const lowerText = documentText.toLowerCase();
1460
1482
  for (const kw of supporting) {
1483
+ if (kw == null || typeof kw.term !== "string") continue;
1461
1484
  const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
1462
1485
  const livePlacement = computePlacementClient(kw.term, documentText, documentFields);
1463
1486
  merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, placement: livePlacement });
1464
1487
  }
1465
1488
  for (const kw of missing) {
1489
+ if (kw == null || typeof kw.term !== "string") continue;
1466
1490
  const actuallyInContent = lowerText.includes(kw.term.toLowerCase());
1467
1491
  const livePlacement = computePlacementClient(kw.term, documentText, documentFields);
1468
1492
  merged.push({ term: kw.term, volume: kw.volume ?? 0, inContent: actuallyInContent, reason: kw.reason, placement: livePlacement });
@@ -1731,7 +1755,7 @@ function SecondaryKeywordSelector({
1731
1755
  setCustomInputOpen(false);
1732
1756
  }
1733
1757
  };
1734
- const opts = selectedTerm && !options.some((o) => o.term === selectedTerm) ? [...options, { term: selectedTerm, volume: null }] : options;
1758
+ const opts = selectedTerm && !options.some((o) => o.term.toLowerCase() === selectedTerm.toLowerCase()) ? [...options, { term: selectedTerm, volume: null }] : options;
1735
1759
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: cardStyle, children: [
1736
1760
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1737
1761
  SectionHeader,
@@ -1841,8 +1865,8 @@ function computePlacementClient(term, content, fields) {
1841
1865
  const lower = term.toLowerCase();
1842
1866
  return {
1843
1867
  inBody: content.toLowerCase().includes(lower),
1844
- inTitle: fields?.title?.toLowerCase().includes(lower) ?? false,
1845
- inMetaDescription: fields?.metaDescription?.toLowerCase().includes(lower) ?? false,
1868
+ inTitle: typeof fields?.title === "string" ? fields.title.toLowerCase().includes(lower) : false,
1869
+ inMetaDescription: typeof fields?.metaDescription === "string" ? fields.metaDescription.toLowerCase().includes(lower) : false,
1846
1870
  inImages: fields?.imageNames?.some((name) => name.toLowerCase().includes(lower)) ?? false,
1847
1871
  inUrl: fields?.slug?.toLowerCase().includes(lower) ?? false
1848
1872
  };
@@ -1912,7 +1936,9 @@ function SuggestedKeywordsCard({
1912
1936
  const res = await fetch(`${apiUrl}/api/seo-copilot/keyword-help`, {
1913
1937
  method: "POST",
1914
1938
  headers: { "Content-Type": "application/json" },
1915
- body: JSON.stringify({ keyword: term, content: text, publication, previousSuggestions })
1939
+ // Clip to 5,000 chars: the backend only reads the first 4,000 anyway, so sending
1940
+ // the full article needlessly bloats the request on long pieces.
1941
+ body: JSON.stringify({ keyword: term, content: text.slice(0, 5e3), publication, previousSuggestions })
1916
1942
  });
1917
1943
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
1918
1944
  const data = await res.json();
@@ -2335,8 +2361,9 @@ function KeywordPanel({
2335
2361
  const prevDefaultRef = (0, import_react9.useRef)(defaultSelectedTerm);
2336
2362
  (0, import_react9.useEffect)(() => {
2337
2363
  if (defaultSelectedTerm && defaultSelectedTerm !== prevDefaultRef.current) {
2338
- setSelectedPrimaryTerm((prev) => prev === prevDefaultRef.current ? defaultSelectedTerm : prev);
2364
+ const oldDefault = prevDefaultRef.current;
2339
2365
  prevDefaultRef.current = defaultSelectedTerm;
2366
+ setSelectedPrimaryTerm((prev) => prev === oldDefault ? defaultSelectedTerm : prev);
2340
2367
  }
2341
2368
  }, [defaultSelectedTerm]);
2342
2369
  if ((!text || text.trim().length < 20) && (!seedKeywords || seedKeywords.length === 0)) {
@@ -2370,10 +2397,12 @@ function KeywordPanel({
2370
2397
  placement: computePlacementClient(c.term, text, documentFields)
2371
2398
  }));
2372
2399
  const activeTerm = candidates.find((c) => c.term === selectedPrimaryTerm) ? selectedPrimaryTerm : candidates[0]?.term ?? "";
2400
+ const activeTermLower = activeTerm.toLowerCase();
2373
2401
  const secondaryOptions = [];
2374
2402
  const seenSecondary = /* @__PURE__ */ new Set();
2375
2403
  for (const c of candidates) {
2376
2404
  const key = c.term.toLowerCase();
2405
+ if (key === activeTermLower) continue;
2377
2406
  if (!seenSecondary.has(key)) {
2378
2407
  seenSecondary.add(key);
2379
2408
  secondaryOptions.push({ term: c.term, volume: c.volume });
@@ -2381,6 +2410,7 @@ function KeywordPanel({
2381
2410
  }
2382
2411
  for (const kw of suggestedKeywords) {
2383
2412
  const key = kw.term.toLowerCase();
2413
+ if (key === activeTermLower) continue;
2384
2414
  if (!seenSecondary.has(key)) {
2385
2415
  seenSecondary.add(key);
2386
2416
  secondaryOptions.push({ term: kw.term, volume: kw.volume });
@@ -2625,20 +2655,22 @@ function ChatPanel({ messages, isStreaming, sendMessage, clearChat, documentId }
2625
2655
  "button",
2626
2656
  {
2627
2657
  onClick: clearChat,
2628
- onMouseEnter: () => setClearHovered(true),
2658
+ onMouseEnter: () => !isStreaming && setClearHovered(true),
2629
2659
  onMouseLeave: () => setClearHovered(false),
2630
2660
  title: "Clear conversation",
2631
2661
  "aria-label": "Clear conversation",
2662
+ disabled: isStreaming,
2632
2663
  style: {
2633
2664
  background: "none",
2634
2665
  border: "none",
2635
- cursor: "pointer",
2666
+ cursor: isStreaming ? "not-allowed" : "pointer",
2636
2667
  padding: 4,
2637
2668
  display: "flex",
2638
2669
  alignItems: "center",
2639
- color: clearHovered ? "#ef4444" : "#9ca3af",
2670
+ color: isStreaming ? "#d1d5db" : clearHovered ? "#ef4444" : "#9ca3af",
2640
2671
  transition: "color 150ms",
2641
- flexShrink: 0
2672
+ flexShrink: 0,
2673
+ opacity: isStreaming ? 0.4 : 1
2642
2674
  },
2643
2675
  children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("svg", { width: "14", height: "14", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("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" }) })
2644
2676
  }
@@ -2817,6 +2849,9 @@ function TabBar({ tabs, activeTab, onTabChange }) {
2817
2849
  const duration = Math.min(560, Math.max(280, Math.round(250 + dist * 0.6)));
2818
2850
  return { ...next, ready: true, duration };
2819
2851
  });
2852
+ return () => {
2853
+ if (clickTimerRef.current) clearTimeout(clickTimerRef.current);
2854
+ };
2820
2855
  }, [activeTab, signature]);
2821
2856
  (0, import_react11.useEffect)(() => {
2822
2857
  const bar = barRef.current;
@@ -3056,7 +3091,7 @@ function OnboardingCard({ onDismiss, closing }) {
3056
3091
  backdropFilter: "blur(20px) saturate(170%)",
3057
3092
  WebkitBackdropFilter: "blur(20px) saturate(170%)",
3058
3093
  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)",
3059
- animation: `${closing ? "onboard-out" : "onboard-in"} ${closing ? 180 : 240}ms ease-out forwards`
3094
+ animation: `${closing ? "onboard-out" : "onboard-in"} ${closing ? 200 : 240}ms ease-out forwards`
3060
3095
  },
3061
3096
  children: [
3062
3097
  /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 6 }, children: [
@@ -3065,7 +3100,7 @@ function OnboardingCard({ onDismiss, closing }) {
3065
3100
  "button",
3066
3101
  {
3067
3102
  onClick: onDismiss,
3068
- style: { background: "none", border: "none", cursor: "pointer", padding: 2, display: "flex", color: "#00468a", opacity: 0.7 },
3103
+ style: { background: "none", border: "none", cursor: "pointer", padding: 2, display: "flex", color: "#00468a", opacity: 1 },
3069
3104
  title: "Dismiss",
3070
3105
  "aria-label": "Dismiss",
3071
3106
  children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("svg", { width: "14", height: "14", viewBox: "0 0 20 20", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("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" }) })
@@ -3079,7 +3114,7 @@ function OnboardingCard({ onDismiss, closing }) {
3079
3114
  /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("strong", { children: "Primary" }),
3080
3115
  " keyword (required) and, optionally, one ",
3081
3116
  /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("strong", { children: "Secondary" }),
3082
- " keyword. Copilot then optimizes the whole article - title, meta, URL, headings, and images - toward both."
3117
+ " keyword. Copilot then optimizes its recommendations toward both."
3083
3118
  ] }),
3084
3119
  /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
3085
3120
  "button",
@@ -3156,6 +3191,13 @@ function ShimmerLoader({
3156
3191
  style.dataset.seoCopilotKeyframes = "1";
3157
3192
  style.innerHTML = KEYFRAMES;
3158
3193
  document.head.appendChild(style);
3194
+ return () => {
3195
+ try {
3196
+ document.head.removeChild(style);
3197
+ } catch {
3198
+ }
3199
+ keyframesInjected = false;
3200
+ };
3159
3201
  }
3160
3202
  }, []);
3161
3203
  (0, import_react12.useEffect)(() => {
@@ -3263,7 +3305,7 @@ function calculateContentScoreDetailed(content, analysis, documentFields) {
3263
3305
  }
3264
3306
  const supportingKws = analysis.supportingKeywords || [];
3265
3307
  if (supportingKws.length > 0) {
3266
- const inContentCount = supportingKws.filter((kw) => lowerContent.includes(kw.term.toLowerCase())).length;
3308
+ const inContentCount = supportingKws.filter((kw) => kw != null && typeof kw.term === "string" && lowerContent.includes(kw.term.toLowerCase())).length;
3267
3309
  const coverageRatio = inContentCount / supportingKws.length;
3268
3310
  const pts = Math.round(coverageRatio * 25);
3269
3311
  components.push({
@@ -3336,8 +3378,8 @@ function calculateContentScoreDetailed(content, analysis, documentFields) {
3336
3378
  return { total: Math.min(100, Math.max(0, total)), components };
3337
3379
  }
3338
3380
 
3339
- // src/lib/summary.ts
3340
- function tokensContain(haystack, needle) {
3381
+ // src/lib/utils.ts
3382
+ function containsKeywordTokens(haystack, needle) {
3341
3383
  if (!needle) return true;
3342
3384
  const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
3343
3385
  if (tokens.length === 0) return true;
@@ -3345,6 +3387,7 @@ function tokensContain(haystack, needle) {
3345
3387
  return tokens.every((t) => lower.includes(t));
3346
3388
  }
3347
3389
  function keywordLeadsSlug(slug, primaryKeyword) {
3390
+ if (!primaryKeyword) return true;
3348
3391
  const slugWords = slug.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);
3349
3392
  const tokens = primaryKeyword.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
3350
3393
  if (tokens.length === 0 || slugWords.length === 0) return true;
@@ -3355,6 +3398,15 @@ function keywordLeadsSlug(slug, primaryKeyword) {
3355
3398
  }
3356
3399
  return earliest <= 2;
3357
3400
  }
3401
+ var KNOWN_MJH_PUBLICATIONS = /* @__PURE__ */ new Set([
3402
+ "onclive",
3403
+ "hcplive",
3404
+ "ajmc",
3405
+ "pharmacytimes",
3406
+ "cancernetwork"
3407
+ ]);
3408
+
3409
+ // src/lib/summary.ts
3358
3410
  function isShortFormContent(documentFields, title) {
3359
3411
  const cat = (documentFields?.contentCategory || "").toLowerCase().trim();
3360
3412
  if (/^(videos?|podcasts?|episodes?|webinars?|video series|peer exchange)$/.test(cat)) return true;
@@ -3371,6 +3423,13 @@ function buildSummaryItems(input) {
3371
3423
  const { analysis, deepAnalysis, documentFields, linkingSuggestions, linkCheckResults, text } = input;
3372
3424
  const primaryKeyword = input.primaryKeyword || analysis?.primaryKeyword?.term;
3373
3425
  const secondaryKeyword = input.secondaryKeyword || "";
3426
+ const bodyText = (() => {
3427
+ if (!documentFields?.title) return text;
3428
+ if (!text.startsWith(documentFields.title)) return text;
3429
+ const rest = text.slice(documentFields.title.length);
3430
+ if (rest === "" || /^\s/.test(rest)) return rest.trimStart();
3431
+ return text;
3432
+ })();
3374
3433
  const title = documentFields?.title;
3375
3434
  if (!title) {
3376
3435
  items.push({
@@ -3383,7 +3442,7 @@ function buildSummaryItems(input) {
3383
3442
  jumpTo: { tab: "meta", anchorId: "anchor-meta-title" }
3384
3443
  });
3385
3444
  } else if (primaryKeyword) {
3386
- if (!tokensContain(title, primaryKeyword)) {
3445
+ if (!containsKeywordTokens(title, primaryKeyword)) {
3387
3446
  items.push({
3388
3447
  id: "meta-title-no-keyword",
3389
3448
  category: "meta",
@@ -3449,7 +3508,7 @@ function buildSummaryItems(input) {
3449
3508
  jumpTo: { tab: "meta", anchorId: "anchor-meta-description" }
3450
3509
  });
3451
3510
  }
3452
- if (primaryKeyword && !tokensContain(meta, primaryKeyword)) {
3511
+ if (primaryKeyword && !containsKeywordTokens(meta, primaryKeyword)) {
3453
3512
  items.push({
3454
3513
  id: "meta-desc-no-keyword",
3455
3514
  category: "meta",
@@ -3474,7 +3533,7 @@ function buildSummaryItems(input) {
3474
3533
  });
3475
3534
  } else {
3476
3535
  const slugAsWords = slug.replace(/-/g, " ");
3477
- if (primaryKeyword && !tokensContain(slugAsWords, primaryKeyword)) {
3536
+ if (primaryKeyword && !containsKeywordTokens(slugAsWords, primaryKeyword)) {
3478
3537
  items.push({
3479
3538
  id: "meta-slug-no-keyword",
3480
3539
  category: "meta",
@@ -3496,7 +3555,7 @@ function buildSummaryItems(input) {
3496
3555
  });
3497
3556
  }
3498
3557
  }
3499
- const wordCount2 = text ? text.trim().split(/\s+/).filter(Boolean).length : 0;
3558
+ const wordCount2 = bodyText ? bodyText.trim().split(/\s+/).filter(Boolean).length : 0;
3500
3559
  const isShortForm = isShortFormContent(documentFields, title);
3501
3560
  if (wordCount2 === 0) {
3502
3561
  } else if (wordCount2 < 450 && !isShortForm) {
@@ -3523,7 +3582,7 @@ function buildSummaryItems(input) {
3523
3582
  const headings = documentFields?.headings || [];
3524
3583
  const headingsDetailed = documentFields?.headingsDetailed;
3525
3584
  const h2Count = headingsDetailed ? headingsDetailed.filter((h) => h.level === 2 || h.level === 3).length : headings.length;
3526
- if (headings.length === 0 && wordCount2 > 200 && wordCount2 < 1e3) {
3585
+ if (h2Count === 0 && wordCount2 > 200 && wordCount2 < 1e3) {
3527
3586
  items.push({
3528
3587
  id: "headings-missing",
3529
3588
  category: "headings",
@@ -3629,7 +3688,7 @@ function buildSummaryItems(input) {
3629
3688
  if (GENERIC_FN_RE.test(base)) return true;
3630
3689
  if (/_/.test(base) || /\s/.test(base)) return true;
3631
3690
  const words = base.split("-").filter(Boolean);
3632
- return words.length < 2 || words.length > 7;
3691
+ return words.length < 2 || words.length > 5;
3633
3692
  });
3634
3693
  if (badFilenames.length > 0) {
3635
3694
  items.push({
@@ -3647,7 +3706,7 @@ function buildSummaryItems(input) {
3647
3706
  if (!trimmed) return false;
3648
3707
  const len = trimmed.length;
3649
3708
  const wc = trimmed.split(/\s+/).filter(Boolean).length;
3650
- return len > 125 || wc < 2;
3709
+ return len >= 125 || wc < 2;
3651
3710
  });
3652
3711
  if (badAlts.length > 0) {
3653
3712
  items.push({
@@ -3676,7 +3735,7 @@ function buildSummaryItems(input) {
3676
3735
  }
3677
3736
  if (!primaryKeyword) {
3678
3737
  } else {
3679
- if (text && !tokensContain(text, primaryKeyword)) {
3738
+ if (bodyText && !containsKeywordTokens(bodyText, primaryKeyword)) {
3680
3739
  items.push({
3681
3740
  id: "keywords-primary-not-in-body",
3682
3741
  category: "keywords",
@@ -3701,7 +3760,7 @@ function buildSummaryItems(input) {
3701
3760
  }
3702
3761
  }
3703
3762
  if (secondaryKeyword) {
3704
- if (text && !tokensContain(text, secondaryKeyword)) {
3763
+ if (bodyText && !containsKeywordTokens(bodyText, secondaryKeyword)) {
3705
3764
  items.push({
3706
3765
  id: "secondary-not-in-body",
3707
3766
  category: "keywords",
@@ -3713,19 +3772,19 @@ function buildSummaryItems(input) {
3713
3772
  });
3714
3773
  }
3715
3774
  const titleVal = documentFields?.title;
3716
- if (titleVal && !tokensContain(titleVal, secondaryKeyword)) {
3775
+ if (titleVal && !containsKeywordTokens(titleVal, secondaryKeyword)) {
3717
3776
  items.push({
3718
3777
  id: "secondary-not-in-title",
3719
3778
  category: "meta",
3720
3779
  severity: "opportunity",
3721
3780
  label: "Secondary keyword not in title",
3722
- description: `The title leads with the primary keyword but doesn't include "${secondaryKeyword}".`,
3781
+ description: `The title doesn't include your secondary keyword "${secondaryKeyword}".`,
3723
3782
  howToFix: "If it fits naturally, include the secondary keyword in the title too - but never at the cost of the primary leading.",
3724
3783
  jumpTo: { tab: "meta", anchorId: "anchor-meta-title" }
3725
3784
  });
3726
3785
  }
3727
3786
  const metaVal = documentFields?.metaDescription;
3728
- if (metaVal && !tokensContain(metaVal, secondaryKeyword)) {
3787
+ if (metaVal && !containsKeywordTokens(metaVal, secondaryKeyword)) {
3729
3788
  items.push({
3730
3789
  id: "secondary-not-in-meta",
3731
3790
  category: "meta",
@@ -3737,7 +3796,7 @@ function buildSummaryItems(input) {
3737
3796
  });
3738
3797
  }
3739
3798
  const slugVal = documentFields?.slug;
3740
- if (slugVal && !tokensContain(slugVal.replace(/-/g, " "), secondaryKeyword)) {
3799
+ if (slugVal && !containsKeywordTokens(slugVal.replace(/-/g, " "), secondaryKeyword)) {
3741
3800
  items.push({
3742
3801
  id: "secondary-not-in-url",
3743
3802
  category: "meta",
@@ -4048,7 +4107,7 @@ function SummaryTab({
4048
4107
  }) {
4049
4108
  const scoreDetail = (0, import_react13.useMemo)(() => {
4050
4109
  if (!analysis) return null;
4051
- const scored = primaryKeyword && primaryKeyword !== analysis.primaryKeyword?.term ? { ...analysis, primaryKeyword: { ...analysis.primaryKeyword, term: primaryKeyword } } : analysis;
4110
+ const scored = primaryKeyword && analysis.primaryKeyword && primaryKeyword !== analysis.primaryKeyword.term ? { ...analysis, primaryKeyword: { ...analysis.primaryKeyword, term: primaryKeyword } } : analysis;
4052
4111
  return calculateContentScoreDetailed(text, scored, documentFields);
4053
4112
  }, [text, analysis, documentFields, primaryKeyword]);
4054
4113
  const score = scoreDetail?.total ?? null;
@@ -4271,11 +4330,17 @@ function SectionHeader2({ label, iconColor, ai }) {
4271
4330
  }
4272
4331
  function CopyButton({ text }) {
4273
4332
  const [copied, setCopied] = (0, import_react14.useState)(false);
4333
+ const copyTimerRef = (0, import_react14.useRef)(null);
4334
+ (0, import_react14.useEffect)(() => {
4335
+ return () => {
4336
+ if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
4337
+ };
4338
+ }, []);
4274
4339
  const handleCopy = async () => {
4275
4340
  try {
4276
4341
  await navigator.clipboard.writeText(text);
4277
4342
  setCopied(true);
4278
- setTimeout(() => setCopied(false), 1500);
4343
+ copyTimerRef.current = setTimeout(() => setCopied(false), 1500);
4279
4344
  } catch {
4280
4345
  }
4281
4346
  };
@@ -4834,8 +4899,8 @@ var import_jsx_runtime13 = require("react/jsx-runtime");
4834
4899
  function buildLiveUrl(publication, slug) {
4835
4900
  if (!slug) return null;
4836
4901
  const pub = (publication || "").trim().toLowerCase();
4837
- if (!/^[a-z0-9-]+$/.test(pub)) return null;
4838
- const cleanSlug = slug.replace(/^\/+/, "");
4902
+ if (!KNOWN_MJH_PUBLICATIONS.has(pub)) return null;
4903
+ const cleanSlug = slug.replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
4839
4904
  return `https://www.${pub}.com/view/${cleanSlug}`;
4840
4905
  }
4841
4906
  function buildSanityUrl(baseUrl, id, type) {
@@ -4932,6 +4997,7 @@ function freshnessChip(label, score) {
4932
4997
  "very-old": { bg: "rgba(220,38,38,0.1)", color: "#dc2626", text: "Very old" }
4933
4998
  };
4934
4999
  const c = map[label];
5000
+ if (!c) return null;
4935
5001
  return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
4936
5002
  "span",
4937
5003
  {
@@ -5033,7 +5099,15 @@ function LinkingTab({
5033
5099
  isStale && suggestions.length > 0 && !isLoading && /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(
5034
5100
  "div",
5035
5101
  {
5102
+ role: "button",
5103
+ tabIndex: 0,
5036
5104
  onClick: onRefresh,
5105
+ onKeyDown: (e) => {
5106
+ if (e.key === "Enter" || e.key === " ") {
5107
+ e.preventDefault();
5108
+ onRefresh();
5109
+ }
5110
+ },
5037
5111
  style: {
5038
5112
  display: "flex",
5039
5113
  alignItems: "center",
@@ -5110,10 +5184,10 @@ function LinkingTab({
5110
5184
  ScoreDonut,
5111
5185
  {
5112
5186
  size: 64,
5113
- topic: s.topicScore,
5114
- freshness: s.freshnessScore,
5115
- sectionFit: s.sectionFitScore,
5116
- composite: s.compositeScore
5187
+ topic: Math.max(0, Math.min(100, s.topicScore)),
5188
+ freshness: Math.max(0, Math.min(100, s.freshnessScore)),
5189
+ sectionFit: Math.max(0, Math.min(100, s.sectionFitScore)),
5190
+ composite: Math.max(0, Math.min(100, s.compositeScore))
5117
5191
  }
5118
5192
  ),
5119
5193
  /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { style: { flex: 1, minWidth: 0 }, children: [
@@ -5128,7 +5202,7 @@ function LinkingTab({
5128
5202
  ] }),
5129
5203
  (() => {
5130
5204
  const liveUrl = buildLiveUrl(publication, s.slug);
5131
- const sanityUrl = buildSanityUrl(sanityBaseUrl, s._id, documentType);
5205
+ const sanityUrl = buildSanityUrl(sanityBaseUrl, s._id);
5132
5206
  if (!liveUrl && !sanityUrl) return null;
5133
5207
  return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { style: { display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 6 }, children: [
5134
5208
  sanityUrl && /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(LinkChip, { href: sanityUrl, label: "Inside Sanity", color: MJH_BLUE }),
@@ -5187,13 +5261,6 @@ function LinkingTab({
5187
5261
  // src/components/tabs/MetaTab.tsx
5188
5262
  var import_react16 = require("react");
5189
5263
  var import_jsx_runtime14 = require("react/jsx-runtime");
5190
- function containsKeywordTokens(haystack, needle) {
5191
- if (!needle) return true;
5192
- const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
5193
- if (tokens.length === 0) return true;
5194
- const lower = haystack.toLowerCase();
5195
- return tokens.every((t) => lower.includes(t));
5196
- }
5197
5264
  var cardStyle5 = {
5198
5265
  borderRadius: 14,
5199
5266
  background: "rgba(255,255,255,0.55)",
@@ -5275,7 +5342,7 @@ function keywordCoverageNote(haystack, primaryKeyword, secondaryKeyword) {
5275
5342
  return `Your primary keyword "${primaryKeyword}" isn't included${secondaryKeyword ? ` (secondary keyword "${secondaryKeyword}" ${hasSecondary ? "is" : "isn't"}).` : "."}`;
5276
5343
  }
5277
5344
  if (secondaryKeyword && !hasSecondary) {
5278
- return `Your primary keyword "${primaryKeyword}" is included, but your secondary keyword "${secondaryKeyword}" is not. Work it in if it reads naturally.`;
5345
+ return `Your secondary keyword "${secondaryKeyword}" isn't included${primaryKeyword && hasPrimary ? ` (primary keyword "${primaryKeyword}" is present)` : ""}. Work it in if it reads naturally.`;
5279
5346
  }
5280
5347
  return "";
5281
5348
  }
@@ -5464,25 +5531,6 @@ function MetaTab({ documentFields, primaryKeyword, secondaryKeyword, isLoading }
5464
5531
  // src/components/tabs/TechnicalTab.tsx
5465
5532
  var import_react17 = require("react");
5466
5533
  var import_jsx_runtime15 = require("react/jsx-runtime");
5467
- function containsKeywordTokens2(haystack, needle) {
5468
- if (!needle) return true;
5469
- const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
5470
- if (tokens.length === 0) return true;
5471
- const lower = haystack.toLowerCase();
5472
- return tokens.every((t) => lower.includes(t));
5473
- }
5474
- function keywordLeadsUrl(slug, primaryKeyword) {
5475
- if (!primaryKeyword) return true;
5476
- const slugWords = slug.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);
5477
- const tokens = primaryKeyword.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
5478
- if (tokens.length === 0 || slugWords.length === 0) return true;
5479
- let earliest = Infinity;
5480
- for (const t of tokens) {
5481
- const idx = slugWords.findIndex((w) => w.includes(t));
5482
- if (idx >= 0) earliest = Math.min(earliest, idx);
5483
- }
5484
- return earliest <= 2;
5485
- }
5486
5534
  function urlAudit(slug, primaryKeyword, secondaryKeyword) {
5487
5535
  const SHORT_DESC = "Keep the URL short and descriptive - concise URLs are easier to read - and avoid trailing, duplicate, or excessive spaces.";
5488
5536
  if (!slug) {
@@ -5494,9 +5542,9 @@ function urlAudit(slug, primaryKeyword, secondaryKeyword) {
5494
5542
  };
5495
5543
  }
5496
5544
  const slugAsWords = slug.replace(/-/g, " ");
5497
- const hasPrimary = primaryKeyword ? containsKeywordTokens2(slugAsWords, primaryKeyword) : true;
5498
- const leads = primaryKeyword ? keywordLeadsUrl(slug, primaryKeyword) : true;
5499
- const hasSecondary = secondaryKeyword ? containsKeywordTokens2(slugAsWords, secondaryKeyword) : true;
5545
+ const hasPrimary = primaryKeyword ? containsKeywordTokens(slugAsWords, primaryKeyword) : true;
5546
+ const leads = primaryKeyword ? keywordLeadsSlug(slug, primaryKeyword) : true;
5547
+ const hasSecondary = secondaryKeyword ? containsKeywordTokens(slugAsWords, secondaryKeyword) : true;
5500
5548
  if (primaryKeyword && !hasPrimary) {
5501
5549
  const secNote = secondaryKeyword && !hasSecondary ? ` Your secondary keyword "${secondaryKeyword}" could follow it.` : "";
5502
5550
  return {
@@ -5651,7 +5699,7 @@ function imageFilenameAudit(filenames) {
5651
5699
  const words = base.split("-").filter(Boolean);
5652
5700
  if (words.length < 2) {
5653
5701
  issues.push({ filename: f, reason: "single word - use 2-3 descriptive hyphenated words" });
5654
- } else if (words.length > 7) {
5702
+ } else if (words.length > 5) {
5655
5703
  issues.push({ filename: f, reason: "too many words - keep to 3-5" });
5656
5704
  }
5657
5705
  }
@@ -5680,7 +5728,7 @@ function imageAltTextAudit(altTexts) {
5680
5728
  audited++;
5681
5729
  const len = trimmed.length;
5682
5730
  const wc = trimmed.split(/\s+/).filter(Boolean).length;
5683
- if (len > 125) {
5731
+ if (len >= 125) {
5684
5732
  issues.push({ alt: trimmed, reason: `${len} chars - shorten to under 125` });
5685
5733
  } else if (wc < 2) {
5686
5734
  issues.push({ alt: trimmed, reason: "just one word - use 2-5 descriptive keywords" });
@@ -6093,7 +6141,10 @@ function TechnicalTab({
6093
6141
  );
6094
6142
  const headings = documentFields?.headings || [];
6095
6143
  const headingsDetailed = documentFields?.headingsDetailed;
6096
- const headingsForStructure = headingsDetailed ? headingsDetailed : headings.map((text2) => ({ text: text2, level: 2 }));
6144
+ const headingsForStructure = (0, import_react17.useMemo)(
6145
+ () => headingsDetailed ? headingsDetailed : headings.map((text2) => ({ text: text2, level: 2 })),
6146
+ [headingsDetailed, headings]
6147
+ );
6097
6148
  const wordCount2 = text ? text.split(/\s+/).filter(Boolean).length : 0;
6098
6149
  const structureAudits = (0, import_react17.useMemo)(
6099
6150
  () => computeHeadingStructureAudits(headingsForStructure, wordCount2),
@@ -6201,9 +6252,9 @@ function TechnicalTab({
6201
6252
  },
6202
6253
  i
6203
6254
  )),
6204
- headings.length > 12 && /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { fontSize: 10, color: "#4b5563" }, children: [
6255
+ (headingsDetailed ?? headings).length > 12 && /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { fontSize: 10, color: "#4b5563" }, children: [
6205
6256
  "+ ",
6206
- headings.length - 12,
6257
+ (headingsDetailed ?? headings).length - 12,
6207
6258
  " more"
6208
6259
  ] })
6209
6260
  ] })
@@ -6343,6 +6394,7 @@ function PanelContent({
6343
6394
  const [popupMode, setPopupMode] = (0, import_react18.useState)("hidden");
6344
6395
  const [popupClosing, setPopupClosing] = (0, import_react18.useState)(false);
6345
6396
  const onboardTimerRef = (0, import_react18.useRef)(null);
6397
+ const onboardFadeRef = (0, import_react18.useRef)(null);
6346
6398
  (0, import_react18.useEffect)(() => {
6347
6399
  let onboarded = false;
6348
6400
  let shownThisSession = false;
@@ -6362,14 +6414,15 @@ function PanelContent({
6362
6414
  }
6363
6415
  onboardTimerRef.current = setTimeout(() => {
6364
6416
  setPopupClosing(true);
6365
- setTimeout(() => {
6417
+ onboardFadeRef.current = setTimeout(() => {
6366
6418
  setPopupMode("hidden");
6367
6419
  setPopupClosing(false);
6368
6420
  }, 180);
6369
- }, 5e3);
6421
+ }, 8e3);
6370
6422
  }
6371
6423
  return () => {
6372
6424
  if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
6425
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
6373
6426
  };
6374
6427
  }, [onboardKey, onboardSessionKey]);
6375
6428
  const markOnboarded = (0, import_react18.useCallback)(() => {
@@ -6380,15 +6433,17 @@ function PanelContent({
6380
6433
  }, [onboardKey]);
6381
6434
  const dismissPopup = (0, import_react18.useCallback)(() => {
6382
6435
  if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
6436
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
6383
6437
  markOnboarded();
6384
6438
  setPopupClosing(true);
6385
- setTimeout(() => {
6439
+ onboardFadeRef.current = setTimeout(() => {
6386
6440
  setPopupMode("hidden");
6387
6441
  setPopupClosing(false);
6388
6442
  }, 180);
6389
6443
  }, [markOnboarded]);
6390
6444
  const openPopupPersistent = (0, import_react18.useCallback)(() => {
6391
6445
  if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
6446
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
6392
6447
  markOnboarded();
6393
6448
  setPopupClosing(false);
6394
6449
  setPopupMode("persistent");
@@ -6396,7 +6451,12 @@ function PanelContent({
6396
6451
  const handleTabChange = (0, import_react18.useCallback)((id) => {
6397
6452
  markOnboarded();
6398
6453
  if (onboardTimerRef.current) clearTimeout(onboardTimerRef.current);
6399
- setPopupMode((m) => m === "hidden" ? m : "hidden");
6454
+ if (onboardFadeRef.current) clearTimeout(onboardFadeRef.current);
6455
+ setPopupClosing(true);
6456
+ onboardFadeRef.current = setTimeout(() => {
6457
+ setPopupMode("hidden");
6458
+ setPopupClosing(false);
6459
+ }, 120);
6400
6460
  onActiveTabChange(id);
6401
6461
  }, [markOnboarded, onActiveTabChange]);
6402
6462
  const tabDefs = [
@@ -6836,6 +6896,8 @@ function SEOCopilotInner({ config, onClose }) {
6836
6896
  );
6837
6897
  const dragOffset = (0, import_react18.useRef)(null);
6838
6898
  const resizeStart = (0, import_react18.useRef)(null);
6899
+ const activeDragCleanupRef = (0, import_react18.useRef)(null);
6900
+ const activeResizeCleanupRef = (0, import_react18.useRef)(null);
6839
6901
  const { text, isLoading: docLoading, documentFields, documentId, documentType } = useDocumentContent();
6840
6902
  const { apiUrl } = useConfig();
6841
6903
  const workspace = (0, import_sanity3.useWorkspace)();
@@ -6883,6 +6945,11 @@ function SEOCopilotInner({ config, onClose }) {
6883
6945
  const [splitPercent, setSplitPercent] = usePersistentState("seo-copilot-ui-split", 70);
6884
6946
  const keywordAnalysisState = useKeywordAnalysis(text, apiUrl, effectivePublication, seedKeywords, documentFields, selectedPrimary, documentId);
6885
6947
  const effectivePrimary = selectedPrimary || keywordAnalysisState.analysis?.primaryKeyword?.term || "";
6948
+ (0, import_react18.useEffect)(() => {
6949
+ if (selectedSecondary && effectivePrimary && selectedSecondary.toLowerCase() === effectivePrimary.toLowerCase()) {
6950
+ setSelectedSecondary("");
6951
+ }
6952
+ }, [effectivePrimary, selectedSecondary, setSelectedSecondary]);
6886
6953
  const keywordPanelData = (0, import_react18.useMemo)(() => {
6887
6954
  const analysis = keywordAnalysisState.analysis;
6888
6955
  if (!analysis) return void 0;
@@ -6904,6 +6971,7 @@ function SEOCopilotInner({ config, onClose }) {
6904
6971
  const [isCSLoading, setIsCSLoading] = (0, import_react18.useState)(false);
6905
6972
  const [csError, setCsError] = (0, import_react18.useState)(null);
6906
6973
  const aeoOpVersionRef = (0, import_react18.useRef)(0);
6974
+ const csAbortRef = (0, import_react18.useRef)(null);
6907
6975
  const didInitAeoRef = (0, import_react18.useRef)(false);
6908
6976
  (0, import_react18.useEffect)(() => {
6909
6977
  if (!didInitAeoRef.current) {
@@ -6919,7 +6987,11 @@ function SEOCopilotInner({ config, onClose }) {
6919
6987
  setIsCSLoading(true);
6920
6988
  setCsError(null);
6921
6989
  try {
6922
- const data = await fetchContentSuggestions(apiUrl, text, effectivePrimary, effectivePublication);
6990
+ csAbortRef.current?.abort();
6991
+ const csController = new AbortController();
6992
+ csAbortRef.current = csController;
6993
+ const data = await fetchContentSuggestions(apiUrl, text, effectivePrimary, effectivePublication, csController.signal);
6994
+ if (csController.signal.aborted) return;
6923
6995
  if (aeoOpVersionRef.current !== myVersion) return;
6924
6996
  if (data.keyTakeaways.length === 0 && data.infographicOpportunities.length === 0 && data.bulletListItems.length === 0) {
6925
6997
  setCsError("No suggestions returned. Try again with more content.");
@@ -6939,6 +7011,7 @@ function SEOCopilotInner({ config, onClose }) {
6939
7011
  const [linkingError, setLinkingError] = (0, import_react18.useState)(null);
6940
7012
  const [linkingFetchedText, setLinkingFetchedText] = (0, import_react18.useState)("");
6941
7013
  const linkingVersionRef = (0, import_react18.useRef)(0);
7014
+ const linkingAbortRef = (0, import_react18.useRef)(null);
6942
7015
  const didInitLinkingRef = (0, import_react18.useRef)(false);
6943
7016
  const lastLinkingFetchKey = (0, import_react18.useRef)("");
6944
7017
  (0, import_react18.useEffect)(() => {
@@ -6963,14 +7036,19 @@ function SEOCopilotInner({ config, onClose }) {
6963
7036
  setIsLinkingLoading(true);
6964
7037
  setLinkingError(null);
6965
7038
  try {
7039
+ linkingAbortRef.current?.abort();
7040
+ const linkingController = new AbortController();
7041
+ linkingAbortRef.current = linkingController;
6966
7042
  const suggestions = await fetchLinkingSuggestions(
6967
7043
  apiUrl,
6968
7044
  text,
6969
7045
  effectivePrimary,
6970
7046
  supportingKeywordsForLinking,
6971
7047
  documentId,
6972
- effectivePublication
7048
+ effectivePublication,
7049
+ linkingController.signal
6973
7050
  );
7051
+ if (linkingController.signal.aborted) return;
6974
7052
  if (linkingVersionRef.current !== myVersion) return;
6975
7053
  setLinkingSuggestions(suggestions);
6976
7054
  setLinkingFetchedText(text);
@@ -7039,6 +7117,14 @@ function SEOCopilotInner({ config, onClose }) {
7039
7117
  if (linkCheckVersionRef.current !== myVersion) return;
7040
7118
  setIsLinkCheckLoading(false);
7041
7119
  }, [apiUrl, documentFields?.bodyLinks, setHasRunLinkCheck, setLinkCheckResults]);
7120
+ (0, import_react18.useEffect)(() => {
7121
+ return () => {
7122
+ activeDragCleanupRef.current?.();
7123
+ activeResizeCleanupRef.current?.();
7124
+ csAbortRef.current?.abort();
7125
+ linkingAbortRef.current?.abort();
7126
+ };
7127
+ }, []);
7042
7128
  const handleDragStart = (0, import_react18.useCallback)(
7043
7129
  (e) => {
7044
7130
  dragOffset.current = {
@@ -7053,6 +7139,7 @@ function SEOCopilotInner({ config, onClose }) {
7053
7139
  });
7054
7140
  };
7055
7141
  const onMouseUp = () => {
7142
+ activeDragCleanupRef.current = null;
7056
7143
  dragOffset.current = null;
7057
7144
  window.removeEventListener("mousemove", onMouseMove);
7058
7145
  window.removeEventListener("mouseup", onMouseUp);
@@ -7063,6 +7150,12 @@ function SEOCopilotInner({ config, onClose }) {
7063
7150
  document.body.style.userSelect = "none";
7064
7151
  window.addEventListener("mousemove", onMouseMove);
7065
7152
  window.addEventListener("mouseup", onMouseUp);
7153
+ activeDragCleanupRef.current = () => {
7154
+ window.removeEventListener("mousemove", onMouseMove);
7155
+ window.removeEventListener("mouseup", onMouseUp);
7156
+ document.body.style.cursor = "";
7157
+ document.body.style.userSelect = "";
7158
+ };
7066
7159
  },
7067
7160
  [floatPos]
7068
7161
  );
@@ -7080,6 +7173,7 @@ function SEOCopilotInner({ config, onClose }) {
7080
7173
  setFloatSize({ width: newW, height: newH });
7081
7174
  };
7082
7175
  const onMouseUp = () => {
7176
+ activeResizeCleanupRef.current = null;
7083
7177
  resizeStart.current = null;
7084
7178
  document.body.style.cursor = "";
7085
7179
  document.body.style.userSelect = "";
@@ -7088,6 +7182,12 @@ function SEOCopilotInner({ config, onClose }) {
7088
7182
  };
7089
7183
  window.addEventListener("mousemove", onMouseMove);
7090
7184
  window.addEventListener("mouseup", onMouseUp);
7185
+ activeResizeCleanupRef.current = () => {
7186
+ window.removeEventListener("mousemove", onMouseMove);
7187
+ window.removeEventListener("mouseup", onMouseUp);
7188
+ document.body.style.cursor = "";
7189
+ document.body.style.userSelect = "";
7190
+ };
7091
7191
  },
7092
7192
  [floatSize]
7093
7193
  );
@@ -7313,8 +7413,7 @@ function seoCopilotInspector(config) {
7313
7413
  name: "seo-copilot",
7314
7414
  useMenuItem: () => ({
7315
7415
  title: "SEO Copilot",
7316
- icon: SEOIcon,
7317
- showAsAction: true
7416
+ icon: SEOIcon
7318
7417
  }),
7319
7418
  component: function SEOCopilotInspector(props) {
7320
7419
  return (0, import_react19.createElement)(SEOCopilotPanel, { ...props, config });