diff --git a/app/alerts-settings/page.tsx b/app/alerts-settings/page.tsx index d93a9ce..5a42c70 100644 --- a/app/alerts-settings/page.tsx +++ b/app/alerts-settings/page.tsx @@ -4,6 +4,7 @@ import { useEffect, useMemo, useState } from "react"; import { useRouter } from "next/navigation"; import { apiFetch } from "@/lib/api"; import type { AlertListResponse, AlertItem } from "@/lib/types/alert"; +import { alertItemAsNarrativeHandoff, stashNarrativeHandoff } from "@/lib/narrativeHandoff"; import { useNotifications } from "@/components/layout/NotificationContext"; import { useSidebar } from "@/components/layout/SidebarContext"; import { useTheme } from "@/components/layout/ThemeContext"; @@ -220,7 +221,10 @@ export default function AlertsSettingsPage() { - +
+
+
+

Claims database

+

Sortable list with confidence and review status

+
+
+
+ + + {filterOpen && ( +
+

Filter by

+ +
+ + + +
+ +
+ + +
+
+ )} +
+ +
{loading ? ( -
-
-

Processing Narrative Data...

+
+
+

Loading claims…

) : ( -
- - - - - - - - - - - - {visibleClaims.map((claim) => ( - - - - - - + <> +
+
Claim IDClaim TextSourceStatusConfidence
{claim.claim_id}{claim.text}{claim.source} - - {claim.status.toUpperCase()} - - -
-
-
-
- {claim.confidence} -
-
+ + + + + + + - ))} - -
Claim IDClaim textSourceStatusConfidence
-
+ + + {pageClaims.length === 0 ? ( + + + No claims match your search or filters. + + + ) : ( + pageClaims.map((claim) => ( + + {claim.claim_id} + + {claim.text} + + {claim.source} + + + {claim.status.toUpperCase()} + + + +
+
+
+
+ + {claim.confidence} + +
+ + + )) + )} + + +
+ + {visibleClaims.length > 0 && ( +
+

+ Showing {rangeStart} + {"–"} + {rangeEnd} + {" of "} + {visibleClaims.length} + {(search.trim() || hasActiveFilters) && " matching"} claims +

+
+ +
+ + + Page {safePage} / {totalPages} + + +
+
+
+ )} + )} -
+
) } -function Card({ title, value, subtitle }: { title: string; value: number; subtitle: string }) { +function StatCard({ + kind, + title, + value, + subtitle, +}: { + kind: StatKind + title: string + value: number + subtitle: string +}) { return ( -
-

{title}

-

{value}

-

{subtitle}

+
+
+
+ +
+
+

{title}

+

{value}

+

{subtitle}

+
+
) -} \ No newline at end of file +} diff --git a/app/creator-risk-monitor/page.tsx b/app/creator-risk-monitor/page.tsx index b286081..234859f 100644 --- a/app/creator-risk-monitor/page.tsx +++ b/app/creator-risk-monitor/page.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useState, useEffect, useCallback } from "react"; +import React, { useCallback, useEffect, useMemo, useState } from "react"; import { apiFetch } from "@/lib/api"; type Creator = { @@ -16,12 +16,16 @@ const SORT_OPTIONS = [ { label: "Reach: High to Low", value: "reach_desc" }, ] as const; +/** Four cards per row × three rows per page */ +const CREATORS_PER_PAGE = 12; + const CreatorRiskMonitor = () => { const [creators, setCreators] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); - const [narrative, setNarrative] = useState(""); + const [creatorSearch, setCreatorSearch] = useState(""); const [sort, setSort] = useState("risk_desc"); + const [page, setPage] = useState(1); const fetchCreators = useCallback(async () => { setLoading(true); @@ -29,45 +33,61 @@ const CreatorRiskMonitor = () => { try { const json = await apiFetch<{ ok: boolean; data: Creator[] }>("/creators/risk", { sort, - narrative: narrative.trim() || undefined, }); setCreators(json.data ?? []); + setPage(1); } catch (err: unknown) { setError(err instanceof Error ? err.message : "Failed to load creators"); } finally { setLoading(false); } - }, [narrative, sort]); + }, [sort]); useEffect(() => { - const id = setTimeout(fetchCreators, narrative ? 300 : 0); - return () => clearTimeout(id); - }, [fetchCreators, narrative]); + void fetchCreators(); + }, [fetchCreators]); + + const filteredCreators = useMemo(() => { + const q = creatorSearch.trim().toLowerCase(); + if (!q) return creators; + return creators.filter((c) => c.handle.toLowerCase().includes(q)); + }, [creators, creatorSearch]); return ( -
+
+
{/* Header Section */} -
+

Creator Risk Monitor

Assess and track high-risk content creators based on flagged health claims.

-
+
- + setNarrative(e.target.value)} - placeholder="e.g. Ozempic, COVID…" - className="w-52 rounded-lg border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-900 placeholder:text-zinc-400 focus:outline-none focus:ring-2 focus:ring-zinc-200 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200 dark:placeholder:text-zinc-500 dark:focus:ring-zinc-500" + id="creator-risk-search" + type="search" + value={creatorSearch} + onChange={(e) => { + setCreatorSearch(e.target.value); + setPage(1); + }} + placeholder="Search by name or handle…" + autoComplete="off" + className="w-56 rounded-lg border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-900 placeholder:text-zinc-400 focus:outline-none focus:ring-2 focus:ring-zinc-200 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-200 dark:placeholder:text-zinc-500 dark:focus:ring-zinc-500" />
{ + setClaimsLoading(true); + setClaims([]); + setClaimStatusFilter(e.target.value as "all" | "verified" | "unverifiable"); + }} + disabled={claimsLoading} + className="h-9 cursor-pointer rounded-lg border border-zinc-200 bg-white px-3 text-xs font-medium text-zinc-700 focus:border-zinc-900 focus:outline-none focus:ring-2 focus:ring-zinc-900/10 dark:border-zinc-600 dark:bg-zinc-700 dark:text-zinc-300 dark:focus:border-zinc-400 dark:focus:ring-zinc-400/20" + aria-label="Filter claims by verification status" + > + + + + + + + + + Export + +
@@ -361,15 +422,9 @@ export default function ExecutiveOverviewPage() { {claim.views} - {claim.status} + {formatClaimStatus(claim.status)} @@ -382,6 +437,20 @@ export default function ExecutiveOverviewPage() { ))} + {claimsLoading && ( + + + Loading claims... + + + )} + {!claimsLoading && claims.length === 0 && ( + + + No claims match this status filter. + + + )}
diff --git a/app/narrative-discovery/page.tsx b/app/narrative-discovery/page.tsx index a605739..f2eddd1 100644 --- a/app/narrative-discovery/page.tsx +++ b/app/narrative-discovery/page.tsx @@ -1,9 +1,11 @@ "use client"; -import { Suspense, useEffect, useMemo, useState } from "react"; +import { Suspense, useEffect, useMemo, useState, useSyncExternalStore } from "react"; +import { createPortal } from "react-dom"; import { useRouter, useSearchParams } from "next/navigation"; import { apiFetch } from "@/lib/api"; import type { NarrativeListResponse, NarrativeItem } from "@/lib/types/narrative"; +import { stashNarrativeHandoff, clearNarrativeHandoff, useNarrativeHandoff } from "@/lib/narrativeHandoff"; type RiskLevel = "High" | "Medium" | "Low"; @@ -67,18 +69,24 @@ function NarrativeDiscoveryInner() { return () => { cancelled = true; }; }, [sortBy, debouncedSearch]); - // URL + loaded data determine which narrative is open (derived state — no effect). + const idParam = searchParams.get("id"); + const handoffNarrative = useNarrativeHandoff(idParam); + + // Prefer list data when loaded; otherwise use session handoff (e.g. from Alerts View). const activeNarrative = useMemo(() => { - const id = searchParams.get("id"); - if (!id || narratives.length === 0) return null; - return narratives.find((n) => String(n.id) === String(id)) ?? null; - }, [searchParams, narratives]); + if (!idParam) return null; + const fromList = narratives.find((n) => String(n.id) === String(idParam)); + if (fromList) return fromList; + return handoffNarrative; + }, [idParam, narratives, handoffNarrative]); function openNarrative(n: NarrativeItem) { + stashNarrativeHandoff(n); router.replace(`/narrative-discovery?id=${n.id}`, { scroll: false }); } function closeNarrative() { + if (idParam) clearNarrativeHandoff(idParam); router.replace("/narrative-discovery", { scroll: false }); } @@ -190,54 +198,80 @@ function NarrativeDiscoveryInner() { ); } +function useIsClient() { + return useSyncExternalStore( + () => () => {}, + () => true, + () => false, + ); +} + function NarrativeDetailDialog({ narrative, onClose }: { narrative: NarrativeItem; onClose: () => void }) { + const isClient = useIsClient(); + useEffect(() => { const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose(); document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); }, [onClose]); - return ( -
-
e.stopPropagation()}> -
-
-

