sanity-plugin-seo-copilot 0.2.1 → 0.2.7

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.
@@ -1,11 +1,14 @@
1
- import { useMemo } from "react";
1
+ import { useMemo, useState } from "react";
2
2
  import { LoadingBars } from "../SEOCopilotPanel";
3
3
  import { MJH_BLUE, MJH_GOLD } from "../styles";
4
4
  import type { DocumentFields, HeadingItem, LinkCheckResult, TechnicalAuditItem } from "../../lib/types";
5
+ import { isShortFormContent } from "../../lib/summary";
5
6
 
6
7
  interface TechnicalTabProps {
7
8
  text: string;
8
9
  documentFields?: DocumentFields;
10
+ primaryKeyword?: string;
11
+ secondaryKeyword?: string;
9
12
  isLoading?: boolean;
10
13
  // Link-check state lifted to the panel so results survive tab switches and re-mount.
11
14
  linkCheckResults: LinkCheckResult[];
@@ -15,6 +18,111 @@ interface TechnicalTabProps {
15
18
  onCheckLinks: () => void;
16
19
  }
17
20
 
21
+ // Token-based keyword match so "selinexor in myelofibrosis" still counts as containing
22
+ // "selinexor myelofibrosis" (word order / connecting words don't matter).
23
+ function containsKeywordTokens(haystack: string, needle?: string): boolean {
24
+ if (!needle) return true;
25
+ const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
26
+ if (tokens.length === 0) return true;
27
+ const lower = haystack.toLowerCase();
28
+ return tokens.every((t) => lower.includes(t));
29
+ }
30
+
31
+ // True when the primary keyword sits near the START of the slug. Editors get the
32
+ // most SEO/CTR value when the keyword leads the URL (and it survives truncation).
33
+ function keywordLeadsUrl(slug: string, primaryKeyword?: string): boolean {
34
+ if (!primaryKeyword) return true;
35
+ const slugWords = slug.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);
36
+ const tokens = primaryKeyword.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
37
+ if (tokens.length === 0 || slugWords.length === 0) return true;
38
+ let earliest = Infinity;
39
+ for (const t of tokens) {
40
+ const idx = slugWords.findIndex((w) => w.includes(t));
41
+ if (idx >= 0) earliest = Math.min(earliest, idx);
42
+ }
43
+ return earliest <= 2; // within the first three slug words
44
+ }
45
+
46
+ // URL Slug audit (moved here from Meta per the 6/10 director notes). Deliberately
47
+ // vague and non-numeric: we never cite a character count or say "too long" - just
48
+ // scan for the primary keyword (ideally leading the URL) and nudge toward short,
49
+ // descriptive slugs.
50
+ function urlAudit(slug?: string, primaryKeyword?: string, secondaryKeyword?: string): TechnicalAuditItem {
51
+ const SHORT_DESC = "Keep the URL short and descriptive - concise URLs are easier to read - and avoid trailing, duplicate, or excessive spaces.";
52
+ if (!slug) {
53
+ return {
54
+ label: "URL Slug",
55
+ value: "Missing",
56
+ status: "warning",
57
+ recommendation: `Add a URL slug that leads with your primary keyword. ${SHORT_DESC}`,
58
+ };
59
+ }
60
+ const slugAsWords = slug.replace(/-/g, " ");
61
+ const hasPrimary = primaryKeyword ? containsKeywordTokens(slugAsWords, primaryKeyword) : true;
62
+ const leads = primaryKeyword ? keywordLeadsUrl(slug, primaryKeyword) : true;
63
+ const hasSecondary = secondaryKeyword ? containsKeywordTokens(slugAsWords, secondaryKeyword) : true;
64
+
65
+ if (primaryKeyword && !hasPrimary) {
66
+ const secNote = secondaryKeyword && !hasSecondary ? ` Your secondary keyword "${secondaryKeyword}" could follow it.` : "";
67
+ return {
68
+ label: "URL Slug",
69
+ value: `/${slug}`,
70
+ status: "warning",
71
+ recommendation: `Work your primary keyword "${primaryKeyword}" into the URL, ideally at the start - if the address gets shortened, a leading keyword still shows.${secNote} ${SHORT_DESC}`,
72
+ };
73
+ }
74
+ if (primaryKeyword && hasPrimary && !leads) {
75
+ return {
76
+ label: "URL Slug",
77
+ value: `/${slug}`,
78
+ status: "warning",
79
+ recommendation: `Your primary keyword is in the URL but not at the start. Leading with it reads better and holds up if the address gets shortened. ${SHORT_DESC}`,
80
+ };
81
+ }
82
+ // Primary leads (or no primary set). Clean pass.
83
+ return { label: "URL Slug", value: `/${slug}`, status: "good" };
84
+ }
85
+
86
+ // Caution block that lives INSIDE the URL Slug card. Changing an indexed page's
87
+ // slug without a 301 redirect drops its search rankings to zero and breaks every
88
+ // external link to the old URL - a warning (avoidable), not an error.
89
+ function SlugRedirectNotice() {
90
+ const [expanded, setExpanded] = useState(false);
91
+ return (
92
+ <div style={{ marginTop: 10, paddingTop: 10, borderTop: "1px solid rgba(0,0,0,0.07)" }}>
93
+ <div style={{ padding: "8px 10px", background: "rgba(245,158,11,0.08)", borderLeft: "2px solid #f59e0b", borderRadius: 6 }}>
94
+ <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
95
+ <svg width="12" height="12" viewBox="0 0 20 20" fill="#f59e0b" aria-hidden="true">
96
+ <path fillRule="evenodd" d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z" clipRule="evenodd" />
97
+ </svg>
98
+ <span style={{ fontSize: 10.5, fontWeight: 700, color: "#b45309", textTransform: "uppercase", letterSpacing: "0.06em" }}>
99
+ Changing a URL?
100
+ </span>
101
+ </div>
102
+ <div style={{ fontSize: 11, color: "#1f2937", lineHeight: 1.55 }}>
103
+ If the page has been published and indexed, you MUST add a 301 redirect from the old slug to the new one before changing it. For a brand-new page that's never been published, no redirect needed.
104
+ </div>
105
+ <button
106
+ onClick={() => setExpanded((v) => !v)}
107
+ style={{ display: "flex", alignItems: "center", gap: 3, marginTop: 6, padding: 0, background: "none", border: "none", cursor: "pointer", fontSize: 10.5, fontWeight: 700, color: "#b45309", fontFamily: "inherit" }}
108
+ >
109
+ {expanded ? "Show less" : "Learn more"}
110
+ <svg width="10" height="10" viewBox="0 0 20 20" fill="currentColor" style={{ transform: expanded ? "rotate(180deg)" : "none", transition: "transform 150ms" }}>
111
+ <path fillRule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" clipRule="evenodd" />
112
+ </svg>
113
+ </button>
114
+ {expanded && (
115
+ <ul style={{ margin: "6px 0 0", paddingLeft: 16, fontSize: 11, color: "#1f2937", lineHeight: 1.55 }}>
116
+ <li>Without the 301, the page loses every search ranking and every external link to it breaks.</li>
117
+ <li>A 301 preserves the rankings and link equity built up on the old URL.</li>
118
+ <li>Set this up using vanity redirects in Sanity.</li>
119
+ </ul>
120
+ )}
121
+ </div>
122
+ </div>
123
+ );
124
+ }
125
+
18
126
  const cardStyle: React.CSSProperties = {
19
127
  borderRadius: 14,
20
128
  background: "rgba(255,255,255,0.55)",
@@ -56,12 +164,14 @@ function AuditCard({
56
164
  status,
57
165
  recommendation,
58
166
  anchorId,
167
+ footer,
59
168
  }: {
60
169
  label: string;
61
170
  value: string;
62
171
  status: TechnicalAuditItem["status"];
63
172
  recommendation?: string;
64
173
  anchorId?: string;
174
+ footer?: React.ReactNode;
65
175
  }) {
66
176
  return (
67
177
  <div id={anchorId} style={cardStyle}>
@@ -98,6 +208,7 @@ function AuditCard({
98
208
  {recommendation}
99
209
  </div>
100
210
  )}
211
+ {footer}
101
212
  </div>
102
213
  );
103
214
  }
@@ -169,9 +280,11 @@ function imageFilenameAudit(filenames: string[]): TechnicalAuditItem | null {
169
280
  function imageAltTextAudit(altTexts: string[]): TechnicalAuditItem | null {
170
281
  if (altTexts.length === 0) return null;
171
282
  const issues: { alt: string; reason: string }[] = [];
283
+ let audited = 0; // non-empty alt texts we actually evaluate (blank = decorative, skipped)
172
284
  for (const alt of altTexts) {
173
285
  const trimmed = alt.trim();
174
286
  if (!trimmed) continue; // empty alt is intentional - skip
287
+ audited++;
175
288
  const len = trimmed.length;
176
289
  const wc = trimmed.split(/\s+/).filter(Boolean).length;
177
290
  if (len > 125) {
@@ -180,10 +293,12 @@ function imageAltTextAudit(altTexts: string[]): TechnicalAuditItem | null {
180
293
  issues.push({ alt: trimmed, reason: "just one word - use 2-5 descriptive keywords" });
181
294
  }
182
295
  }
296
+ // Every image had an intentionally-empty (decorative) alt - nothing to audit.
297
+ if (audited === 0) return null;
183
298
  if (issues.length === 0) {
184
299
  return {
185
300
  label: "Image Alt Text",
186
- value: `${altTexts.length} alt text${altTexts.length === 1 ? "" : "s"} look well-formed`,
301
+ value: `${audited} alt text${audited === 1 ? "" : "s"} look well-formed`,
187
302
  status: "good",
188
303
  };
189
304
  }
@@ -193,7 +308,7 @@ function imageAltTextAudit(altTexts: string[]): TechnicalAuditItem | null {
193
308
  }).join("; ");
194
309
  return {
195
310
  label: "Image Alt Text",
196
- value: `${issues.length} of ${altTexts.length} alt text${altTexts.length === 1 ? "" : "s"} need attention`,
311
+ value: `${issues.length} of ${audited} alt text${audited === 1 ? "" : "s"} need attention`,
197
312
  status: "warning",
198
313
  recommendation: `${examples}. Alt text should be 2-5 descriptive keywords that describe the image, ideally including the primary keyword, and stay under 125 characters.`,
199
314
  };
@@ -202,9 +317,17 @@ function imageAltTextAudit(altTexts: string[]): TechnicalAuditItem | null {
202
317
  // Image title audit. Per the director, the title attribute (the tooltip shown on
203
318
  // hover) sends an SEO signal, so each image should carry a short descriptive title.
204
319
  // Flags images with no title, and titles that are a single bare word.
320
+ //
321
+ // MJH's image schemas (mainImage, figure) do not have a `title` field at all -
322
+ // only `alt`, `caption`, and `link`. When NONE of the document's images have a
323
+ // title, we treat that as "schema doesn't support titles" and skip the audit
324
+ // silently rather than flagging every image as missing a field the editor
325
+ // has no way to fill in. The director's intent (catch editors who set title
326
+ // on some images but not others) is preserved.
205
327
  function imageTitleAudit(titles: string[], imageCount: number): TechnicalAuditItem | null {
206
328
  if (imageCount <= 0) return null;
207
329
  const withTitle = titles.length;
330
+ if (withTitle === 0) return null; // schema doesn't expose a title field - skip
208
331
  const missing = imageCount - withTitle;
209
332
  if (missing > 0) {
210
333
  return {
@@ -234,7 +357,9 @@ function imageTitleAudit(titles: string[], imageCount: number): TechnicalAuditIt
234
357
  // heading-level skips, and empty heading blocks.
235
358
  function computeHeadingStructureAudits(headings: HeadingItem[], wordCount: number): TechnicalAuditItem[] {
236
359
  const audits: TechnicalAuditItem[] = [];
237
- const h2Count = headings.filter((h) => h.level === 2).length;
360
+ // Count H2 AND H3 as section headings: an article sectioned only with H3s is
361
+ // still sectioned, so it shouldn't be told it has "no section headings".
362
+ const sectionCount = headings.filter((h) => h.level === 2 || h.level === 3).length;
238
363
 
239
364
  // Heading-density check. Thresholds backed by SEO best-practice research:
240
365
  // > 2,500 words really wants 1 H2 per ~400 words; 1,500+ usually needs 3+;
@@ -244,28 +369,28 @@ function computeHeadingStructureAudits(headings: HeadingItem[], wordCount: numbe
244
369
  // softer density warnings, so a long article with no headings reports "error"
245
370
  // (matching summary.ts) rather than falling into a lower-severity branch.
246
371
  let densityFired = false;
247
- if (wordCount >= 1000 && h2Count === 0) {
372
+ if (wordCount >= 1000 && sectionCount === 0) {
248
373
  audits.push({
249
374
  label: "Section Headings",
250
- value: `No H2 headings in a ${wordCount}-word article`,
375
+ value: `No section headings in a ${wordCount}-word article`,
251
376
  status: "error",
252
- recommendation: "Articles this long need section headings. Add 2-3 H2 headings to break the body into scannable sections.",
377
+ recommendation: "Articles this long need section headings. Add 2-3 H2 (or H3) headings to break the body into scannable sections.",
253
378
  });
254
379
  densityFired = true;
255
- } else if (wordCount >= 2500 && h2Count < 5) {
380
+ } else if (wordCount >= 2500 && sectionCount < 5) {
256
381
  audits.push({
257
382
  label: "Section Headings",
258
- value: `${h2Count} H2 heading${h2Count === 1 ? "" : "s"} for a ${wordCount}-word article`,
383
+ value: `${sectionCount} section heading${sectionCount === 1 ? "" : "s"} for a ${wordCount}-word article`,
259
384
  status: "warning",
260
- recommendation: "Long articles read best with 1 H2 per 300-400 words. Break the content into more named sections so readers and search engines can navigate it.",
385
+ recommendation: "Long articles read best with 1 section heading per 300-400 words. Break the content into more named sections so readers and search engines can navigate it.",
261
386
  });
262
387
  densityFired = true;
263
- } else if (wordCount >= 1500 && h2Count < 3) {
388
+ } else if (wordCount >= 1500 && sectionCount < 3) {
264
389
  audits.push({
265
390
  label: "Section Headings",
266
- value: `${h2Count} H2 heading${h2Count === 1 ? "" : "s"} for a ${wordCount}-word article`,
391
+ value: `${sectionCount} section heading${sectionCount === 1 ? "" : "s"} for a ${wordCount}-word article`,
267
392
  status: "warning",
268
- recommendation: "Articles above 1,500 words usually need at least 3 H2 sections. Add named section breaks so the outline is scannable.",
393
+ recommendation: "Articles above 1,500 words usually need at least 3 named sections. Add section breaks so the outline is scannable.",
269
394
  });
270
395
  densityFired = true;
271
396
  }
@@ -358,8 +483,9 @@ function LinkCheckCard({
358
483
  const redirects = results.filter((r) => r.category === "redirect").length;
359
484
  const broken = results.filter((r) => r.category === "broken").length;
360
485
  const errored = results.filter((r) => r.category === "error").length;
486
+ const unverified = results.filter((r) => r.category === "unverified").length;
361
487
  const issues = results.filter((r) => r.category !== "ok");
362
- return { total, valid, redirects, broken, errored, issues };
488
+ return { total, valid, redirects, broken, errored, unverified, issues };
363
489
  }, [results]);
364
490
 
365
491
  return (
@@ -455,13 +581,33 @@ function LinkCheckCard({
455
581
 
456
582
  {hasRun && !isLoading && !error && (
457
583
  <>
458
- {/* 4-up summary tile */}
459
- <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }}>
584
+ {/* Summary tiles - drops to 5 columns when any links were blocked by anti-bot walls */}
585
+ <div style={{ display: "grid", gridTemplateColumns: counts.unverified > 0 ? "repeat(5, 1fr)" : "repeat(4, 1fr)", gap: 6 }}>
460
586
  <StatTile label="Checked" value={counts.total} color="#475569" />
461
587
  <StatTile label="Valid" value={counts.valid} color="#16a34a" />
462
588
  <StatTile label="Redirects" value={counts.redirects} color="#8B7310" />
463
589
  <StatTile label="Broken" value={counts.broken + counts.errored} color="#dc2626" />
590
+ {counts.unverified > 0 && (
591
+ <StatTile label="Blocked" value={counts.unverified} color="#b45309" />
592
+ )}
464
593
  </div>
594
+ {counts.unverified > 0 && (
595
+ <div
596
+ style={{
597
+ marginTop: 8,
598
+ padding: "6px 10px",
599
+ background: "rgba(245,158,11,0.08)",
600
+ border: "1px solid rgba(245,158,11,0.25)",
601
+ borderRadius: 6,
602
+ fontSize: 10.5,
603
+ color: "#92400e",
604
+ lineHeight: 1.45,
605
+ }}
606
+ >
607
+ {counts.unverified} link{counts.unverified === 1 ? "" : "s"} were blocked from our auto-check (likely
608
+ anti-bot rules on the destination site). They may still work fine for human readers - click each to confirm.
609
+ </div>
610
+ )}
465
611
 
466
612
  {/* Issues list */}
467
613
  {counts.issues.length > 0 ? (
@@ -519,9 +665,14 @@ function LinkIssueRow({ result }: { result: LinkCheckResult }) {
519
665
  ok: { bg: "rgba(22,163,74,0.06)", color: "#16a34a", label: "OK" },
520
666
  redirect: { bg: "rgba(230,192,27,0.12)", color: "#8B7310", label: result.status > 0 ? String(result.status) : "REDIR" },
521
667
  broken: { bg: "rgba(220,38,38,0.06)", color: "#dc2626", label: result.status > 0 ? String(result.status) : "404" },
668
+ // Amber for unverified - the link may work fine, our server just couldn't confirm.
669
+ unverified: { bg: "rgba(245,158,11,0.10)", color: "#b45309", label: result.status > 0 ? String(result.status) : "BLOCKED" },
522
670
  error: { bg: "rgba(220,38,38,0.06)", color: "#dc2626", label: "ERR" },
523
671
  } as const;
524
672
  const c = map[result.category];
673
+ const tooltip = result.category === "unverified"
674
+ ? `${result.url} (couldn't auto-check; likely anti-bot blocking - open manually to verify)`
675
+ : result.error ? `${result.url} (${result.error})` : result.url;
525
676
  return (
526
677
  <a
527
678
  href={result.url}
@@ -563,7 +714,7 @@ function LinkIssueRow({ result }: { result: LinkCheckResult }) {
563
714
  textOverflow: "ellipsis",
564
715
  whiteSpace: "nowrap",
565
716
  }}
566
- title={result.error ? `${result.url} (${result.error})` : result.url}
717
+ title={tooltip}
567
718
  >
568
719
  {result.url}
569
720
  </span>
@@ -574,6 +725,8 @@ function LinkIssueRow({ result }: { result: LinkCheckResult }) {
574
725
  export function TechnicalTab({
575
726
  text,
576
727
  documentFields,
728
+ primaryKeyword,
729
+ secondaryKeyword,
577
730
  isLoading,
578
731
  linkCheckResults,
579
732
  isLinkCheckLoading,
@@ -581,6 +734,10 @@ export function TechnicalTab({
581
734
  hasRunLinkCheck,
582
735
  onCheckLinks,
583
736
  }: TechnicalTabProps) {
737
+ const urlSlugAudit = useMemo(
738
+ () => urlAudit(documentFields?.slug, primaryKeyword, secondaryKeyword),
739
+ [documentFields?.slug, primaryKeyword, secondaryKeyword]
740
+ );
584
741
  const headings = documentFields?.headings || [];
585
742
  const headingsDetailed = documentFields?.headingsDetailed;
586
743
  // Fall back gracefully if a host (e.g. older Notebook builds) doesn't supply heading
@@ -631,14 +788,17 @@ export function TechnicalTab({
631
788
  : null;
632
789
 
633
790
  // 450 is the body-text floor. 1,500+ is the competitive target for HCP clinical content.
634
- const wordAudit: TechnicalAuditItem =
791
+ // An empty body is not an error to "Fix" - the editor simply hasn't written yet
792
+ // (or the body hasn't loaded). Mirror summary.ts and show no card rather than a red
793
+ // alarm; the Word Count card appears once there's real text to measure.
794
+ // Videos / podcasts / news / briefs are legitimately short (body text summarizes
795
+ // the media, it isn't the deliverable), so they're exempt from the word-count floor.
796
+ const isShortForm = isShortFormContent(documentFields, documentFields?.title);
797
+ const wordAudit: TechnicalAuditItem | null =
635
798
  wordCount === 0
636
- ? {
637
- label: "Word Count",
638
- value: "0 words",
639
- status: "error",
640
- recommendation: "Start writing. A link or image on its own doesn't count - the body needs real written substance.",
641
- }
799
+ ? null
800
+ : isShortForm
801
+ ? { label: "Word Count", value: `${wordCount} words`, status: "good" }
642
802
  : wordCount < 450
643
803
  ? {
644
804
  label: "Word Count",
@@ -677,13 +837,24 @@ export function TechnicalTab({
677
837
  return (
678
838
  <div style={{ padding: 12, display: "flex", flexDirection: "column", gap: 10 }}>
679
839
  <AuditCard
680
- anchorId="anchor-word-count"
681
- label={wordAudit.label}
682
- value={wordAudit.value}
683
- status={wordAudit.status}
684
- recommendation={wordAudit.recommendation}
840
+ anchorId="anchor-url-slug"
841
+ label={urlSlugAudit.label}
842
+ value={urlSlugAudit.value}
843
+ status={urlSlugAudit.status}
844
+ recommendation={urlSlugAudit.recommendation}
845
+ footer={<SlugRedirectNotice />}
685
846
  />
686
847
 
848
+ {wordAudit && (
849
+ <AuditCard
850
+ anchorId="anchor-word-count"
851
+ label={wordAudit.label}
852
+ value={wordAudit.value}
853
+ status={wordAudit.status}
854
+ recommendation={wordAudit.recommendation}
855
+ />
856
+ )}
857
+
687
858
  {structureAudits.map((a, i) => (
688
859
  <AuditCard
689
860
  key={`structure-${i}`}
@@ -1,128 +1,12 @@
1
1
  import { useState, useEffect, useRef } from "react";
2
2
  import { useDocumentPane } from "sanity/structure";
3
- import type { DocumentFields, HeadingItem } from "../lib/types";
3
+ import type { DocumentFields } from "../lib/types";
4
+ import { extractText, buildDocumentFields } from "../lib/documentExtract";
4
5
 
5
- interface PortableTextSpan {
6
- _type: string;
7
- text?: string;
8
- marks?: string[];
9
- children?: PortableTextSpan[];
10
- }
11
-
12
- interface PortableTextMarkDef {
13
- _key: string;
14
- _type: string;
15
- href?: string;
16
- url?: string;
17
- }
18
-
19
- interface PortableTextBlock {
20
- _type: string;
21
- style?: string;
22
- children?: PortableTextSpan[];
23
- markDefs?: PortableTextMarkDef[];
24
- text?: string;
25
- }
26
-
27
- function extractText(blocks: unknown): string {
28
- if (!blocks || !Array.isArray(blocks)) return "";
29
- const parts: string[] = [];
30
- for (const block of blocks as PortableTextBlock[]) {
31
- if (block._type === "block" && block.children) {
32
- const blockText = block.children.map((child) => child.text || "").join("");
33
- if (blockText) parts.push(blockText);
34
- } else if (typeof block === "string") {
35
- parts.push(block);
36
- }
37
- }
38
- return parts.join("\n");
39
- }
40
-
41
- function extractHeadings(blocks: unknown): string[] {
42
- if (!blocks || !Array.isArray(blocks)) return [];
43
- const headings: string[] = [];
44
- for (const block of blocks as PortableTextBlock[]) {
45
- if (block._type === "block" && block.style && /^h[1-6]$/.test(block.style) && block.children) {
46
- const text = block.children.map((child) => child.text || "").join("");
47
- if (text) headings.push(text);
48
- }
49
- }
50
- return headings;
51
- }
52
-
53
- // Headings with their numeric level (1-6), so the Technical tab can audit hierarchy.
54
- function extractHeadingsDetailed(blocks: unknown): HeadingItem[] {
55
- if (!blocks || !Array.isArray(blocks)) return [];
56
- const out: HeadingItem[] = [];
57
- for (const block of blocks as PortableTextBlock[]) {
58
- if (block._type === "block" && block.style && /^h[1-6]$/.test(block.style) && block.children) {
59
- const text = block.children.map((child) => child.text || "").join("").trim();
60
- const level = Number(block.style.slice(1));
61
- // Include empty headings too - the Technical tab flags them.
62
- out.push({ text, level });
63
- }
64
- }
65
- return out;
66
- }
67
-
68
- // Every URL the editor has linked from this article body. Sanity stores them
69
- // in Portable Text markDefs (with _type: "link" and href/url). We also catch
70
- // inline plain-text URLs as a fallback.
71
- function extractBodyLinks(blocks: unknown): string[] {
72
- const urls = new Set<string>();
73
- if (Array.isArray(blocks)) {
74
- for (const block of blocks as PortableTextBlock[]) {
75
- if (block._type === "block" && Array.isArray(block.markDefs)) {
76
- for (const md of block.markDefs) {
77
- const href = md.href || md.url;
78
- if (typeof href === "string" && /^https?:\/\//i.test(href)) {
79
- urls.add(href.trim());
80
- }
81
- }
82
- }
83
- }
84
- }
85
- // Inline URLs that aren't in a link annotation - rare but possible.
86
- if (Array.isArray(blocks)) {
87
- for (const block of blocks as PortableTextBlock[]) {
88
- if (block._type === "block" && Array.isArray(block.children)) {
89
- const blockText = block.children.map((c) => c.text || "").join(" ");
90
- const matches = blockText.match(/https?:\/\/[^\s"'<>)\]]+/g);
91
- if (matches) matches.forEach((u) => urls.add(u.replace(/[.,;:!?]+$/, "")));
92
- }
93
- }
94
- }
95
- return Array.from(urls);
96
- }
97
-
98
- // Extracts image metadata from the known top-level image fields:
99
- // - names: alt text + asset filename (for the alt + filename audits)
100
- // - titles: the `title` field on the image object or asset (the hover tooltip)
101
- // - count: number of real images found (so the title audit can say "X of N")
102
- function extractImageMeta(value: Record<string, unknown>): { names: string[]; titles: string[]; count: number } {
103
- const names: string[] = [];
104
- const titles: string[] = [];
105
- let count = 0;
106
- const imageFields = ["mainImage", "image", "heroImage", "thumbnail", "featuredImage"];
107
- for (const field of imageFields) {
108
- const img = value[field] as Record<string, unknown> | undefined;
109
- if (!img || typeof img !== "object") continue;
110
- const asset = img.asset && typeof img.asset === "object" ? (img.asset as Record<string, unknown>) : undefined;
111
- // Only count entries that are actually images (have an asset or an image _type).
112
- if (!asset && img._type !== "image") continue;
113
- count++;
114
- if (typeof img.alt === "string" && img.alt) names.push(img.alt);
115
- if (asset && typeof asset.originalFilename === "string" && asset.originalFilename) names.push(asset.originalFilename);
116
- // The hover-tooltip title can live on the image object or on the asset.
117
- if (typeof img.title === "string" && img.title) titles.push(img.title);
118
- else if (asset && typeof asset.title === "string" && asset.title) titles.push(asset.title);
119
- }
120
- return { names, titles, count };
121
- }
122
-
123
- export function useDocumentContent(): { text: string; isLoading: boolean; documentFields: DocumentFields; documentId: string | undefined } {
6
+ export function useDocumentContent(): { text: string; isLoading: boolean; documentFields: DocumentFields; documentId: string | undefined; documentType: string | undefined } {
124
7
  const { value, ready } = useDocumentPane();
125
8
  const documentId = (value?._id as string | undefined) || undefined;
9
+ const documentType = (value?._type as string | undefined) || undefined;
126
10
  const title = value?.title as string | undefined;
127
11
  const body = value?.body;
128
12
  const [debouncedText, setDebouncedText] = useState("");
@@ -143,59 +27,7 @@ export function useDocumentContent(): { text: string; isLoading: boolean; docume
143
27
  useEffect(() => {
144
28
  const bodyText = extractText(body);
145
29
  const fullText = [title, bodyText].filter(Boolean).join("\n\n");
146
-
147
- const val = value as Record<string, unknown> | undefined;
148
-
149
- // Author extraction - covers several common Sanity schemas.
150
- // Note: Sanity references aren't auto-resolved by useDocumentPane; we detect them
151
- // separately so the audit doesn't flag ref-based authors as "Missing".
152
- let authorName: string | undefined;
153
- let authorCredentials: string | undefined;
154
- let authorBioUrl: string | undefined;
155
- let authorIsReference = false;
156
- const author = (val?.author || (Array.isArray(val?.authors) && (val.authors as unknown[])[0]) || val?.byline) as
157
- | Record<string, unknown>
158
- | string
159
- | undefined;
160
- if (typeof author === "string") {
161
- authorName = author;
162
- } else if (author && typeof author === "object") {
163
- authorName =
164
- (author.name as string | undefined) ||
165
- (author.fullName as string | undefined) ||
166
- (author.displayName as string | undefined);
167
- authorCredentials =
168
- (author.credentials as string | undefined) ||
169
- (author.title as string | undefined) ||
170
- (author.suffix as string | undefined);
171
- authorBioUrl = (author.bioUrl as string | undefined) || ((author.slug as { current?: string })?.current ? `/author/${(author.slug as { current?: string }).current}` : undefined);
172
- // Sanity reference: { _type: 'reference', _ref: '...' } with no inline name
173
- if (!authorName && typeof author._ref === "string") {
174
- authorIsReference = true;
175
- }
176
- }
177
-
178
- const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
179
- const fields: DocumentFields = {
180
- title: title || undefined,
181
- metaDescription: (val?.metaDescription || val?.summary || val?.description || val?.seoDescription) as string | undefined,
182
- slug: (val?.slug as { current?: string })?.current || undefined,
183
- imageNames: imageMeta.names,
184
- imageTitles: imageMeta.titles,
185
- imageCount: imageMeta.count,
186
- headings: extractHeadings(body),
187
- headingsDetailed: extractHeadingsDetailed(body),
188
- bodyLinks: extractBodyLinks(body),
189
- contentCategory: (val?.contentCategory || val?.category) as string | undefined,
190
- contentPlacement: Array.isArray(val?.contentPlacement) ? (val.contentPlacement as string[]) : undefined,
191
- authorName,
192
- authorCredentials,
193
- authorBioUrl,
194
- authorIsReference,
195
- publishedAt: (val?.publishedAt || val?.publishDate || val?._createdAt) as string | undefined,
196
- updatedAt: (val?.updatedAt || val?._updatedAt) as string | undefined,
197
- lastReviewedAt: (val?.lastReviewedAt || val?.lastReviewed || val?.medicallyReviewedAt) as string | undefined,
198
- };
30
+ const fields = buildDocumentFields(value as Record<string, unknown> | undefined);
199
31
 
200
32
  // documentFields are cheap and shown immediately so the Technical tab doesn't flash
201
33
  // "Missing" cards while the text debounce is pending. Only debounce text since that
@@ -212,5 +44,5 @@ export function useDocumentContent(): { text: string; isLoading: boolean; docume
212
44
  return () => { if (timerRef.current) clearTimeout(timerRef.current); };
213
45
  }, [title, body, value]);
214
46
 
215
- return { text: debouncedText, isLoading, documentFields, documentId };
47
+ return { text: debouncedText, isLoading, documentFields, documentId, documentType };
216
48
  }