Study/web/src/ui/Markdown.tsx
Elijah c595e0ff2c
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
Third revision: web search, MCP sign-in, exams, intelligent UI, clarifying questions
- Built-in Parallel web search (keyless; optional sign-in for higher limits and research)
  with its own settings page; OAuth sign-in (RFC 9728/8414/7591, PKCE, RFC 8707) for any
  MCP server, with token refresh and pre-registered client support
- Friendly tool steps (icon, name, status; details on click) and ids stripped from results;
  per-chat tool switches; taller thinking box
- Exams within classes: exam tabs, scoped lists, uploads, imports and Generate; exam-only
  material for generation; class setting for what the groups are called
- Assistant can ask clarifying questions in an inline form before generating
- OpenUI blocks (charts, questions, flashcards, inputs) in assistant, Explain and share chats
- Explain beside the quiz on wide screens, grounded in the cited source pages
- Quiz results: percentage ring coloured by score band, rainbow at 100
- Share links: assistant button like the owner's, hidden during quizzes; documents readable
  in the browser
- Live draft and library updates over server-sent events

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:30:00 -07:00

142 lines
5.4 KiB
TypeScript

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 (
<Suspense fallback={<div className="my-3 h-16 rounded-[14px] border border-line bg-surface" />}>
<GenUiBlock source={source} streaming={ctx.streaming} onSend={ctx.onSend} />
</Suspense>
);
}
return <pre>{children}</pre>;
}
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/') ? (
<Link to={href}>{children}</Link>
) : (
<a href={href} target="_blank" rel="noreferrer noopener">
{children}
</a>
),
table: ({ children }) => (
<div className="table-wrap">
<table>{children}</table>
</div>
),
img: ({ src, alt }) => <img src={typeof src === 'string' ? src : undefined} alt={alt ?? ''} loading="lazy" />,
};
/** Splits text on [c12] / [c12, c13] markers and swaps them for numbered citation chips. */
function withCitations(children: ReactNode, cites: Map<string, { n: number; cite: Citation }>, 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 (
<span key={`${key}-${i}`} className="whitespace-nowrap">
{refs.map((ref) => {
const hit = cites.get(ref);
if (!hit) return null;
return (
<button
key={ref}
type="button"
title={hit.cite.label}
onClick={() => onCite?.(hit.cite)}
className="num mx-0.5 inline-grid h-[18px] min-w-[18px] -translate-y-px place-items-center rounded-[5px] bg-accent-soft px-1 align-middle text-[10.5px] font-semibold text-accent hover:bg-accent hover:text-accent-ink"
>
{hit.n}
</button>
);
})}
</span>
);
});
}
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<string, { n: number; cite: Citation }>();
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 }) => <Tag>{withCitations(kids, order, onCite)}</Tag>;
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 (
<div className={cx('md', serif && 'reading', className)}>
<ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
{children}
</ReactMarkdown>
</div>
);
});
/** 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<string, { n: number; cite: Citation }>();
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()];
}