{narrative.title}

-

{narrative.category}

+ if (!isClient) return null; + + return createPortal( +
+
e.stopPropagation()} + role="dialog" + aria-modal="true" + aria-labelledby="narrative-dialog-title" + > +
+
+

+ {narrative.title} +

+

{narrative.category}

- + {narrative.risk_level} RISK

{narrative.detail || narrative.description}

-
+
-
Analyzed
+
Analyzed
{narrative.videos_analyzed?.toLocaleString()} Videos
-
Views
+
Views
{narrative.total_views}
-
Risk Score
+
Risk Score
{narrative.risk_score}/10
-
Window
+
Window
{narrative.time_window}
-
+
, + document.body, ); -} \ No newline at end of file +} diff --git a/components/layout/Header.tsx b/components/layout/Header.tsx index 754fab4..1dfcb3f 100644 --- a/components/layout/Header.tsx +++ b/components/layout/Header.tsx @@ -9,7 +9,7 @@ import { useSidebar } from "./SidebarContext"; import { useNotifications } from "./NotificationContext"; import { useAuth } from "./AuthContext"; import { useTheme } from "./ThemeContext"; -import { User, Settings, LogOut, Info, ChevronDown, Bell } from "lucide-react"; +import { User, Settings, LogOut, ChevronDown, Bell } from "lucide-react"; export function Header() { const router = useRouter(); @@ -176,38 +176,24 @@ export function Header() {
- -
-
+
- -
diff --git a/lib/narrativeHandoff.ts b/lib/narrativeHandoff.ts new file mode 100644 index 0000000..3879d84 --- /dev/null +++ b/lib/narrativeHandoff.ts @@ -0,0 +1,110 @@ +import { useRef, useSyncExternalStore } from "react" +import type { AlertItem } from "@/lib/types/alert" +import type { NarrativeItem } from "@/lib/types/narrative" + +const PREFIX = "nd-handoff:" + +export function stashNarrativeHandoff(n: NarrativeItem): void { + if (typeof window === "undefined") return + try { + sessionStorage.setItem(`${PREFIX}${n.id}`, JSON.stringify(n)) + } catch { + /* private mode / quota */ + } +} + +export function clearNarrativeHandoff(id: string): void { + if (typeof window === "undefined") return + try { + sessionStorage.removeItem(`${PREFIX}${id}`) + } catch { + /* ignore */ + } +} + +export function readNarrativeHandoff(id: string | null): NarrativeItem | null { + if (!id || typeof window === "undefined") return null + try { + const raw = sessionStorage.getItem(`${PREFIX}${id}`) + if (!raw) return null + const parsed = JSON.parse(raw) as NarrativeItem + return String(parsed.id) === String(id) ? parsed : null + } catch { + return null + } +} + +/** Map an alert row to the narrative shape expected by the discovery dialog. */ +export function alertItemAsNarrativeHandoff(a: AlertItem): NarrativeItem { + return { + id: a.id, + title: a.title, + description: a.description, + detail: a.description, + category: "Narrative", + risk_level: a.risk_level, + risk_score: a.risk_score, + videos_analyzed: a.videos_analyzed, + total_views: a.total_views, + time_window: a.time_window, + primary_link: null, + } +} + +/** + * Reads a narrative stashed for deep-link open (?id=) after the first paint so + * server HTML and the first hydrated client snapshot both stay null, then the + * next snapshot pulls from sessionStorage (instant dialog after navigation). + * + * Parsed objects are cached by storage key + raw string so getSnapshot returns + * referentially stable values — required by useSyncExternalStore (React 19). + */ +export function useNarrativeHandoff(id: string | null): NarrativeItem | null { + const pass = useRef(0) + const snapshotCache = useRef<{ + storageKey: string + raw: string | null + parsed: NarrativeItem | null + } | null>(null) + + return useSyncExternalStore( + (onStoreChange) => { + if (typeof window === "undefined") return () => {} + queueMicrotask(() => { + pass.current += 1 + onStoreChange() + }) + return () => {} + }, + () => { + if (!id || typeof window === "undefined") return null + if (pass.current === 0) return null + + const storageKey = `${PREFIX}${id}` + let raw: string | null + try { + raw = sessionStorage.getItem(storageKey) + } catch { + raw = null + } + + const c = snapshotCache.current + if (c && c.storageKey === storageKey && c.raw === raw) { + return c.parsed + } + + let parsed: NarrativeItem | null = null + if (raw) { + try { + const obj = JSON.parse(raw) as NarrativeItem + parsed = String(obj.id) === String(id) ? obj : null + } catch { + parsed = null + } + } + snapshotCache.current = { storageKey, raw, parsed } + return parsed + }, + () => null, + ) +} diff --git a/lib/types/claim.ts b/lib/types/claim.ts index 63dca6c..b12e326 100644 --- a/lib/types/claim.ts +++ b/lib/types/claim.ts @@ -2,7 +2,8 @@ export interface ClaimItem { claim_id: string; text: string; source: string; - status: "Verified" | "Disputed" | "Under Review"; + /** Backend may return additional values (e.g. Unverifiable). */ + status: string; confidence: string; views: string; date: string; @@ -15,9 +16,16 @@ export interface ClaimStats { under_review: number; } +/** Optional facet lists returned by GET /claims; UI falls back to deriving from `data` if omitted. */ +export interface ClaimFilterOptions { + statuses?: string[]; + confidences?: string[]; +} + export interface ClaimListResponse { ok: boolean; data: ClaimItem[]; stats: ClaimStats; count: number; + filter_options?: ClaimFilterOptions; }