Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 | 23x 23x 23x 23x 23x 23x 23x 320x 320x 320x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 14x 14x 14x 14x 14x 14x 13x 6x 23x 14x 14x 14x 14x 14x 14x 14x 23x 23x 23x 23x 320x 320x 320x 320x 23x 320x 320x 14x 14x 14x 14x 14x 14x 1x 1x 1x 14x | import React, { useState, useEffect, useId, useRef, useContext, createContext, useMemo } from "react";
import ReactMarkdown from "react-markdown";
import mermaid from "mermaid";
import { mermaidConfig } from "@/util/mermaidConfig";
import remarkMath from "remark-math";
import rehypeKatex from "rehype-katex";
import remarkGfm from "remark-gfm";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";
import {
BarChart,
Bar,
LineChart,
Line,
PieChart,
Pie,
Cell,
AreaChart,
Area,
ScatterChart,
Scatter,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
} from "recharts";
import { Check, Copy, Maximize2, X, ZoomIn, ZoomOut, RotateCcw } from "lucide-react";
import "katex/dist/katex.min.css";
import "leaflet/dist/leaflet.css";
import { MapContainer, GeoJSON as LfGeoJSON } from "react-leaflet";
import L from "leaflet";
import { BasemapLayer } from "@/components/map";
import { processCitations } from "./processCitations";
import {
DocumentCard,
DocumentDownloadProvider,
DocumentImagesProvider,
MarkdownImage,
useDocumentImageUrl,
} from "@/components/document";
import { documentImages, extractDocuments, parseDocument } from "@/objects/Document";
// ─── Chart ────────────────────────────────────────────────────────────────────
interface ChartSeries {
key?: string;
field?: string; // alias for key
y_key?: string; // alias for key
label?: string;
color?: string;
}
interface ChartConfig {
type: "bar" | "multibar" | "grouped" | "line" | "area" | "pie";
title?: string;
data: Record<string, string | number>[];
xKey?: string;
x_key?: string;
yKey?: string; // single-series shorthand → series:[{key:yKey}]
y_key?: string; // alias for yKey
series?: ChartSeries[];
}
const PALETTE = [
"#6366f1",
"#10b981",
"#f59e0b",
"#ef4444",
"#8b5cf6",
"#06b6d4",
"#f97316",
"#ec4899",
];
// Resolve a ChartSeries to its canonical data key.
function resolveSeriesKey(s: ChartSeries): string {
return (s.key ?? s.field ?? s.y_key ?? "value");
}
const ChartContent: React.FC<{ cfg: ChartConfig; height: number }> = ({ cfg, height }) => {
const xKey = cfg.xKey ?? cfg.x_key ?? "name";
const yKeyShorthand = cfg.yKey ?? cfg.y_key;
const rawSeries: ChartSeries[] =
cfg.series ??
(yKeyShorthand
? [{ key: yKeyShorthand }]
: Object.keys(cfg.data[0])
.filter((k) => k !== xKey)
.map((key) => ({ key })));
const autoSeries = rawSeries.map((s, i) => ({
...s,
key: resolveSeriesKey(s),
label: s.label ?? resolveSeriesKey(s),
color: s.color ?? PALETTE[i % PALETTE.length],
}));
const chartType = cfg.type ?? "bar";
return (
<>
{cfg.title && (
<p className="text-sm font-semibold text-center text-gray-700 dark:text-gray-300 mb-3">
{cfg.title}
</p>
)}
<ResponsiveContainer width="100%" height={height}>
{chartType === "pie" ? (
<PieChart>
<Pie
data={cfg.data}
dataKey={
autoSeries[0]?.key ??
Object.keys(cfg.data[0]).find((k) => typeof cfg.data[0][k] === "number") ??
"value"
}
nameKey={
xKey !== "name"
? xKey
: (Object.keys(cfg.data[0]).find((k) => typeof cfg.data[0][k] === "string") ?? "name")
}
cx="50%"
cy="50%"
outerRadius={100}
label={({ name, percent }: { name?: string; percent?: number }) =>
`${name ?? ""} (${((percent ?? 0) * 100).toFixed(0)}%)`
}
>
{cfg.data.map((_, i) => (
<Cell key={i} fill={PALETTE[i % PALETTE.length]} />
))}
</Pie>
<Tooltip />
<Legend />
</PieChart>
) : chartType === "line" ? (
<LineChart data={cfg.data}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis dataKey={xKey} tick={{ fontSize: 11 }} />
<YAxis tick={{ fontSize: 11 }} />
<Tooltip />
<Legend />
{autoSeries.map((s, i) => (
<Line
key={s.key}
dataKey={s.key}
name={s.label ?? s.key}
stroke={s.color ?? PALETTE[i % PALETTE.length]}
strokeWidth={2}
dot={false}
/>
))}
</LineChart>
) : chartType === "area" ? (
<AreaChart data={cfg.data}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis dataKey={xKey} tick={{ fontSize: 11 }} />
<YAxis tick={{ fontSize: 11 }} />
<Tooltip />
<Legend />
{autoSeries.map((s, i) => (
<Area
key={s.key}
dataKey={s.key}
name={s.label ?? s.key}
stroke={s.color ?? PALETTE[i % PALETTE.length]}
fill={s.color ?? PALETTE[i % PALETTE.length]}
fillOpacity={0.15}
strokeWidth={2}
/>
))}
</AreaChart>
) : chartType === "multibar" || chartType === "grouped" ? (
<BarChart data={cfg.data} barCategoryGap="20%" barGap={2}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis dataKey={xKey} tick={{ fontSize: 11 }} />
<YAxis tick={{ fontSize: 11 }} />
<Tooltip />
<Legend />
{autoSeries.map((s, i) => (
<Bar
key={s.key}
dataKey={s.key}
name={s.label ?? s.key}
fill={s.color ?? PALETTE[i % PALETTE.length]}
radius={[3, 3, 0, 0]}
/>
))}
</BarChart>
) : (
<BarChart data={cfg.data}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis dataKey={xKey} tick={{ fontSize: 11 }} />
<YAxis tick={{ fontSize: 11 }} />
<Tooltip />
<Legend />
{autoSeries.map((s, i) => (
<Bar
key={s.key}
dataKey={s.key}
name={s.label ?? s.key}
fill={s.color ?? PALETTE[i % PALETTE.length]}
radius={[3, 3, 0, 0]}
/>
))}
</BarChart>
)}
</ResponsiveContainer>
</>
);
};
const ChartBlock: React.FC<{ code: string }> = ({ code }) => {
const [modalOpen, setModalOpen] = useState(false);
let cfg: ChartConfig;
try {
cfg = JSON.parse(code) as ChartConfig;
} catch {
return (
<div className="p-3 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-xs font-mono">
Invalid chart JSON — could not parse configuration.
</div>
);
}
if (!Array.isArray(cfg.data) || cfg.data.length === 0) {
return (
<div className="p-3 rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 text-xs">
Chart has no data.
</div>
);
}
return (
<>
<div
className="my-3 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 p-4 not-prose relative group cursor-zoom-in"
onClick={() => setModalOpen(true)}
title="Click to expand"
>
<ChartContent cfg={cfg} height={260} />
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity bg-gray-100 dark:bg-gray-700 rounded p-1">
<Maximize2 className="w-3.5 h-3.5 text-gray-500 dark:text-gray-400" />
</div>
</div>
{modalOpen && (
<DiagramModal onClose={() => setModalOpen(false)}>
<div className="w-[90vw] max-w-[900px] bg-white dark:bg-gray-800/40 rounded-xl p-6">
<ChartContent cfg={cfg} height={520} />
</div>
</DiagramModal>
)}
</>
);
};
// ─── Plot (scatter / line / histogram) ───────────────────────────────────────
interface PlotSeries {
name: string;
data: [number, number][];
color?: string;
bestFit?: boolean; // per-series linear regression overlay
}
interface PlotConfig {
type: "scatter" | "line" | "histogram";
title?: string;
xlabel?: string;
ylabel?: string;
series?: PlotSeries[];
data?: number[]; // shorthand: flat 1-D array for histogram
bins?: number;
bestFit?: boolean; // global: apply best-fit line to all scatter series
}
// Parse "key: value, key2: value2" respecting nested parentheses.
function _parseKV(inner: string): Record<string, string> {
const out: Record<string, string> = {};
let s = inner.trim();
while (s.length > 0) {
const km = /^(\w+)\s*:\s*/.exec(s);
if (!km) break;
s = s.slice(km[0].length);
let depth = 0;
let end = s.length;
for (let i = 0; i < s.length; i++) {
if (s[i] === "(") depth++;
else if (s[i] === ")") depth--;
else if (s[i] === "," && depth === 0 && /^\w+\s*:/.test(s.slice(i + 1).trimStart())) {
end = i;
break;
}
}
out[km[1]] = s.slice(0, end).trim();
s = s.slice(end).trimStart();
if (s.startsWith(",")) s = s.slice(1).trimStart();
}
return out;
}
// Parse "(x,y),(x2,y2),..." → [[x,y],[x2,y2],...].
// Single-element tuples "(v)" use an auto-incrementing index as x.
function _parseRows(rowsStr: string): [number, number][] {
const rows: [number, number][] = [];
const re = /\(\s*([^)]+)\s*\)/g;
let m: RegExpExecArray | null;
let idx = 0;
while ((m = re.exec(rowsStr)) !== null) {
const parts = m[1].split(",").map((v) => parseFloat(v.trim())).filter(Number.isFinite);
if (parts.length === 1) rows.push([idx++, parts[0]]);
else if (parts.length >= 2) { rows.push([parts[0], parts[1]]); idx++; }
}
return rows;
}
// Bin numeric values into k equal-width buckets for a histogram.
function _histBins(values: number[], k: number): Array<{ name: string; count: number }> {
if (!values.length) return [];
const lo = Math.min(...values);
const hi = Math.max(...values);
const w = (hi - lo) / k || 1;
const out = Array.from({ length: k }, (_, i) => ({
name: `${(lo + i * w).toFixed(2)}`,
count: 0,
}));
for (const v of values) out[Math.min(Math.floor((v - lo) / w), k - 1)].count++;
return out;
}
// Ordinary least-squares linear regression → two endpoint {x,y} objects spanning the data range.
function _linearRegression(pts: [number, number][]): { x: number; y: number }[] | null {
const n = pts.length;
if (n < 2) return null;
let sx = 0, sy = 0, sxy = 0, sx2 = 0;
for (const [x, y] of pts) { sx += x; sy += y; sxy += x * y; sx2 += x * x; }
const d = n * sx2 - sx * sx;
if (Math.abs(d) < 1e-10) return null;
const b = (n * sxy - sx * sy) / d;
const a = (sy - b * sx) / n;
const xs = pts.map(([x]) => x);
const x0 = Math.min(...xs), x1 = Math.max(...xs);
return [{ x: x0, y: a + b * x0 }, { x: x1, y: a + b * x1 }];
}
const PlotContent: React.FC<{ cfg: PlotConfig; height: number }> = ({ cfg, height }) => {
const type = cfg.type ?? "scatter";
const bins = Math.max(2, Math.min(50, cfg.bins ?? 10));
// Normalise histogram input: accept either a flat `data` number array or the
// standard `series` structure. The flat form is what LLMs naturally produce
// (e.g. {"type":"histogram","data":[72,85,91,...]}) so we must handle it first,
// before the empty-series guard would reject the whole block.
let histValues: number[] = [];
if (type === "histogram") {
if (Array.isArray(cfg.data) && cfg.data.length > 0) {
histValues = (cfg.data as unknown[]).filter((v): v is number => typeof v === "number");
} else {
histValues = (cfg.series ?? []).flatMap((s) => s.data.map(([, y]) => y));
}
}
const series = cfg.series ?? [];
const xLabel = cfg.xlabel ?? "";
const yLabel = cfg.ylabel ?? "";
const margin = { top: 4, right: 16, bottom: xLabel ? 28 : 8, left: yLabel ? 16 : 8 };
const labelStyle = { fontSize: 11, fill: "#6b7280" };
return (
<>
{cfg.title && (
<p className="text-sm font-semibold text-center text-gray-700 dark:text-gray-300 mb-3">
{cfg.title}
</p>
)}
<ResponsiveContainer width="100%" height={height}>
{type === "histogram" ? (
<BarChart data={_histBins(histValues, bins)} margin={margin}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
dataKey="name"
tick={{ fontSize: 10 }}
label={xLabel ? { value: xLabel, position: "insideBottom", offset: -12, style: labelStyle } : undefined}
/>
<YAxis
tick={{ fontSize: 11 }}
label={yLabel ? { value: yLabel, angle: -90, position: "insideLeft", style: labelStyle } : undefined}
/>
<Tooltip />
<Bar dataKey="count" name="Count" fill={PALETTE[0]} radius={[3, 3, 0, 0]} />
</BarChart>
) : (
<ScatterChart margin={margin}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
type="number"
dataKey="x"
name={xLabel || "x"}
tick={{ fontSize: 11 }}
label={xLabel ? { value: xLabel, position: "insideBottom", offset: -12, style: labelStyle } : undefined}
/>
<YAxis
type="number"
dataKey="y"
name={yLabel || "y"}
tick={{ fontSize: 11 }}
label={yLabel ? { value: yLabel, angle: -90, position: "insideLeft", style: labelStyle } : undefined}
/>
<Tooltip cursor={{ strokeDasharray: "3 3" }} />
<Legend />
{series.map((s, i) => {
const color = s.color ?? PALETTE[i % PALETTE.length];
const showFit = type === "scatter" && (s.bestFit ?? cfg.bestFit ?? false);
const fitPts = showFit ? _linearRegression(s.data) : null;
return (
<React.Fragment key={s.name}>
<Scatter
name={s.name}
data={s.data.map(([x, y]) => ({ x, y }))}
fill={color}
{...(type === "line"
? { line: { stroke: color, strokeWidth: 2 }, lineType: "joint", fillOpacity: 0.8 }
: {})}
/>
{fitPts && (
<Scatter
name={`${s.name} (best fit)`}
data={fitPts}
fill="none"
line={{ stroke: color, strokeDasharray: "5 3", strokeWidth: 1.5, strokeOpacity: 0.75 }}
lineType="joint"
legendType="none"
isAnimationActive={false}
shape={(props: { cx?: number; cy?: number }) => (
<circle cx={props.cx ?? 0} cy={props.cy ?? 0} r={0} />
)}
/>
)}
</React.Fragment>
);
})}
</ScatterChart>
)}
</ResponsiveContainer>
</>
);
};
const PlotBlock: React.FC<{ code: string }> = ({ code }) => {
const [modalOpen, setModalOpen] = useState(false);
let cfg: PlotConfig;
try {
cfg = JSON.parse(code) as PlotConfig;
} catch {
return (
<div className="p-3 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-xs font-mono">
Invalid plot configuration — could not parse JSON.
</div>
);
}
const type = cfg.type ?? "scatter";
const hasData = type === "histogram"
? (Array.isArray(cfg.data) && cfg.data.length > 0) || (cfg.series ?? []).length > 0
: (cfg.series ?? []).length > 0;
if (!hasData) {
return (
<div className="p-3 rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 text-xs">
Plot has no data.
</div>
);
}
return (
<>
<div
className="my-3 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 p-4 not-prose relative group cursor-zoom-in"
onClick={() => setModalOpen(true)}
title="Click to expand"
>
<PlotContent cfg={cfg} height={280} />
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity bg-gray-100 dark:bg-gray-700 rounded p-1">
<Maximize2 className="w-3.5 h-3.5 text-gray-500 dark:text-gray-400" />
</div>
</div>
{modalOpen && (
<DiagramModal onClose={() => setModalOpen(false)}>
<div className="w-[90vw] max-w-[900px] bg-white dark:bg-gray-800/40 rounded-xl p-6">
<PlotContent cfg={cfg} height={520} />
</div>
</DiagramModal>
)}
</>
);
};
// ─── Template pre-processor ───────────────────────────────────────────────────
// Converts inline {data}{name: ..., rows: ...} + {graph}{data: ..., type: ...}
// blocks into ```plot fences that PlotBlock renders. Data definitions are
// collected in a registry so graphs can reference them by name.
const _DATA_RE = /\{data\}\{((?:[^{}]|\([^)]*\))*)\}/g;
const _GRAPH_RE = /\{graph\}\{([^{}]*)\}/g;
function processTemplates(text: string): string {
const registry = new Map<string, [number, number][]>();
const withoutData = text.replace(_DATA_RE, (_full, inner: string) => {
const kv = _parseKV(inner);
const name = kv.name?.trim();
if (name && kv.rows) registry.set(name, _parseRows(kv.rows));
return "";
});
Eif (!registry.size) return withoutData;
return withoutData.replace(_GRAPH_RE, (original, inner: string) => {
const kv = _parseKV(inner);
const names = [
...(kv.data ? [kv.data.trim()] : []),
...(kv.series ? kv.series.trim().split(/[\s,]+/).filter(Boolean) : []),
];
const series: PlotSeries[] = names.flatMap((n) => {
const data = registry.get(n);
return data ? [{ name: n, data }] : [];
});
if (!series.length) return original;
const cfg: PlotConfig = {
type: (kv.type?.trim() ?? "scatter") as PlotConfig["type"],
...(kv.title?.trim() && { title: kv.title.trim() }),
...(kv.xlabel?.trim() && { xlabel: kv.xlabel.trim() }),
...(kv.ylabel?.trim() && { ylabel: kv.ylabel.trim() }),
...(kv.bins && { bins: Math.max(2, parseInt(kv.bins, 10) || 10) }),
series,
};
return `\`\`\`plot\n${JSON.stringify(cfg)}\n\`\`\``;
});
}
// ─── Network Graph ────────────────────────────────────────────────────────────
interface GNode {
id: string;
label?: string;
x?: number;
y?: number;
z?: number;
color?: string;
size?: number;
}
interface GEdge {
source: string;
target: string;
label?: string;
weight?: number;
color?: string;
}
interface GraphConfig {
type?: "2d" | "3d";
title?: string;
directed?: boolean;
/** x = longitude, y = latitude — flips y-axis so north points up */
geo?: boolean;
/** alias for geo; flip y-axis when coordinates use math convention (y increases upward) */
flipY?: boolean;
nodes: GNode[];
edges: GEdge[];
}
interface _SimNode {
id: string;
label: string;
nx: number; ny: number; nz: number;
vx: number; vy: number; vz: number;
fixed: boolean;
color?: string;
size?: number;
}
const _GRAPH_PALETTE = ["#6366f1","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#f97316","#ec4899"];
function _graphNodeColor(id: string): string {
const h = id.split("").reduce((a, c) => (a * 31 + c.charCodeAt(0)) | 0, 0);
return _GRAPH_PALETTE[Math.abs(h) % _GRAPH_PALETTE.length];
}
function _seededRand(seed: number) {
let s = seed | 0;
return () => {
s = (Math.imul(s, 1664525) + 1013904223) | 0;
return (s >>> 0) / 0x100000000;
};
}
function _buildSimNodes(nodes: GNode[], is3d: boolean, flipY: boolean): _SimNode[] {
const rng = _seededRand(42);
const hasPos = nodes.some(n => n.x != null && n.y != null);
if (hasPos) {
const xs = nodes.filter(n => n.x != null).map(n => n.x!);
const ys = nodes.filter(n => n.y != null).map(n => n.y!);
const zs = nodes.filter(n => n.z != null).map(n => n.z!);
const minX = Math.min(...xs), maxX = Math.max(...xs);
const minY = Math.min(...ys), maxY = Math.max(...ys);
const minZ = zs.length ? Math.min(...zs) : 0, maxZ = zs.length ? Math.max(...zs) : 1;
const rX = maxX - minX || 1, rY = maxY - minY || 1, rZ = maxZ - minZ || 1;
return nodes.map(n => {
const nx = n.x != null ? 0.08 + ((n.x - minX) / rX) * 0.84 : 0.5;
const rawY = n.y != null ? 0.08 + ((n.y - minY) / rY) * 0.84 : 0.5;
const ny = flipY ? 1.0 - rawY : rawY;
const nz = is3d && n.z != null ? 0.08 + ((n.z - minZ) / rZ) * 0.84 : 0.5;
return { id: n.id, label: n.label ?? n.id, nx, ny, nz, vx: 0, vy: 0, vz: 0, fixed: true, color: n.color, size: n.size };
});
}
return nodes.map(n => ({
id: n.id, label: n.label ?? n.id,
nx: 0.1 + rng() * 0.8, ny: 0.1 + rng() * 0.8,
nz: is3d ? 0.1 + rng() * 0.8 : 0.5,
vx: 0, vy: 0, vz: 0, fixed: false, color: n.color, size: n.size,
}));
}
function _runForceSimulation(nodes: _SimNode[], edges: GEdge[], is3d: boolean): void {
if (nodes.every(n => n.fixed)) return;
const nodeMap = new Map(nodes.map(n => [n.id, n]));
for (let iter = 0; iter < 300; iter++) {
const cool = 1 - iter / 300;
for (let i = 0; i < nodes.length; i++) {
for (let j = i + 1; j < nodes.length; j++) {
const a = nodes[i], b = nodes[j];
const dx = b.nx - a.nx, dy = b.ny - a.ny, dz = is3d ? b.nz - a.nz : 0;
const d2 = dx*dx + dy*dy + dz*dz + 1e-4;
const f = 4e-3 / d2;
const d = Math.sqrt(d2);
const fx = dx/d*f, fy = dy/d*f, fz = is3d ? dz/d*f : 0;
if (!a.fixed) { a.vx -= fx; a.vy -= fy; a.vz -= fz; }
if (!b.fixed) { b.vx += fx; b.vy += fy; b.vz += fz; }
}
}
for (const e of edges) {
const a = nodeMap.get(e.source), b = nodeMap.get(e.target);
if (!a || !b) continue;
const dx = b.nx - a.nx, dy = b.ny - a.ny, dz = is3d ? b.nz - a.nz : 0;
const d = Math.sqrt(dx*dx + dy*dy + dz*dz) || 1e-3;
const target = e.weight ? Math.min(0.45, e.weight / (e.weight + 10) * 0.5 + 0.1) : 0.2;
const stretch = (d - target) * 0.05;
const fx = dx/d*stretch, fy = dy/d*stretch, fz = is3d ? dz/d*stretch : 0;
if (!a.fixed) { a.vx += fx; a.vy += fy; a.vz += fz; }
if (!b.fixed) { b.vx -= fx; b.vy -= fy; b.vz -= fz; }
}
for (const n of nodes) {
if (n.fixed) continue;
n.vx += (0.5 - n.nx) * 0.012;
n.vy += (0.5 - n.ny) * 0.012;
if (is3d) n.vz += (0.5 - n.nz) * 0.012;
}
for (const n of nodes) {
if (n.fixed) continue;
n.vx *= 0.85; n.vy *= 0.85; n.vz *= 0.85;
n.nx = Math.max(0.04, Math.min(0.96, n.nx + n.vx * cool));
n.ny = Math.max(0.04, Math.min(0.96, n.ny + n.vy * cool));
if (is3d) n.nz = Math.max(0.04, Math.min(0.96, n.nz + n.vz * cool));
}
}
}
const _GW = 600, _GH = 360;
type _Pos = { x: number; y: number; depth: number };
const NetworkGraphContent: React.FC<{ cfg: GraphConfig; expanded?: boolean }> = ({ cfg, expanded = false }) => {
const is3d = cfg.type === "3d";
const [pan, setPan] = useState({ x: 0, y: 0 });
const [zoom, setZoom] = useState(1);
const [rot, setRot] = useState({ x: 0.35, y: 0.4 });
const dragRef = useRef<{ sx: number; sy: number; panStart: { x: number; y: number }; rotStart: { x: number; y: number } } | null>(null);
const arrowId = useId().replace(/[^a-zA-Z0-9]/g, "g");
const simNodes = useMemo(() => {
const flipY = cfg.geo === true || cfg.flipY === true;
const sn = _buildSimNodes(cfg.nodes, is3d, flipY);
_runForceSimulation(sn, cfg.edges, is3d);
return sn;
}, [cfg.nodes, cfg.edges, is3d, cfg.geo, cfg.flipY]);
const positions = useMemo<Map<string, _Pos>>(() => {
const map = new Map<string, _Pos>();
const cosRY = Math.cos(rot.y), sinRY = Math.sin(rot.y);
const cosRX = Math.cos(rot.x), sinRX = Math.sin(rot.x);
for (const n of simNodes) {
if (!is3d) {
map.set(n.id, { x: n.nx * _GW, y: n.ny * _GH, depth: 0 });
} else {
const x1 = (n.nx - 0.5) * cosRY - (n.nz - 0.5) * sinRY;
const z1 = (n.nx - 0.5) * sinRY + (n.nz - 0.5) * cosRY;
const y2 = (n.ny - 0.5) * cosRX - z1 * sinRX;
const z2 = (n.ny - 0.5) * sinRX + z1 * cosRX;
const p = 2.5 / (2.5 + z2);
map.set(n.id, { x: (x1 * p + 0.5) * _GW, y: (y2 * p + 0.5) * _GH, depth: z2 });
}
}
return map;
}, [simNodes, is3d, rot.x, rot.y]);
const sortedNodes = useMemo(() => {
if (!is3d) return simNodes;
return [...simNodes].sort((a, b) => (positions.get(a.id)?.depth ?? 0) - (positions.get(b.id)?.depth ?? 0));
}, [simNodes, positions, is3d]);
const svgHeight = expanded ? 540 : 320;
return (
<svg
viewBox={`0 0 ${_GW} ${_GH}`}
width="100%"
height={svgHeight}
className="select-none block"
style={{ cursor: "grab", touchAction: "none" }}
onWheel={(e) => {
e.preventDefault();
const f = e.deltaY < 0 ? 1.12 : 1 / 1.12;
setZoom(z => Math.max(0.25, Math.min(6, z * f)));
}}
onMouseDown={(e) => {
if (e.button !== 0) return;
dragRef.current = { sx: e.clientX, sy: e.clientY, panStart: { ...pan }, rotStart: { ...rot } };
}}
onMouseMove={(e) => {
const d = dragRef.current;
if (!d) return;
if (is3d) {
setRot({ x: d.rotStart.x + (e.clientY - d.sy) * 0.007, y: d.rotStart.y + (e.clientX - d.sx) * 0.007 });
} else {
const scale = _GW / (e.currentTarget.getBoundingClientRect().width || _GW);
setPan({ x: d.panStart.x + (e.clientX - d.sx) * scale / zoom, y: d.panStart.y + (e.clientY - d.sy) * scale / zoom });
}
}}
onMouseUp={() => { dragRef.current = null; }}
onMouseLeave={() => { dragRef.current = null; }}
>
<defs>
{cfg.directed && (
<marker id={arrowId} markerWidth="6" markerHeight="4" refX="5" refY="2" orient="auto">
<path d="M0,0 L6,2 L0,4 Z" fill="#94a3b8" />
</marker>
)}
</defs>
<g transform={`translate(${_GW / 2 + pan.x},${_GH / 2 + pan.y}) scale(${zoom}) translate(${-_GW / 2},${-_GH / 2})`}>
{cfg.edges.map((edge, i) => {
const sp = positions.get(edge.source);
const tp = positions.get(edge.target);
if (!sp || !tp) return null;
const mx = (sp.x + tp.x) / 2, my = (sp.y + tp.y) / 2;
let x2 = tp.x, y2 = tp.y;
if (cfg.directed) {
const edx = tp.x - sp.x, edy = tp.y - sp.y;
const dist = Math.sqrt(edx * edx + edy * edy) || 1;
const tgtNode = simNodes.find(n => n.id === edge.target);
const tr = (tgtNode?.size ?? 7) + 5;
x2 = tp.x - edx / dist * tr;
y2 = tp.y - edy / dist * tr;
}
return (
<g key={i}>
<line
x1={sp.x} y1={sp.y} x2={x2} y2={y2}
stroke={edge.color ?? "#94a3b8"} strokeWidth={1.5} strokeOpacity={0.65}
markerEnd={cfg.directed ? `url(#${arrowId})` : undefined}
/>
{edge.label && (
<text x={mx} y={my - 5} textAnchor="middle" fontSize={9} fill="#9ca3af" fontFamily="system-ui,sans-serif">
{edge.label}
</text>
)}
</g>
);
})}
{sortedNodes.map(n => {
const pos = positions.get(n.id);
if (!pos) return null;
const color = n.color ?? _graphNodeColor(n.id);
const base = n.size ?? 7;
const r = is3d ? base * Math.max(0.5, 0.75 + pos.depth * 0.5) : base;
return (
<g key={n.id}>
<circle cx={pos.x} cy={pos.y} r={r + 3} fill={color} fillOpacity={0.12} />
<circle cx={pos.x} cy={pos.y} r={r} fill={color} stroke="white" strokeWidth={1.5} />
<text
x={pos.x} y={pos.y + r + 12}
textAnchor="middle" fontSize={9} fontFamily="system-ui,sans-serif" fontWeight="500"
fill="#4b5563"
>
{n.label}
</text>
</g>
);
})}
</g>
</svg>
);
};
const NetworkGraphBlock: React.FC<{ code: string }> = ({ code }) => {
const isStreaming = useContext(_StreamingCtx);
const [modalOpen, setModalOpen] = useState(false);
const cfg = useMemo<GraphConfig | null>(() => {
try { return JSON.parse(code) as GraphConfig; } catch { return null; }
}, [code]);
if (isStreaming) {
return (
<div className="my-3 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 p-4 text-xs text-gray-400 dark:text-gray-500 not-prose">
Graph streaming…
</div>
);
}
if (!cfg) {
return (
<div className="p-3 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-xs font-mono">
Invalid graph JSON — could not parse configuration.
</div>
);
}
if (!Array.isArray(cfg.nodes) || cfg.nodes.length === 0) {
return (
<div className="p-3 rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 text-xs">
Graph has no nodes.
</div>
);
}
const hint = cfg.type === "3d" ? "Drag to rotate · Scroll to zoom" : "Drag to pan · Scroll to zoom";
return (
<>
<div className="my-3 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 overflow-hidden not-prose relative group">
{cfg.title && (
<p className="text-sm font-semibold text-center text-gray-700 dark:text-gray-300 pt-3 px-4 pb-1">
{cfg.title}
</p>
)}
<NetworkGraphContent cfg={cfg} />
<div className="absolute bottom-2 left-3 text-[9px] text-gray-400 dark:text-gray-600 select-none pointer-events-none">
{hint}
</div>
<button
onClick={() => setModalOpen(true)}
className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity bg-gray-100 dark:bg-gray-700 rounded p-1"
title="Expand"
>
<Maximize2 className="w-3.5 h-3.5 text-gray-500 dark:text-gray-400" />
</button>
</div>
{modalOpen && (
<DiagramModal onClose={() => setModalOpen(false)}>
<div className="bg-white dark:bg-gray-800 rounded-xl p-4 w-[90vw] max-w-[900px]">
{cfg.title && (
<p className="text-sm font-semibold text-center text-gray-700 dark:text-gray-300 mb-2">
{cfg.title}
</p>
)}
<NetworkGraphContent cfg={cfg} expanded />
</div>
</DiagramModal>
)}
</>
);
};
// ─── Mermaid Graph ────────────────────────────────────────────────────────────
const _StreamingCtx = createContext(false);
let mermaidReady = false;
const DiagramModal: React.FC<{ children: React.ReactNode; onClose: () => void }> = ({ children, onClose }) => {
const [zoom, setZoom] = useState(1);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [onClose]);
useEffect(() => {
const el = containerRef.current;
if (!el) return;
const handler = (e: WheelEvent) => {
if (!e.ctrlKey && !e.metaKey) return;
e.preventDefault();
setZoom(z => {
const delta = e.deltaY < 0 ? 0.15 : -0.15;
return Math.min(4, Math.max(0.25, parseFloat((z + delta).toFixed(2))));
});
};
el.addEventListener("wheel", handler, { passive: false });
return () => el.removeEventListener("wheel", handler);
}, []);
const zoomIn = () => setZoom(z => Math.min(4, parseFloat((z + 0.25).toFixed(2))));
const zoomOut = () => setZoom(z => Math.max(0.25, parseFloat((z - 0.25).toFixed(2))));
return (
<div
data-pdf-hide
role="dialog"
aria-modal="true"
aria-label="Expanded diagram"
className="fixed inset-0 z-50 flex flex-col bg-black/75 backdrop-blur-sm"
onClick={onClose}
>
<div
className="flex items-center justify-between px-4 py-2 bg-gray-900/90 border-b border-gray-700 shrink-0"
onClick={e => e.stopPropagation()}
>
<div className="flex items-center gap-1">
<button
onClick={zoomOut}
className="p-1.5 rounded hover:bg-gray-700 text-gray-300 hover:text-white transition-colors"
title="Zoom out"
>
<ZoomOut className="w-4 h-4" />
</button>
<button
onClick={() => setZoom(1)}
className="px-2 py-1 rounded hover:bg-gray-700 text-gray-300 hover:text-white transition-colors text-xs font-mono min-w-[3.5rem] text-center"
title="Reset zoom"
>
<RotateCcw className="w-3 h-3 inline mr-1" />
{Math.round(zoom * 100)}%
</button>
<button
onClick={zoomIn}
className="p-1.5 rounded hover:bg-gray-700 text-gray-300 hover:text-white transition-colors"
title="Zoom in"
>
<ZoomIn className="w-4 h-4" />
</button>
<span className="ml-3 text-xs text-gray-500">Ctrl + scroll to zoom</span>
</div>
<button
onClick={onClose}
className="p-1.5 rounded hover:bg-gray-700 text-gray-300 hover:text-white transition-colors"
title="Close (Esc)"
>
<X className="w-4 h-4" />
</button>
</div>
<div
ref={containerRef}
className="flex-1 overflow-auto flex items-start justify-center p-10"
onClick={e => e.stopPropagation()}
>
<div style={{ zoom: zoom }}>
{children}
</div>
</div>
</div>
);
};
const MermaidBlock: React.FC<{ code: string }> = ({ code }) => {
const uid = useId().replace(/:/g, "m");
const isStreaming = useContext(_StreamingCtx);
const [svg, setSvg] = useState<string>("");
const [error, setError] = useState<string>("");
const [modalOpen, setModalOpen] = useState(false);
const latestCode = useRef(code);
latestCode.current = code;
useEffect(() => {
// remark-gfm treats end-of-document as an implicit closing fence, so
// MermaidBlock receives partial code on every chunk while streaming.
// Skip rendering until the full diagram has arrived to prevent Mermaid
// from injecting its error overlay into the DOM.
if (isStreaming) return;
if (!mermaidReady) {
const dark = document.documentElement.classList.contains("dark");
mermaid.initialize(mermaidConfig(dark ? "dark" : "default"));
mermaidReady = true;
}
setSvg("");
setError("");
mermaid
.render(uid, latestCode.current)
.then(({ svg: rendered }) => setSvg(rendered))
.catch((err: unknown) => setError(err instanceof Error ? err.message : String(err)));
}, [code, isStreaming, uid]);
if (isStreaming) {
return (
<div className="my-3 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 p-4 text-xs text-gray-400 dark:text-gray-500 not-prose">
Diagram streaming…
</div>
);
}
if (error) {
return (
<div className="p-3 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-xs font-mono">
Invalid Mermaid diagram — {error}
</div>
);
}
if (!svg) {
return (
<div className="my-3 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 p-4 text-xs text-gray-400 dark:text-gray-500 not-prose">
Rendering diagram…
</div>
);
}
return (
<>
<div
className="my-3 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 p-4 overflow-x-auto not-prose flex justify-center [&_svg]:max-w-full [&_svg]:h-auto relative group cursor-zoom-in"
onClick={() => setModalOpen(true)}
title="Click to expand"
>
{/* The source rides along so a PDF export can re-render the diagram
in the light theme — Mermaid bakes its theme into the SVG. */}
<div data-mermaid-source={code} dangerouslySetInnerHTML={{ __html: svg }} />
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity bg-gray-100 dark:bg-gray-700 rounded p-1">
<Maximize2 className="w-3.5 h-3.5 text-gray-500 dark:text-gray-400" />
</div>
</div>
{modalOpen && (
<DiagramModal onClose={() => setModalOpen(false)}>
<div className="[&_svg]:max-w-none [&_svg]:h-auto" dangerouslySetInnerHTML={{ __html: svg }} />
</DiagramModal>
)}
</>
);
};
// ─── Map (Leaflet + GeoJSON on the shared basemap, components/map) ───────────
type _MapRawGeo = Record<string, unknown>;
interface _MapCfg {
title?: string;
center?: [number, number];
zoom?: number;
geojson?: _MapRawGeo;
// raw GeoJSON detection helpers
type?: string;
}
const _GEO_TYPES = new Set([
"FeatureCollection", "Feature",
"Point", "MultiPoint", "LineString", "MultiLineString",
"Polygon", "MultiPolygon", "GeometryCollection",
]);
function _parseMapCode(code: string): { geojson: _MapRawGeo; cfg: _MapCfg } | { error: string } {
let p: _MapCfg;
try { p = JSON.parse(code) as _MapCfg; } catch { return { error: "Invalid map JSON — could not parse." }; }
if (p.type && _GEO_TYPES.has(p.type)) return { geojson: p as _MapRawGeo, cfg: {} };
if (p.geojson) return { geojson: p.geojson, cfg: p };
return { error: "No GeoJSON found — provide a GeoJSON FeatureCollection directly, or an object with a 'geojson' key." };
}
function _mapStyle(feature?: { properties?: Record<string, unknown> | null }): L.PathOptions {
const q = feature?.properties ?? {};
return {
color: String(q["stroke"] ?? q["color"] ?? "#6366f1"),
weight: Number(q["stroke-width"] ?? q["weight"] ?? 2),
fillColor: String(q["fill"] ?? q["color"] ?? "#6366f1"),
fillOpacity: Number(q["fill-opacity"] ?? 0.25),
opacity: Number(q["stroke-opacity"] ?? 0.85),
};
}
const _MapExpandModal: React.FC<{ onClose: () => void; children: React.ReactNode }> = ({ onClose, children }) => {
useEffect(() => {
const h = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
document.addEventListener("keydown", h);
return () => document.removeEventListener("keydown", h);
}, [onClose]);
return (
<div
data-pdf-hide
role="dialog"
aria-modal="true"
aria-label="Expanded map"
className="fixed inset-0 z-[9999] bg-black/75 backdrop-blur-sm flex items-center justify-center p-6"
onClick={onClose}
>
<div className="relative w-full max-w-4xl" onClick={e => e.stopPropagation()}>
<button
onClick={onClose}
className="absolute -top-8 right-0 flex items-center gap-1.5 text-xs text-gray-300 hover:text-white transition-colors"
title="Close (Esc)"
>
<X className="w-3.5 h-3.5" />
Close
</button>
{children}
</div>
</div>
);
};
const _MapView: React.FC<{ geojson: _MapRawGeo; cfg: _MapCfg; height: number }> = ({ geojson, cfg, height }) => {
const isDark = document.documentElement.classList.contains("dark");
// Compute initial centre/bounds synchronously — L.geoJSON().getBounds() is pure maths, no DOM needed.
const [initProps] = useState<
{ bounds: L.LatLngBoundsExpression; boundsOptions: L.FitBoundsOptions } |
{ center: L.LatLngExpression; zoom: number }
>(() => {
if (cfg.center) return { center: cfg.center as L.LatLngExpression, zoom: cfg.zoom ?? 13 };
try {
const b = L.geoJSON(geojson as unknown as Parameters<typeof L.geoJSON>[0]).getBounds();
if (b.isValid()) return { bounds: b, boundsOptions: { padding: [24, 24] } };
} catch { /* fall through */ }
return { center: [51.505, -0.09] as L.LatLngExpression, zoom: 10 };
});
return (
<MapContainer
{...initProps}
style={{ height, width: "100%" }}
scrollWheelZoom
// `!`: leaflet.css is unlayered, so its #ddd beats any utility.
// It shows before tiles load, and wherever there are none.
className="!bg-gray-100 dark:!bg-gray-900"
>
<BasemapLayer dark={isDark} />
<LfGeoJSON
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data={geojson as any}
style={_mapStyle as (feature?: Parameters<typeof _mapStyle>[0]) => L.PathOptions}
pointToLayer={(feature, latlng) =>
L.circleMarker(latlng, {
radius: feature.properties?.["marker-size"] === "small" ? 5 : feature.properties?.["marker-size"] === "large" ? 11 : 8,
fillColor: String(feature.properties?.["marker-color"] ?? feature.properties?.color ?? "#6366f1"),
color: "white",
weight: 1.5,
fillOpacity: 0.9,
})
}
onEachFeature={(feature, layer) => {
const q = feature.properties ?? {};
const name = q.name ?? q.title ?? q.label ?? q.Name;
const desc = q.description ?? q.desc ?? q.Description;
if (name ?? desc) {
layer.bindPopup(
[name ? `<strong>${String(name)}</strong>` : null, desc ? String(desc) : null]
.filter(Boolean).join("<br/>")
);
}
}}
/>
</MapContainer>
);
};
const MapBlock: React.FC<{ code: string }> = ({ code }) => {
const isStreaming = useContext(_StreamingCtx);
const [modalOpen, setModalOpen] = useState(false);
const parsed = useMemo(() => _parseMapCode(code), [code]);
if (isStreaming) {
return (
<div className="my-3 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 p-4 text-xs text-gray-400 dark:text-gray-500 not-prose">
Map loading…
</div>
);
}
if ("error" in parsed) {
return (
<div className="p-3 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-xs font-mono">
{parsed.error}
</div>
);
}
const { geojson, cfg } = parsed;
return (
<>
<div className="my-3 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden not-prose relative group">
{cfg.title && (
<div className="px-3 py-2 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 text-sm font-semibold text-gray-700 dark:text-gray-300">
{cfg.title}
</div>
)}
<_MapView geojson={geojson} cfg={cfg} height={300} />
<button
onClick={() => setModalOpen(true)}
className="absolute top-2 right-2 z-[1000] opacity-0 group-hover:opacity-100 transition-opacity bg-white/90 dark:bg-gray-800/90 rounded p-1 shadow-sm"
title="Expand"
>
<Maximize2 className="w-3.5 h-3.5 text-gray-500 dark:text-gray-400" />
</button>
</div>
{modalOpen && (
<_MapExpandModal onClose={() => setModalOpen(false)}>
<div className="rounded-xl overflow-hidden shadow-2xl">
{cfg.title && (
<div className="px-4 py-2.5 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 text-sm font-semibold text-gray-700 dark:text-gray-300">
{cfg.title}
</div>
)}
<_MapView geojson={geojson} cfg={cfg} height={560} />
</div>
</_MapExpandModal>
)}
</>
);
};
// ─── Document Block ───────────────────────────────────────────────────────────
// The bodies `extractDocuments` lifted out of this content; a document block's
// code is its index here.
const _DocumentsCtx = createContext<string[]>([]);
const DocumentBlock: React.FC<{ code: string }> = ({ code }) => {
const documents = useContext(_DocumentsCtx);
// Where the record this content belongs to serves its documents' images.
const imageUrl = useDocumentImageUrl();
const index = Number(code.trim());
const body = Number.isInteger(index) ? documents[index] : undefined;
const document = body !== undefined ? parseDocument(body) : null;
if (!document) return null;
return (
<DocumentCard
document={document}
index={index}
renderMarkdown={(markdown) => (
// A document inside a document's body is not the message's, so it
// gets no download; this document's images are its stored copies.
<DocumentDownloadProvider download={null}>
<DocumentImagesProvider
images={documentImages(document)}
imageUrl={imageUrl}
>
<RichMarkdown content={markdown} />
</DocumentImagesProvider>
</DocumentDownloadProvider>
)}
/>
);
};
// ─── Code Block ───────────────────────────────────────────────────────────────
const CodeBlock: React.FC<{ language: string; code: string }> = ({
language,
code,
}) => {
const [copied, setCopied] = useState(false);
Iif (language === "chart") return <ChartBlock code={code} />;
Iif (language === "plot") return <PlotBlock code={code} />;
Iif (language === "mermaid") return <MermaidBlock code={code} />;
Iif (language === "graph") return <NetworkGraphBlock code={code} />;
Iif (language === "map") return <MapBlock code={code} />;
Eif (language === "document") return <DocumentBlock code={code} />;
const copy = () => {
void navigator.clipboard.writeText(code).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
});
};
return (
<div className="my-3 rounded-xl overflow-hidden border border-gray-200 dark:border-gray-700 not-prose">
<div className="flex items-center justify-between px-3.5 py-1.5 bg-gray-100 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700">
<span className="text-[10px] font-mono text-gray-500 dark:text-gray-400 uppercase tracking-wider">
{language || "text"}
</span>
<button
onClick={copy}
className="flex items-center gap-1 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
>
{copied ? (
<Check className="w-3 h-3 text-emerald-500" />
) : (
<Copy className="w-3 h-3" />
)}
<span className="text-[10px]">{copied ? "Copied" : "Copy"}</span>
</button>
</div>
<SyntaxHighlighter
language={language || "text"}
style={oneDark}
customStyle={{
margin: 0,
padding: "12px 16px",
fontSize: "0.72rem",
lineHeight: "1.65",
background: "#1e2330",
}}
wrapLongLines
>
{code}
</SyntaxHighlighter>
</div>
);
};
// ─── Table Components ─────────────────────────────────────────────────────────
const MarkdownTable: React.FC<React.PropsWithChildren> = ({ children }) => (
<div className="my-3 overflow-x-auto rounded-xl border border-gray-200 dark:border-gray-700 not-prose">
<table className="w-full text-sm border-collapse">{children}</table>
</div>
);
const MarkdownTh: React.FC<React.PropsWithChildren> = ({ children }) => (
<th className="px-4 py-2.5 text-left text-xs font-semibold text-gray-600 dark:text-gray-400 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 whitespace-nowrap">
{children}
</th>
);
const MarkdownTd: React.FC<React.PropsWithChildren> = ({ children }) => (
<td className="px-4 py-2 text-gray-800 dark:text-gray-200 border-b border-gray-100 dark:border-gray-800">
{children}
</td>
);
const MarkdownTr: React.FC<React.PropsWithChildren> = ({ children }) => (
<tr className="hover:bg-gray-50/50 dark:hover:bg-gray-700/20 transition-colors last:*:border-0">
{children}
</tr>
);
// ─── Math normaliser ──────────────────────────────────────────────────────────
// Models commonly emit LaTeX math with delimiters that remark-math doesn't
// understand. Normalise them to the $...$ / $$...$$ form before parsing.
function normalizeMath(text: string): string {
// \[...\] → $$...$$ (display math — standard LaTeX delimiter)
// RegExp constructor avoids linter false-positives on \[ in regex literals.
let out = text.replace(
new RegExp('\\\\\\[([\\s\\S]*?)\\\\\\]', 'g'),
(_: string, inner: string) => `$$${inner}$$`,
);
// \(...\) → $...$ (inline math — standard LaTeX delimiter)
out = out.replace(
new RegExp('\\\\\\(([\\s\\S]*?)\\\\\\)', 'g'),
(_: string, inner: string) => `$${inner}$`,
);
// Bare [ ... ] lines containing at least one LaTeX command (\word).
// Targets lines where the entire paragraph is wrapped in [ ] — models
// sometimes emit display math this way without the leading backslash.
// [[] and [\]] are character-class equivalents of \[ and \] to satisfy linter.
out = out.replace(
/(?:^|\n)([ \t]*)[[]([^[\]\n]*\\[a-zA-Z]+[^[\]\n]*)[\]]([ \t]*)(?=\n|$)/gm,
(_m: string, leading: string, inner: string, trailing: string) =>
`\n${leading}$$${inner}$$${trailing}`,
);
return out;
}
// ─── RichMarkdown ─────────────────────────────────────────────────────────────
export interface RichMarkdownProps {
content: string;
className?: string;
isStreaming?: boolean;
}
const RichMarkdown: React.FC<RichMarkdownProps> = ({
content,
className = "",
isStreaming = false,
}) => {
const { text, documents } = extractDocuments(content);
return (
<_DocumentsCtx.Provider value={documents}>
<_StreamingCtx.Provider value={isStreaming}>
<div
className={`prose prose-sm dark:prose-invert max-w-none
prose-p:my-2 prose-p:leading-relaxed
prose-headings:font-semibold prose-headings:mt-5 prose-headings:mb-2
prose-h1:text-xl prose-h2:text-lg prose-h3:text-base
prose-ul:my-2 prose-ol:my-2 prose-li:my-1 prose-li:leading-relaxed
prose-hr:my-5
prose-blockquote:my-3 prose-blockquote:not-italic
prose-blockquote:border-l-indigo-300 dark:prose-blockquote:border-l-indigo-700
prose-strong:font-semibold
prose-pre:p-0 prose-pre:bg-transparent prose-pre:border-0 prose-pre:shadow-none
${className}`}
>
<ReactMarkdown
remarkPlugins={[remarkMath, remarkGfm]}
rehypePlugins={[rehypeKatex]}
components={{
code({ className: cls, children }) {
const match = /language-(\w+)/.exec(cls ?? "");
const language = match?.[1] ?? "";
const text = String(children).replace(/\n$/, "");
Eif (match || text.includes("\n")) {
return <CodeBlock language={language} code={text} />;
}
return (
<code className="text-xs bg-gray-100 dark:bg-gray-800 px-1 py-0.5 rounded font-mono not-italic">
{children}
</code>
);
},
pre({ children }) {
return <>{children}</>;
},
a({ href, children }) {
const cite = /^#cite-(\d{1,3})$/.exec(href ?? "");
Eif (cite) {
return (
<sup className="not-prose">
<span
title={`Source ${cite[1]} — see Sources below`}
className="inline-flex items-center justify-center min-w-[1.1rem] h-[1.1rem] px-1 mx-0.5 rounded-full bg-indigo-50 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-300 text-[10px] font-semibold select-none cursor-default"
>
{cite[1]}
</span>
</sup>
);
}
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-indigo-600 dark:text-indigo-400 font-medium no-underline hover:underline underline-offset-2 break-words"
>
{children}
</a>
);
},
// Inside a document's text, the stored copy (or the alt text);
// elsewhere, the image as written.
img({ src, alt, title }) {
return <MarkdownImage src={src} alt={alt} title={title} />;
},
table: MarkdownTable,
th: MarkdownTh,
td: MarkdownTd,
tr: MarkdownTr,
}}
>
{normalizeMath(processCitations(processTemplates(text)))}
</ReactMarkdown>
</div>
</_StreamingCtx.Provider>
</_DocumentsCtx.Provider>
);
};
export default RichMarkdown;
|