import { createContext, lazy, memo, Suspense, useContext, type ReactNode } from 'react';
import ReactMarkdown, { type Components } from 'react-markdown';
import { Link } from 'react-router';
import remarkGfm from 'remark-gfm';
import { cx } from '@/lib/util';
export interface Citation {
ref: string;
label: string;
documentId: string;
chunkId: number;
}
const GenUiBlock = lazy(() => import('@/genui/GenUiBlock'));
/**
* Chat surfaces provide this so `openui-lang` fences in a reply render as live components.
* Elsewhere (notes, rationales) such fences stay code.
*/
export const GenUiContext = createContext<{ streaming: boolean; onSend?: (text: string) => void } | null>(null);
const GENUI_LANG = /\blanguage-(openui-lang|openui)\b/;
function Pre({ children, node }: { children?: ReactNode; node?: any }) {
const ctx = useContext(GenUiContext);
const code = node?.children?.[0];
const cls = code?.properties?.className;
const lang = Array.isArray(cls) ? cls.join(' ') : String(cls ?? '');
if (ctx && GENUI_LANG.test(lang)) {
const source = (code?.children ?? []).map((c: any) => (typeof c.value === 'string' ? c.value : '')).join('');
return (
}>
);
}
return
{children}
;
}
const BASE: Components = {
pre: Pre as Components['pre'],
a: ({ href, children }) =>
// Links to pages inside the app (the assistant uses these to point at quizzes, decks and notes)
// navigate without a reload; everything else opens in a new tab.
href && href.startsWith('/') && !href.startsWith('//') && !href.startsWith('/api/') && !href.startsWith('/media/') ? (
{children}
) : (
{children}
),
table: ({ children }) => (
{children}
),
img: ({ src, alt }) => ,
};
/** Splits text on [c12] / [c12, c13] markers and swaps them for numbered citation chips. */
function withCitations(children: ReactNode, cites: Map, onCite?: (c: Citation) => void): ReactNode {
const walk = (node: ReactNode, key: string): ReactNode => {
if (typeof node === 'string') {
const parts = node.split(/(\[c\d+(?:\s*,\s*c\d+)*\])/g);
if (parts.length === 1) return node;
return parts.map((part, i) => {
if (!/^\[c\d/.test(part)) return part;
const refs = part.slice(1, -1).split(',').map((r) => r.trim());
return (
{refs.map((ref) => {
const hit = cites.get(ref);
if (!hit) return null;
return (
);
})}
);
});
}
if (Array.isArray(node)) return node.map((n, i) => walk(n, `${key}.${i}`));
return node;
};
return walk(children, 'c');
}
export const Markdown = memo(function Markdown({
children,
className,
citations,
onCite,
serif,
}: {
children: string;
className?: string;
citations?: Citation[];
onCite?: (c: Citation) => void;
/** Use the reading serif (questions, cards, notes). */
serif?: boolean;
}) {
let components = BASE;
if (citations && citations.length > 0) {
// Number citations in order of first appearance in the text.
const order = new Map();
const byRef = new Map(citations.map((c) => [c.ref, c]));
for (const m of children.matchAll(/c\d+/g)) {
const cite = byRef.get(m[0]);
if (cite && !order.has(m[0])) order.set(m[0], { n: order.size + 1, cite });
}
const wrap =
(Tag: 'p' | 'li' | 'td' | 'strong' | 'em' | 'h1' | 'h2' | 'h3' | 'h4' | 'blockquote') =>
({ children: kids }: { children?: ReactNode }) => {withCitations(kids, order, onCite)};
components = { ...BASE, p: wrap('p'), li: wrap('li'), td: wrap('td'), strong: wrap('strong'), em: wrap('em'), h1: wrap('h1'), h2: wrap('h2'), h3: wrap('h3'), h4: wrap('h4'), blockquote: wrap('blockquote') };
}
return (
{children}
);
});
/** Ordered list of the sources actually cited in a piece of text. */
export function citedSources(text: string, citations: Citation[]): { n: number; cite: Citation }[] {
const byRef = new Map(citations.map((c) => [c.ref, c]));
const out = new Map();
for (const m of text.matchAll(/c\d+/g)) {
const cite = byRef.get(m[0]);
if (cite && !out.has(m[0])) out.set(m[0], { n: out.size + 1, cite });
}
return [...out.values()];
}