index.js 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118
  1. #!/usr/bin/env node
  2. const fs = require('fs');
  3. const path = require('path');
  4. const { build } = require('esbuild');
  5. const { convertV8ToGraph } = require('./convert_v8_to_graph');
  6. const { convertV8ToGraphV2 } = require('./convert_v8_to_graph_v2');
  7. // 读取命令行参数
  8. const args = process.argv.slice(2);
  9. if (args.length === 0) {
  10. console.error('Usage: node index.js <path-to-run_context.json> [output.html]');
  11. process.exit(1);
  12. }
  13. const inputFile = args[0];
  14. const outputFile = args[1] || 'query_graph_output.html';
  15. // 读取输入数据
  16. const inputData = JSON.parse(fs.readFileSync(inputFile, 'utf-8'));
  17. // 检测数据格式并转换
  18. let data;
  19. if (inputData.rounds && inputData.o) {
  20. // v6.1.2.8 格式,需要转换
  21. console.log('✨ 检测到 v6.1.2.8 格式,正在转换为图结构...');
  22. // 尝试读取 search_results.json
  23. let searchResults = null;
  24. const searchResultsPath = path.join(path.dirname(inputFile), 'search_results.json');
  25. if (fs.existsSync(searchResultsPath)) {
  26. console.log('📄 读取搜索结果数据...');
  27. searchResults = JSON.parse(fs.readFileSync(searchResultsPath, 'utf-8'));
  28. }
  29. // 使用新的转换函数(按 Round > 步骤 > 数据 组织)
  30. const graphData = convertV8ToGraphV2(inputData, searchResults);
  31. data = {
  32. nodes: graphData.nodes,
  33. edges: graphData.edges,
  34. iterations: graphData.iterations
  35. };
  36. console.log(`✅ 转换完成: ${Object.keys(data.nodes).length} 个节点, ${data.edges.length} 条边`);
  37. } else if (inputData.nodes && inputData.edges) {
  38. // v6.1.2.5 格式,直接使用
  39. console.log('✨ 检测到 v6.1.2.5 格式,直接使用');
  40. data = inputData;
  41. } else {
  42. console.error('❌ 无法识别的数据格式');
  43. process.exit(1);
  44. }
  45. // 创建临时 React 组件文件
  46. const reactComponentPath = path.join(__dirname, 'temp_flow_component_v2.jsx');
  47. const reactComponent = `
  48. import React, { useState, useCallback, useMemo, useEffect } from 'react';
  49. import { createRoot } from 'react-dom/client';
  50. import {
  51. ReactFlow,
  52. Controls,
  53. Background,
  54. useNodesState,
  55. useEdgesState,
  56. Handle,
  57. Position,
  58. useReactFlow,
  59. ReactFlowProvider,
  60. } from '@xyflow/react';
  61. import '@xyflow/react/dist/style.css';
  62. const data = ${JSON.stringify(data, null, 2)};
  63. // 根据节点类型获取边框颜色
  64. function getNodeTypeColor(type) {
  65. const typeColors = {
  66. 'root': '#6b21a8', // 紫色 - 根节点
  67. 'round': '#7c3aed', // 深紫 - Round节点
  68. 'step': '#f59e0b', // 橙色 - 步骤节点
  69. 'seg': '#10b981', // 绿色 - 分词
  70. 'q': '#3b82f6', // 蓝色 - Query
  71. 'sug': '#06b6d4', // 青色 - Sug建议词
  72. 'seed': '#84cc16', // 黄绿 - Seed
  73. 'add_word': '#22c55e', // 绿色 - 加词生成
  74. 'search_word': '#8b5cf6', // 紫色 - 搜索词
  75. 'post': '#ec4899', // 粉色 - 帖子
  76. 'filtered_sug': '#14b8a6',// 青绿 - 筛选的sug
  77. 'next_q': '#2563eb', // 深蓝 - 下轮查询
  78. 'next_seed': '#65a30d', // 深黄绿 - 下轮种子
  79. 'search': '#8b5cf6', // 深紫 - 搜索(兼容旧版)
  80. 'operation': '#f59e0b', // 橙色 - 操作节点(兼容旧版)
  81. 'query': '#3b82f6', // 蓝色 - 查询(兼容旧版)
  82. 'note': '#ec4899', // 粉色 - 帖子(兼容旧版)
  83. };
  84. return typeColors[type] || '#9ca3af';
  85. }
  86. // 查询节点组件 - 卡片样式
  87. function QueryNode({ id, data, sourcePosition, targetPosition }) {
  88. // 所有节点默认展开
  89. const expanded = true;
  90. // 获取节点类型颜色
  91. const typeColor = getNodeTypeColor(data.nodeType || 'query');
  92. return (
  93. <div>
  94. <Handle
  95. type="target"
  96. position={targetPosition || Position.Left}
  97. style={{ background: typeColor, width: 8, height: 8 }}
  98. />
  99. <div
  100. style={{
  101. padding: '12px',
  102. borderRadius: '8px',
  103. border: data.isHighlighted ? \`3px solid \${typeColor}\` :
  104. data.isCollapsed ? \`2px solid \${typeColor}\` :
  105. data.isSelected === false ? '2px dashed #d1d5db' :
  106. \`2px solid \${typeColor}\`,
  107. background: data.isHighlighted ? '#eef2ff' :
  108. data.isSelected === false ? '#f9fafb' : 'white',
  109. minWidth: '200px',
  110. maxWidth: '280px',
  111. boxShadow: data.isHighlighted ? '0 0 0 4px rgba(102, 126, 234, 0.25), 0 4px 16px rgba(102, 126, 234, 0.4)' :
  112. data.isCollapsed ? '0 4px 12px rgba(102, 126, 234, 0.15)' :
  113. data.level === 0 ? '0 4px 12px rgba(139, 92, 246, 0.15)' : '0 2px 6px rgba(0, 0, 0, 0.06)',
  114. transition: 'all 0.3s ease',
  115. cursor: 'pointer',
  116. position: 'relative',
  117. opacity: data.isSelected === false ? 0.6 : 1,
  118. }}
  119. >
  120. {/* 折叠当前节点按钮 - 左边 */}
  121. <div
  122. style={{
  123. position: 'absolute',
  124. top: '6px',
  125. left: '6px',
  126. width: '20px',
  127. height: '20px',
  128. borderRadius: '50%',
  129. background: '#f59e0b',
  130. color: 'white',
  131. display: 'flex',
  132. alignItems: 'center',
  133. justifyContent: 'center',
  134. fontSize: '11px',
  135. fontWeight: 'bold',
  136. cursor: 'pointer',
  137. transition: 'all 0.2s ease',
  138. zIndex: 10,
  139. }}
  140. onClick={(e) => {
  141. e.stopPropagation();
  142. if (data.onHideSelf) {
  143. data.onHideSelf();
  144. }
  145. }}
  146. onMouseEnter={(e) => {
  147. e.currentTarget.style.background = '#d97706';
  148. }}
  149. onMouseLeave={(e) => {
  150. e.currentTarget.style.background = '#f59e0b';
  151. }}
  152. title="隐藏当前节点"
  153. >
  154. ×
  155. </div>
  156. {/* 聚焦按钮 - 右上角 */}
  157. <div
  158. style={{
  159. position: 'absolute',
  160. top: '6px',
  161. right: '6px',
  162. width: '20px',
  163. height: '20px',
  164. borderRadius: '50%',
  165. background: data.isFocused ? '#10b981' : '#e5e7eb',
  166. color: data.isFocused ? 'white' : '#6b7280',
  167. display: 'flex',
  168. alignItems: 'center',
  169. justifyContent: 'center',
  170. fontSize: '11px',
  171. fontWeight: 'bold',
  172. cursor: 'pointer',
  173. transition: 'all 0.2s ease',
  174. zIndex: 10,
  175. }}
  176. onClick={(e) => {
  177. e.stopPropagation();
  178. if (data.onFocus) {
  179. data.onFocus();
  180. }
  181. }}
  182. onMouseEnter={(e) => {
  183. if (!data.isFocused) {
  184. e.currentTarget.style.background = '#d1d5db';
  185. }
  186. }}
  187. onMouseLeave={(e) => {
  188. if (!data.isFocused) {
  189. e.currentTarget.style.background = '#e5e7eb';
  190. }
  191. }}
  192. title={data.isFocused ? '取消聚焦' : '聚焦到此节点'}
  193. >
  194. 🎯
  195. </div>
  196. {/* 折叠/展开子节点按钮 - 右边第二个位置 */}
  197. {data.hasChildren && (
  198. <div
  199. style={{
  200. position: 'absolute',
  201. top: '6px',
  202. right: '30px',
  203. width: '20px',
  204. height: '20px',
  205. borderRadius: '50%',
  206. background: data.isCollapsed ? '#667eea' : '#e5e7eb',
  207. color: data.isCollapsed ? 'white' : '#6b7280',
  208. display: 'flex',
  209. alignItems: 'center',
  210. justifyContent: 'center',
  211. fontSize: '11px',
  212. fontWeight: 'bold',
  213. cursor: 'pointer',
  214. transition: 'all 0.2s ease',
  215. zIndex: 10,
  216. }}
  217. onClick={(e) => {
  218. e.stopPropagation();
  219. data.onToggleCollapse();
  220. }}
  221. title={data.isCollapsed ? '展开子节点' : '折叠子节点'}
  222. >
  223. {data.isCollapsed ? '+' : '−'}
  224. </div>
  225. )}
  226. {/* 卡片内容 */}
  227. <div>
  228. {/* 标题行 */}
  229. <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px', paddingLeft: '24px', paddingRight: data.hasChildren ? '54px' : '28px' }}>
  230. <div style={{ flex: 1 }}>
  231. <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '3px' }}>
  232. <div style={{
  233. fontSize: '13px',
  234. fontWeight: data.level === 0 ? '700' : '600',
  235. color: data.level === 0 ? '#6b21a8' : '#1f2937',
  236. lineHeight: '1.3',
  237. flex: 1,
  238. }}>
  239. {data.title}
  240. </div>
  241. {data.isSelected === false && (
  242. <div style={{
  243. fontSize: '9px',
  244. padding: '1px 4px',
  245. borderRadius: '3px',
  246. background: '#fee2e2',
  247. color: '#991b1b',
  248. fontWeight: '500',
  249. flexShrink: 0,
  250. }}>
  251. 未选中
  252. </div>
  253. )}
  254. </div>
  255. </div>
  256. </div>
  257. {/* 展开的详细信息 - 始终显示 */}
  258. <div style={{ fontSize: '11px', lineHeight: 1.4 }}>
  259. <div style={{ display: 'flex', gap: '4px', marginBottom: '6px', flexWrap: 'wrap' }}>
  260. <span style={{
  261. display: 'inline-block',
  262. padding: '1px 6px',
  263. borderRadius: '10px',
  264. background: '#eff6ff',
  265. color: '#3b82f6',
  266. fontSize: '10px',
  267. fontWeight: '500',
  268. }}>
  269. Lv.{data.level}
  270. </span>
  271. <span style={{
  272. display: 'inline-block',
  273. padding: '1px 6px',
  274. borderRadius: '10px',
  275. background: '#f0fdf4',
  276. color: '#16a34a',
  277. fontSize: '10px',
  278. fontWeight: '500',
  279. }}>
  280. {data.score}
  281. </span>
  282. {data.strategy && data.strategy !== 'root' && (
  283. <span style={{
  284. display: 'inline-block',
  285. padding: '1px 6px',
  286. borderRadius: '10px',
  287. background: '#fef3c7',
  288. color: '#92400e',
  289. fontSize: '10px',
  290. fontWeight: '500',
  291. }}>
  292. {data.strategy}
  293. </span>
  294. )}
  295. </div>
  296. {data.parent && (
  297. <div style={{ color: '#6b7280', fontSize: '10px', marginTop: '4px', paddingTop: '4px', borderTop: '1px solid #f3f4f6' }}>
  298. <strong>Parent:</strong> {data.parent}
  299. </div>
  300. )}
  301. {data.evaluationReason && (
  302. <div style={{
  303. marginTop: '6px',
  304. paddingTop: '6px',
  305. borderTop: '1px solid #f3f4f6',
  306. fontSize: '10px',
  307. color: '#6b7280',
  308. lineHeight: '1.5',
  309. }}>
  310. <strong style={{ color: '#4b5563' }}>评估:</strong>
  311. <div style={{ marginTop: '2px' }}>{data.evaluationReason}</div>
  312. </div>
  313. )}
  314. </div>
  315. </div>
  316. </div>
  317. <Handle
  318. type="source"
  319. position={sourcePosition || Position.Right}
  320. style={{ background: '#667eea', width: 8, height: 8 }}
  321. />
  322. </div>
  323. );
  324. }
  325. // 笔记节点组件 - 卡片样式,带轮播图
  326. function NoteNode({ id, data, sourcePosition, targetPosition }) {
  327. const [currentImageIndex, setCurrentImageIndex] = useState(0);
  328. const expanded = true;
  329. const hasImages = data.imageList && data.imageList.length > 0;
  330. const nextImage = (e) => {
  331. e.stopPropagation();
  332. if (hasImages) {
  333. setCurrentImageIndex((prev) => (prev + 1) % data.imageList.length);
  334. }
  335. };
  336. const prevImage = (e) => {
  337. e.stopPropagation();
  338. if (hasImages) {
  339. setCurrentImageIndex((prev) => (prev - 1 + data.imageList.length) % data.imageList.length);
  340. }
  341. };
  342. return (
  343. <div>
  344. <Handle
  345. type="target"
  346. position={targetPosition || Position.Left}
  347. style={{ background: '#ec4899', width: 8, height: 8 }}
  348. />
  349. <div
  350. style={{
  351. padding: '14px',
  352. borderRadius: '20px',
  353. border: data.isHighlighted ? '3px solid #ec4899' : '2px solid #fce7f3',
  354. background: data.isHighlighted ? '#eef2ff' : 'white',
  355. minWidth: '220px',
  356. maxWidth: '300px',
  357. boxShadow: data.isHighlighted ? '0 0 0 4px rgba(236, 72, 153, 0.25), 0 4px 16px rgba(236, 72, 153, 0.4)' : '0 4px 12px rgba(236, 72, 153, 0.15)',
  358. transition: 'all 0.3s ease',
  359. cursor: 'pointer',
  360. }}
  361. >
  362. {/* 笔记标题 */}
  363. <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: '8px' }}>
  364. <div style={{ flex: 1 }}>
  365. <div style={{
  366. fontSize: '13px',
  367. fontWeight: '600',
  368. color: '#831843',
  369. lineHeight: '1.4',
  370. marginBottom: '4px',
  371. }}>
  372. {data.title}
  373. </div>
  374. </div>
  375. </div>
  376. {/* 轮播图 */}
  377. {hasImages && (
  378. <div style={{
  379. position: 'relative',
  380. marginBottom: '8px',
  381. borderRadius: '12px',
  382. overflow: 'hidden',
  383. }}>
  384. <img
  385. src={data.imageList[currentImageIndex].image_url}
  386. alt={\`Image \${currentImageIndex + 1}\`}
  387. style={{
  388. width: '100%',
  389. height: '160px',
  390. objectFit: 'cover',
  391. display: 'block',
  392. }}
  393. onError={(e) => {
  394. e.target.style.display = 'none';
  395. }}
  396. />
  397. {data.imageList.length > 1 && (
  398. <>
  399. {/* 左右切换按钮 */}
  400. <button
  401. onClick={prevImage}
  402. style={{
  403. position: 'absolute',
  404. left: '4px',
  405. top: '50%',
  406. transform: 'translateY(-50%)',
  407. background: 'rgba(0, 0, 0, 0.5)',
  408. color: 'white',
  409. border: 'none',
  410. borderRadius: '50%',
  411. width: '24px',
  412. height: '24px',
  413. cursor: 'pointer',
  414. display: 'flex',
  415. alignItems: 'center',
  416. justifyContent: 'center',
  417. fontSize: '14px',
  418. }}
  419. >
  420. </button>
  421. <button
  422. onClick={nextImage}
  423. style={{
  424. position: 'absolute',
  425. right: '4px',
  426. top: '50%',
  427. transform: 'translateY(-50%)',
  428. background: 'rgba(0, 0, 0, 0.5)',
  429. color: 'white',
  430. border: 'none',
  431. borderRadius: '50%',
  432. width: '24px',
  433. height: '24px',
  434. cursor: 'pointer',
  435. display: 'flex',
  436. alignItems: 'center',
  437. justifyContent: 'center',
  438. fontSize: '14px',
  439. }}
  440. >
  441. </button>
  442. {/* 图片计数 */}
  443. <div style={{
  444. position: 'absolute',
  445. bottom: '4px',
  446. right: '4px',
  447. background: 'rgba(0, 0, 0, 0.6)',
  448. color: 'white',
  449. padding: '2px 6px',
  450. borderRadius: '10px',
  451. fontSize: '10px',
  452. }}>
  453. {currentImageIndex + 1}/{data.imageList.length}
  454. </div>
  455. </>
  456. )}
  457. </div>
  458. )}
  459. {/* 标签 */}
  460. <div style={{ display: 'flex', gap: '6px', marginBottom: '8px', flexWrap: 'wrap' }}>
  461. <span style={{
  462. display: 'inline-block',
  463. padding: '2px 8px',
  464. borderRadius: '12px',
  465. background: '#fff1f2',
  466. color: '#be123c',
  467. fontSize: '10px',
  468. fontWeight: '500',
  469. }}>
  470. {data.matchLevel}
  471. </span>
  472. <span style={{
  473. display: 'inline-block',
  474. padding: '2px 8px',
  475. borderRadius: '12px',
  476. background: '#fff7ed',
  477. color: '#c2410c',
  478. fontSize: '10px',
  479. fontWeight: '500',
  480. }}>
  481. Score: {data.score}
  482. </span>
  483. </div>
  484. {/* 描述 */}
  485. {expanded && data.description && (
  486. <div style={{
  487. fontSize: '11px',
  488. color: '#9f1239',
  489. lineHeight: '1.5',
  490. paddingTop: '8px',
  491. borderTop: '1px solid #fbcfe8',
  492. }}>
  493. {data.description}
  494. </div>
  495. )}
  496. {/* 评估理由 */}
  497. {expanded && data.evaluationReason && (
  498. <div style={{
  499. fontSize: '10px',
  500. color: '#831843',
  501. lineHeight: '1.5',
  502. paddingTop: '8px',
  503. marginTop: '8px',
  504. borderTop: '1px solid #fbcfe8',
  505. }}>
  506. <strong style={{ color: '#9f1239' }}>评估:</strong>
  507. <div style={{ marginTop: '2px' }}>{data.evaluationReason}</div>
  508. </div>
  509. )}
  510. </div>
  511. <Handle
  512. type="source"
  513. position={sourcePosition || Position.Right}
  514. style={{ background: '#ec4899', width: 8, height: 8 }}
  515. />
  516. </div>
  517. );
  518. }
  519. const nodeTypes = {
  520. query: QueryNode,
  521. note: NoteNode,
  522. };
  523. // 根据 score 获取颜色
  524. function getScoreColor(score) {
  525. if (score >= 0.7) return '#10b981'; // 绿色 - 高分
  526. if (score >= 0.4) return '#f59e0b'; // 橙色 - 中分
  527. return '#ef4444'; // 红色 - 低分
  528. }
  529. // 截断文本,保留头尾,中间显示省略号
  530. function truncateMiddle(text, maxLength = 20) {
  531. if (!text || text.length <= maxLength) return text;
  532. const headLength = Math.ceil(maxLength * 0.4);
  533. const tailLength = Math.floor(maxLength * 0.4);
  534. const head = text.substring(0, headLength);
  535. const tail = text.substring(text.length - tailLength);
  536. return \`\${head}...\${tail}\`;
  537. }
  538. // 根据策略获取颜色
  539. function getStrategyColor(strategy) {
  540. const strategyColors = {
  541. '初始分词': '#10b981',
  542. '调用sug': '#06b6d4',
  543. '同义改写': '#f59e0b',
  544. '加词': '#3b82f6',
  545. '抽象改写': '#8b5cf6',
  546. '基于部分匹配改进': '#ec4899',
  547. '结果分支-抽象改写': '#a855f7',
  548. '结果分支-同义改写': '#fb923c',
  549. // v6.1.2.8 新增策略
  550. '原始问题': '#6b21a8',
  551. '来自分词': '#10b981',
  552. '加词生成': '#ef4444',
  553. '建议词': '#06b6d4',
  554. '执行搜索': '#8b5cf6',
  555. };
  556. return strategyColors[strategy] || '#9ca3af';
  557. }
  558. // 树节点组件
  559. function TreeNode({ node, level, children, isCollapsed, onToggle, isSelected, onSelect }) {
  560. const hasChildren = children && children.length > 0;
  561. const score = node.data.score ? parseFloat(node.data.score) : 0;
  562. const strategy = node.data.strategy || '';
  563. const strategyColor = getStrategyColor(strategy);
  564. const nodeActualType = node.data.nodeType || node.type; // 获取实际节点类型
  565. return (
  566. <div style={{ marginLeft: level * 12 + 'px' }}>
  567. <div
  568. style={{
  569. padding: '6px 8px',
  570. borderRadius: '4px',
  571. cursor: 'pointer',
  572. background: 'transparent',
  573. border: isSelected ? '1px solid #3b82f6' : '1px solid transparent',
  574. display: 'flex',
  575. alignItems: 'center',
  576. gap: '6px',
  577. transition: 'all 0.2s ease',
  578. position: 'relative',
  579. overflow: 'visible',
  580. }}
  581. onMouseEnter={(e) => {
  582. if (!isSelected) e.currentTarget.style.background = '#f9fafb';
  583. }}
  584. onMouseLeave={(e) => {
  585. if (!isSelected) e.currentTarget.style.background = 'transparent';
  586. }}
  587. >
  588. {/* 策略类型竖线 */}
  589. <div style={{
  590. width: '3px',
  591. height: '20px',
  592. background: strategyColor,
  593. borderRadius: '2px',
  594. flexShrink: 0,
  595. position: 'relative',
  596. zIndex: 1,
  597. }} />
  598. {hasChildren && (
  599. <span
  600. style={{
  601. fontSize: '10px',
  602. color: '#6b7280',
  603. cursor: 'pointer',
  604. width: '16px',
  605. textAlign: 'center',
  606. position: 'relative',
  607. zIndex: 1,
  608. }}
  609. onClick={(e) => {
  610. e.stopPropagation();
  611. onToggle();
  612. }}
  613. >
  614. {isCollapsed ? '▶' : '▼'}
  615. </span>
  616. )}
  617. {!hasChildren && <span style={{ width: '16px', position: 'relative', zIndex: 1 }}></span>}
  618. <div
  619. style={{
  620. flex: 1,
  621. fontSize: '12px',
  622. color: '#374151',
  623. position: 'relative',
  624. zIndex: 1,
  625. minWidth: 0,
  626. display: 'flex',
  627. flexDirection: 'column',
  628. gap: '4px',
  629. }}
  630. onClick={onSelect}
  631. >
  632. <div style={{
  633. display: 'flex',
  634. alignItems: 'center',
  635. gap: '8px',
  636. }}>
  637. <div style={{
  638. fontWeight: level === 0 ? '600' : '400',
  639. maxWidth: '180px',
  640. flex: 1,
  641. minWidth: 0,
  642. color: (node.type === 'note' ? node.data.matchLevel === 'unsatisfied' : node.data.isSelected === false) ? '#ef4444' : '#374151',
  643. }}
  644. title={node.data.title || node.id}
  645. >
  646. {truncateMiddle(node.data.title || node.id, 18)}
  647. </div>
  648. {/* 分数显示 - 步骤和轮次节点不显示分数 */}
  649. {nodeActualType !== 'step' && nodeActualType !== 'round' && (
  650. <span style={{
  651. fontSize: '11px',
  652. color: '#6b7280',
  653. fontWeight: '500',
  654. flexShrink: 0,
  655. }}>
  656. {score.toFixed(2)}
  657. </span>
  658. )}
  659. </div>
  660. {/* 分数下划线 - 步骤和轮次节点不显示 */}
  661. {nodeActualType !== 'step' && nodeActualType !== 'round' && (
  662. <div style={{
  663. width: (score * 100) + '%',
  664. height: '2px',
  665. background: getScoreColor(score),
  666. borderRadius: '1px',
  667. }} />
  668. )}
  669. </div>
  670. </div>
  671. {hasChildren && !isCollapsed && (
  672. <div>
  673. {children}
  674. </div>
  675. )}
  676. </div>
  677. );
  678. }
  679. // 使用 dagre 自动布局
  680. function getLayoutedElements(nodes, edges, direction = 'LR') {
  681. console.log('🎯 Starting layout with dagre...');
  682. console.log('Input:', nodes.length, 'nodes,', edges.length, 'edges');
  683. // 检查 dagre 是否加载
  684. if (typeof window === 'undefined' || typeof window.dagre === 'undefined') {
  685. console.warn('⚠️ Dagre not loaded, using fallback layout');
  686. // 降级到简单布局
  687. const levelGroups = {};
  688. nodes.forEach(node => {
  689. const level = node.data.level || 0;
  690. if (!levelGroups[level]) levelGroups[level] = [];
  691. levelGroups[level].push(node);
  692. });
  693. Object.entries(levelGroups).forEach(([level, nodeList]) => {
  694. const x = parseInt(level) * 350;
  695. nodeList.forEach((node, index) => {
  696. node.position = { x, y: index * 150 };
  697. node.targetPosition = 'left';
  698. node.sourcePosition = 'right';
  699. });
  700. });
  701. return { nodes, edges };
  702. }
  703. try {
  704. const dagreGraph = new window.dagre.graphlib.Graph();
  705. dagreGraph.setDefaultEdgeLabel(() => ({}));
  706. const isHorizontal = direction === 'LR';
  707. dagreGraph.setGraph({
  708. rankdir: direction,
  709. nodesep: 120, // 垂直间距 - 增加以避免节点重叠
  710. ranksep: 280, // 水平间距 - 增加以容纳更宽的节点
  711. });
  712. // 添加节点 - 根据节点类型设置不同的尺寸
  713. nodes.forEach((node) => {
  714. let nodeWidth = 280;
  715. let nodeHeight = 180;
  716. // note 节点有轮播图,需要更大的空间
  717. if (node.type === 'note') {
  718. nodeWidth = 320;
  719. nodeHeight = 350; // 增加高度以容纳轮播图
  720. }
  721. dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
  722. });
  723. // 添加边
  724. edges.forEach((edge) => {
  725. dagreGraph.setEdge(edge.source, edge.target);
  726. });
  727. // 计算布局
  728. window.dagre.layout(dagreGraph);
  729. console.log('✅ Dagre layout completed');
  730. // 更新节点位置和 handle 位置
  731. nodes.forEach((node) => {
  732. const nodeWithPosition = dagreGraph.node(node.id);
  733. if (!nodeWithPosition) {
  734. console.warn('Node position not found for:', node.id);
  735. return;
  736. }
  737. node.targetPosition = isHorizontal ? 'left' : 'top';
  738. node.sourcePosition = isHorizontal ? 'right' : 'bottom';
  739. // 根据节点类型获取尺寸
  740. let nodeWidth = 280;
  741. let nodeHeight = 180;
  742. if (node.type === 'note') {
  743. nodeWidth = 320;
  744. nodeHeight = 350;
  745. }
  746. // 将 dagre 的中心点位置转换为 React Flow 的左上角位置
  747. node.position = {
  748. x: nodeWithPosition.x - nodeWidth / 2,
  749. y: nodeWithPosition.y - nodeHeight / 2,
  750. };
  751. });
  752. console.log('✅ Layout completed, sample node:', nodes[0]);
  753. return { nodes, edges };
  754. } catch (error) {
  755. console.error('❌ Error in dagre layout:', error);
  756. console.error('Error details:', error.message, error.stack);
  757. // 降级处理
  758. console.log('Using fallback layout...');
  759. const levelGroups = {};
  760. nodes.forEach(node => {
  761. const level = node.data.level || 0;
  762. if (!levelGroups[level]) levelGroups[level] = [];
  763. levelGroups[level].push(node);
  764. });
  765. Object.entries(levelGroups).forEach(([level, nodeList]) => {
  766. const x = parseInt(level) * 350;
  767. nodeList.forEach((node, index) => {
  768. node.position = { x, y: index * 150 };
  769. node.targetPosition = 'left';
  770. node.sourcePosition = 'right';
  771. });
  772. });
  773. return { nodes, edges };
  774. }
  775. }
  776. function transformData(data) {
  777. const nodes = [];
  778. const edges = [];
  779. const originalIdToCanvasId = {}; // 原始ID -> 画布ID的映射
  780. const canvasIdToNodeData = {}; // 避免重复创建相同的节点
  781. // 创建节点
  782. Object.entries(data.nodes).forEach(([originalId, node]) => {
  783. // 统一处理所有类型的节点
  784. const nodeType = node.type || 'query';
  785. // 直接使用originalId作为canvasId,避免冲突
  786. const canvasId = originalId;
  787. originalIdToCanvasId[originalId] = canvasId;
  788. // 如果这个 canvasId 还没有创建过节点,则创建
  789. if (!canvasIdToNodeData[canvasId]) {
  790. canvasIdToNodeData[canvasId] = true;
  791. // 根据节点类型创建不同的数据结构
  792. if (nodeType === 'note') {
  793. nodes.push({
  794. id: canvasId,
  795. originalId: originalId,
  796. type: 'note',
  797. data: {
  798. title: node.title || '帖子',
  799. matchLevel: node.match_level,
  800. score: node.relevance_score ? node.relevance_score.toFixed(2) : '0.00',
  801. description: node.desc || '',
  802. isSelected: node.is_selected !== undefined ? node.is_selected : true,
  803. imageList: node.image_list || [],
  804. noteUrl: node.note_url || '',
  805. evaluationReason: node.evaluation_reason || '',
  806. nodeType: 'note',
  807. },
  808. position: { x: 0, y: 0 },
  809. });
  810. } else {
  811. // query, seg, q, search, root 等节点
  812. let displayTitle = node.query || originalId;
  813. nodes.push({
  814. id: canvasId,
  815. originalId: originalId,
  816. type: 'query', // 使用 query 组件渲染所有非note节点
  817. data: {
  818. title: displayTitle,
  819. level: node.level || 0,
  820. score: node.relevance_score ? node.relevance_score.toFixed(2) : '0.00',
  821. strategy: node.strategy || '',
  822. parent: node.parent_query || '',
  823. isSelected: node.is_selected !== undefined ? node.is_selected : true,
  824. evaluationReason: node.evaluation_reason || '',
  825. nodeType: nodeType, // 传递实际节点类型用于样式
  826. searchCount: node.search_count, // search 节点特有
  827. totalPosts: node.total_posts, // search 节点特有
  828. },
  829. position: { x: 0, y: 0 },
  830. });
  831. }
  832. }
  833. });
  834. // 创建边 - 使用虚线样式,映射到画布ID
  835. data.edges.forEach((edge, index) => {
  836. const edgeColors = {
  837. '初始分词': '#10b981',
  838. '调用sug': '#06b6d4',
  839. '同义改写': '#f59e0b',
  840. '加词': '#3b82f6',
  841. '抽象改写': '#8b5cf6',
  842. '基于部分匹配改进': '#ec4899',
  843. '结果分支-抽象改写': '#a855f7',
  844. '结果分支-同义改写': '#fb923c',
  845. 'query_to_note': '#ec4899',
  846. };
  847. const color = edgeColors[edge.strategy] || edgeColors[edge.edge_type] || '#d1d5db';
  848. const isNoteEdge = edge.edge_type === 'query_to_note';
  849. edges.push({
  850. id: \`edge-\${index}\`,
  851. source: originalIdToCanvasId[edge.from], // 使用画布ID
  852. target: originalIdToCanvasId[edge.to], // 使用画布ID
  853. type: 'simplebezier', // 使用简单贝塞尔曲线
  854. animated: isNoteEdge,
  855. style: {
  856. stroke: color,
  857. strokeWidth: isNoteEdge ? 2.5 : 2,
  858. strokeDasharray: isNoteEdge ? '5,5' : '8,4',
  859. },
  860. markerEnd: {
  861. type: 'arrowclosed',
  862. color: color,
  863. width: 20,
  864. height: 20,
  865. },
  866. });
  867. });
  868. // 使用 dagre 自动计算布局 - 从左到右
  869. return getLayoutedElements(nodes, edges, 'LR');
  870. }
  871. function FlowContent() {
  872. const { nodes: initialNodes, edges: initialEdges } = useMemo(() => {
  873. console.log('🔍 Transforming data...');
  874. const result = transformData(data);
  875. console.log('✅ Transformed:', result.nodes.length, 'nodes,', result.edges.length, 'edges');
  876. return result;
  877. }, []);
  878. // 初始化:找出所有有子节点的节点,默认折叠(画布节点)
  879. const initialCollapsedNodes = useMemo(() => {
  880. const nodesWithChildren = new Set();
  881. initialEdges.forEach(edge => {
  882. nodesWithChildren.add(edge.source);
  883. });
  884. // 排除根节点(level 0),让根节点默认展开
  885. const rootNode = initialNodes.find(n => n.data.level === 0);
  886. if (rootNode) {
  887. nodesWithChildren.delete(rootNode.id);
  888. }
  889. return nodesWithChildren;
  890. }, [initialNodes, initialEdges]);
  891. // 树节点的折叠状态需要在树构建后初始化
  892. const [collapsedNodes, setCollapsedNodes] = useState(() => initialCollapsedNodes);
  893. const [collapsedTreeNodes, setCollapsedTreeNodes] = useState(new Set());
  894. const [selectedNodeId, setSelectedNodeId] = useState(null);
  895. const [hiddenNodes, setHiddenNodes] = useState(new Set()); // 用户手动隐藏的节点
  896. const [focusMode, setFocusMode] = useState(false); // 全局聚焦模式,默认关闭
  897. const [focusedNodeId, setFocusedNodeId] = useState(null); // 单独聚焦的节点ID
  898. // 获取 React Flow 实例以控制画布
  899. const { setCenter, fitView } = useReactFlow();
  900. // 获取某个节点的所有后代节点ID
  901. const getDescendants = useCallback((nodeId) => {
  902. const descendants = new Set();
  903. const queue = [nodeId];
  904. while (queue.length > 0) {
  905. const current = queue.shift();
  906. initialEdges.forEach(edge => {
  907. if (edge.source === current && !descendants.has(edge.target)) {
  908. descendants.add(edge.target);
  909. queue.push(edge.target);
  910. }
  911. });
  912. }
  913. return descendants;
  914. }, [initialEdges]);
  915. // 获取直接父节点
  916. const getDirectParents = useCallback((nodeId) => {
  917. const parents = [];
  918. initialEdges.forEach(edge => {
  919. if (edge.target === nodeId) {
  920. parents.push(edge.source);
  921. }
  922. });
  923. return parents;
  924. }, [initialEdges]);
  925. // 获取直接子节点
  926. const getDirectChildren = useCallback((nodeId) => {
  927. const children = [];
  928. initialEdges.forEach(edge => {
  929. if (edge.source === nodeId) {
  930. children.push(edge.target);
  931. }
  932. });
  933. return children;
  934. }, [initialEdges]);
  935. // 切换节点折叠状态
  936. const toggleNodeCollapse = useCallback((nodeId) => {
  937. setCollapsedNodes(prev => {
  938. const newSet = new Set(prev);
  939. const descendants = getDescendants(nodeId);
  940. if (newSet.has(nodeId)) {
  941. // 展开:移除此节点,但保持其他折叠的节点
  942. newSet.delete(nodeId);
  943. } else {
  944. // 折叠:添加此节点
  945. newSet.add(nodeId);
  946. }
  947. return newSet;
  948. });
  949. }, [getDescendants]);
  950. // 过滤可见的节点和边,并重新计算布局
  951. const { nodes, edges } = useMemo(() => {
  952. const nodesToHide = new Set();
  953. // 判断使用哪个节点ID进行聚焦:优先使用单独聚焦的节点,否则使用全局聚焦模式的选中节点
  954. const effectiveFocusNodeId = focusedNodeId || (focusMode ? selectedNodeId : null);
  955. // 聚焦模式:只显示聚焦节点、其父节点和直接子节点
  956. if (effectiveFocusNodeId) {
  957. const visibleInFocus = new Set([effectiveFocusNodeId]);
  958. // 添加所有父节点
  959. initialEdges.forEach(edge => {
  960. if (edge.target === effectiveFocusNodeId) {
  961. visibleInFocus.add(edge.source);
  962. }
  963. });
  964. // 添加所有直接子节点
  965. initialEdges.forEach(edge => {
  966. if (edge.source === effectiveFocusNodeId) {
  967. visibleInFocus.add(edge.target);
  968. }
  969. });
  970. // 隐藏不在聚焦范围内的节点
  971. initialNodes.forEach(node => {
  972. if (!visibleInFocus.has(node.id)) {
  973. nodesToHide.add(node.id);
  974. }
  975. });
  976. } else {
  977. // 非聚焦模式:使用原有的折叠逻辑
  978. // 收集所有被折叠节点的后代
  979. collapsedNodes.forEach(collapsedId => {
  980. const descendants = getDescendants(collapsedId);
  981. descendants.forEach(id => nodesToHide.add(id));
  982. });
  983. }
  984. // 添加用户手动隐藏的节点
  985. hiddenNodes.forEach(id => nodesToHide.add(id));
  986. const visibleNodes = initialNodes
  987. .filter(node => !nodesToHide.has(node.id))
  988. .map(node => ({
  989. ...node,
  990. data: {
  991. ...node.data,
  992. isCollapsed: collapsedNodes.has(node.id),
  993. hasChildren: initialEdges.some(e => e.source === node.id),
  994. onToggleCollapse: () => toggleNodeCollapse(node.id),
  995. onHideSelf: () => {
  996. setHiddenNodes(prev => {
  997. const newSet = new Set(prev);
  998. newSet.add(node.id);
  999. return newSet;
  1000. });
  1001. },
  1002. onFocus: () => {
  1003. // 切换聚焦状态
  1004. if (focusedNodeId === node.id) {
  1005. setFocusedNodeId(null); // 如果已经聚焦,则取消聚焦
  1006. } else {
  1007. // 先取消之前的聚焦,然后聚焦到当前节点
  1008. setFocusedNodeId(node.id);
  1009. // 延迟聚焦视图到该节点
  1010. setTimeout(() => {
  1011. fitView({
  1012. nodes: [{ id: node.id }],
  1013. duration: 800,
  1014. padding: 0.3,
  1015. });
  1016. }, 100);
  1017. }
  1018. },
  1019. isFocused: focusedNodeId === node.id,
  1020. isHighlighted: selectedNodeId === node.id,
  1021. }
  1022. }));
  1023. const visibleEdges = initialEdges.filter(
  1024. edge => !nodesToHide.has(edge.source) && !nodesToHide.has(edge.target)
  1025. );
  1026. // 重新计算布局 - 只对可见节点
  1027. if (typeof window !== 'undefined' && typeof window.dagre !== 'undefined') {
  1028. try {
  1029. const dagreGraph = new window.dagre.graphlib.Graph();
  1030. dagreGraph.setDefaultEdgeLabel(() => ({}));
  1031. dagreGraph.setGraph({
  1032. rankdir: 'LR',
  1033. nodesep: 120, // 垂直间距 - 增加以避免节点重叠
  1034. ranksep: 280, // 水平间距 - 增加以容纳更宽的节点
  1035. });
  1036. visibleNodes.forEach((node) => {
  1037. let nodeWidth = 280;
  1038. let nodeHeight = 180;
  1039. // note 节点有轮播图,需要更大的空间
  1040. if (node.type === 'note') {
  1041. nodeWidth = 320;
  1042. nodeHeight = 350;
  1043. }
  1044. dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
  1045. });
  1046. visibleEdges.forEach((edge) => {
  1047. dagreGraph.setEdge(edge.source, edge.target);
  1048. });
  1049. window.dagre.layout(dagreGraph);
  1050. visibleNodes.forEach((node) => {
  1051. const nodeWithPosition = dagreGraph.node(node.id);
  1052. if (nodeWithPosition) {
  1053. // 根据节点类型获取对应的尺寸
  1054. let nodeWidth = 280;
  1055. let nodeHeight = 180;
  1056. if (node.type === 'note') {
  1057. nodeWidth = 320;
  1058. nodeHeight = 350;
  1059. }
  1060. node.position = {
  1061. x: nodeWithPosition.x - nodeWidth / 2,
  1062. y: nodeWithPosition.y - nodeHeight / 2,
  1063. };
  1064. node.targetPosition = 'left';
  1065. node.sourcePosition = 'right';
  1066. }
  1067. });
  1068. console.log('✅ Dynamic layout recalculated for', visibleNodes.length, 'visible nodes');
  1069. } catch (error) {
  1070. console.error('❌ Error in dynamic layout:', error);
  1071. }
  1072. }
  1073. return { nodes: visibleNodes, edges: visibleEdges };
  1074. }, [initialNodes, initialEdges, collapsedNodes, hiddenNodes, focusMode, focusedNodeId, getDescendants, toggleNodeCollapse, selectedNodeId]);
  1075. // 构建树形结构 - 允许一个节点有多个父节点
  1076. const buildTree = useCallback(() => {
  1077. const nodeMap = new Map();
  1078. initialNodes.forEach(node => {
  1079. nodeMap.set(node.id, node);
  1080. });
  1081. // 为每个节点创建树节点的副本(允许多次出现)
  1082. const createTreeNode = (nodeId, pathKey) => {
  1083. const node = nodeMap.get(nodeId);
  1084. if (!node) return null;
  1085. return {
  1086. ...node,
  1087. treeKey: pathKey, // 唯一的树路径key,用于React key
  1088. children: []
  1089. };
  1090. };
  1091. // 构建父子关系映射:记录每个节点的所有父节点,去重边
  1092. const parentToChildren = new Map();
  1093. const childToParents = new Map();
  1094. initialEdges.forEach(edge => {
  1095. // 记录父->子关系(去重:同一个父节点到同一个子节点只记录一次)
  1096. if (!parentToChildren.has(edge.source)) {
  1097. parentToChildren.set(edge.source, []);
  1098. }
  1099. const children = parentToChildren.get(edge.source);
  1100. if (!children.includes(edge.target)) {
  1101. children.push(edge.target);
  1102. }
  1103. // 记录子->父关系(用于判断是否有多个父节点,也去重)
  1104. if (!childToParents.has(edge.target)) {
  1105. childToParents.set(edge.target, []);
  1106. }
  1107. const parents = childToParents.get(edge.target);
  1108. if (!parents.includes(edge.source)) {
  1109. parents.push(edge.source);
  1110. }
  1111. });
  1112. // 递归构建树
  1113. const buildSubtree = (nodeId, pathKey, visitedInPath) => {
  1114. // 避免循环引用:如果当前路径中已经访问过这个节点,跳过
  1115. if (visitedInPath.has(nodeId)) {
  1116. return null;
  1117. }
  1118. const treeNode = createTreeNode(nodeId, pathKey);
  1119. if (!treeNode) return null;
  1120. const newVisitedInPath = new Set(visitedInPath);
  1121. newVisitedInPath.add(nodeId);
  1122. const children = parentToChildren.get(nodeId) || [];
  1123. treeNode.children = children
  1124. .map((childId, index) => buildSubtree(childId, pathKey + '-' + childId + '-' + index, newVisitedInPath))
  1125. .filter(child => child !== null);
  1126. return treeNode;
  1127. };
  1128. // 找出所有根节点(没有入边的节点)
  1129. const hasParent = new Set();
  1130. initialEdges.forEach(edge => {
  1131. hasParent.add(edge.target);
  1132. });
  1133. const roots = [];
  1134. initialNodes.forEach((node, index) => {
  1135. if (!hasParent.has(node.id)) {
  1136. const treeNode = buildSubtree(node.id, 'root-' + node.id + '-' + index, new Set());
  1137. if (treeNode) roots.push(treeNode);
  1138. }
  1139. });
  1140. return roots;
  1141. }, [initialNodes, initialEdges]);
  1142. const treeRoots = useMemo(() => buildTree(), [buildTree]);
  1143. // 生成树形文本结构
  1144. const generateTreeText = useCallback(() => {
  1145. const lines = [];
  1146. // 递归生成树形文本
  1147. const traverse = (nodes, prefix = '', isLast = true, depth = 0) => {
  1148. nodes.forEach((node, index) => {
  1149. const isLastNode = index === nodes.length - 1;
  1150. const nodeData = initialNodes.find(n => n.id === node.id)?.data || {};
  1151. const nodeType = nodeData.nodeType || node.data?.nodeType || 'unknown';
  1152. const title = nodeData.title || node.data?.title || node.id;
  1153. // 优先从node.data获取score,然后从nodeData获取
  1154. let score = null;
  1155. if (node.data?.score !== undefined) {
  1156. score = node.data.score;
  1157. } else if (node.data?.relevance_score !== undefined) {
  1158. score = node.data.relevance_score;
  1159. } else if (nodeData.score !== undefined) {
  1160. score = nodeData.score;
  1161. } else if (nodeData.relevance_score !== undefined) {
  1162. score = nodeData.relevance_score;
  1163. }
  1164. const strategy = nodeData.strategy || node.data?.strategy || '';
  1165. // 构建当前行 - 确保score为数字且不是step/round节点时显示
  1166. const connector = isLastNode ? '└─' : '├─';
  1167. const scoreText = (nodeType !== 'step' && nodeType !== 'round' && typeof score === 'number') ?
  1168. \` (分数: \${score.toFixed(2)})\` : '';
  1169. const strategyText = strategy ? \` [\${strategy}]\` : '';
  1170. lines.push(\`\${prefix}\${connector} \${title}\${scoreText}\${strategyText}\`);
  1171. // 递归处理子节点
  1172. if (node.children && node.children.length > 0) {
  1173. const childPrefix = prefix + (isLastNode ? ' ' : '│ ');
  1174. traverse(node.children, childPrefix, isLastNode, depth + 1);
  1175. }
  1176. });
  1177. };
  1178. // 添加标题
  1179. const rootNode = initialNodes.find(n => n.data?.level === 0);
  1180. if (rootNode) {
  1181. lines.push(\`📊 查询扩展树形结构\`);
  1182. lines.push(\`原始问题: \${rootNode.data.title || rootNode.data.query}\`);
  1183. lines.push('');
  1184. }
  1185. traverse(treeRoots);
  1186. return lines.join('\\n');
  1187. }, [treeRoots, initialNodes]);
  1188. // 复制树形结构到剪贴板
  1189. const copyTreeToClipboard = useCallback(async () => {
  1190. try {
  1191. const treeText = generateTreeText();
  1192. await navigator.clipboard.writeText(treeText);
  1193. alert('✅ 树形结构已复制到剪贴板!');
  1194. } catch (err) {
  1195. console.error('复制失败:', err);
  1196. alert('❌ 复制失败,请手动复制');
  1197. }
  1198. }, [generateTreeText]);
  1199. // 初始化树节点折叠状态
  1200. useEffect(() => {
  1201. const getAllTreeKeys = (nodes) => {
  1202. const keys = new Set();
  1203. const traverse = (node) => {
  1204. if (node.children && node.children.length > 0) {
  1205. // 排除根节点
  1206. if (node.data.level !== 0) {
  1207. keys.add(node.treeKey);
  1208. }
  1209. node.children.forEach(traverse);
  1210. }
  1211. };
  1212. nodes.forEach(traverse);
  1213. return keys;
  1214. };
  1215. setCollapsedTreeNodes(getAllTreeKeys(treeRoots));
  1216. }, [treeRoots]);
  1217. const renderTree = useCallback((treeNodes, level = 0) => {
  1218. return treeNodes.map(node => {
  1219. // 使用 treeKey 来区分树中的不同实例
  1220. const isCollapsed = collapsedTreeNodes.has(node.treeKey);
  1221. const isSelected = selectedNodeId === node.id;
  1222. return (
  1223. <TreeNode
  1224. key={node.treeKey}
  1225. node={node}
  1226. level={level}
  1227. isCollapsed={isCollapsed}
  1228. isSelected={isSelected}
  1229. onToggle={() => {
  1230. setCollapsedTreeNodes(prev => {
  1231. const newSet = new Set(prev);
  1232. if (newSet.has(node.treeKey)) {
  1233. newSet.delete(node.treeKey);
  1234. } else {
  1235. newSet.add(node.treeKey);
  1236. }
  1237. return newSet;
  1238. });
  1239. }}
  1240. onSelect={() => {
  1241. const nodeId = node.id;
  1242. // 展开所有祖先节点
  1243. const ancestorIds = [nodeId];
  1244. const findAncestors = (id) => {
  1245. initialEdges.forEach(edge => {
  1246. if (edge.target === id && !ancestorIds.includes(edge.source)) {
  1247. ancestorIds.push(edge.source);
  1248. findAncestors(edge.source);
  1249. }
  1250. });
  1251. };
  1252. findAncestors(nodeId);
  1253. // 如果节点或其祖先被隐藏,先恢复它们
  1254. setHiddenNodes(prev => {
  1255. const newSet = new Set(prev);
  1256. ancestorIds.forEach(id => newSet.delete(id));
  1257. return newSet;
  1258. });
  1259. setSelectedNodeId(nodeId);
  1260. // 获取选中节点的直接子节点
  1261. const childrenIds = [];
  1262. initialEdges.forEach(edge => {
  1263. if (edge.source === nodeId) {
  1264. childrenIds.push(edge.target);
  1265. }
  1266. });
  1267. setCollapsedNodes(prev => {
  1268. const newSet = new Set(prev);
  1269. // 展开所有祖先节点
  1270. ancestorIds.forEach(id => newSet.delete(id));
  1271. // 展开选中节点本身
  1272. newSet.delete(nodeId);
  1273. // 展开选中节点的直接子节点
  1274. childrenIds.forEach(id => newSet.delete(id));
  1275. return newSet;
  1276. });
  1277. // 延迟聚焦,等待节点展开和布局重新计算
  1278. setTimeout(() => {
  1279. fitView({
  1280. nodes: [{ id: nodeId }],
  1281. duration: 800,
  1282. padding: 0.3,
  1283. });
  1284. }, 300);
  1285. }}
  1286. >
  1287. {node.children && node.children.length > 0 && renderTree(node.children, level + 1)}
  1288. </TreeNode>
  1289. );
  1290. });
  1291. }, [collapsedTreeNodes, selectedNodeId, nodes, setCenter, initialEdges, setCollapsedNodes, fitView]);
  1292. console.log('📊 Rendering with', nodes.length, 'visible nodes and', edges.length, 'visible edges');
  1293. if (nodes.length === 0) {
  1294. return (
  1295. <div style={{ padding: 50, color: 'red', fontSize: 20 }}>
  1296. ERROR: No nodes to display!
  1297. </div>
  1298. );
  1299. }
  1300. return (
  1301. <div style={{ width: '100vw', height: '100vh', background: '#f9fafb', display: 'flex', flexDirection: 'column' }}>
  1302. {/* 顶部面包屑导航栏 */}
  1303. <div style={{
  1304. minHeight: '48px',
  1305. maxHeight: '120px',
  1306. background: 'white',
  1307. borderBottom: '1px solid #e5e7eb',
  1308. display: 'flex',
  1309. alignItems: 'flex-start',
  1310. padding: '12px 24px',
  1311. zIndex: 1000,
  1312. boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)',
  1313. flexShrink: 0,
  1314. overflowY: 'auto',
  1315. }}>
  1316. <div style={{ width: '100%' }}>
  1317. {selectedNodeId ? (
  1318. <div style={{ fontSize: '12px', color: '#6b7280' }}>
  1319. {/* 面包屑导航 - 显示所有路径 */}
  1320. {(() => {
  1321. const selectedNode = nodes.find(n => n.id === selectedNodeId);
  1322. if (!selectedNode) return null;
  1323. // 找到所有从根节点到当前节点的路径
  1324. const findAllPaths = (targetId) => {
  1325. const paths = [];
  1326. const buildPath = (nodeId, currentPath) => {
  1327. const node = initialNodes.find(n => n.id === nodeId);
  1328. if (!node) return;
  1329. const newPath = [node, ...currentPath];
  1330. // 找到所有父节点
  1331. const parents = initialEdges.filter(e => e.target === nodeId).map(e => e.source);
  1332. if (parents.length === 0) {
  1333. // 到达根节点
  1334. paths.push(newPath);
  1335. } else {
  1336. // 递归处理所有父节点
  1337. parents.forEach(parentId => {
  1338. buildPath(parentId, newPath);
  1339. });
  1340. }
  1341. };
  1342. buildPath(targetId, []);
  1343. return paths;
  1344. };
  1345. const allPaths = findAllPaths(selectedNodeId);
  1346. // 去重:将路径转换为字符串进行比较
  1347. const uniquePaths = [];
  1348. const pathStrings = new Set();
  1349. allPaths.forEach(path => {
  1350. const pathString = path.map(n => n.id).join('->');
  1351. if (!pathStrings.has(pathString)) {
  1352. pathStrings.add(pathString);
  1353. uniquePaths.push(path);
  1354. }
  1355. });
  1356. return (
  1357. <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
  1358. {uniquePaths.map((path, pathIndex) => (
  1359. <div key={pathIndex} style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap' }}>
  1360. {pathIndex > 0 && <span style={{ color: '#d1d5db', marginRight: '4px' }}>或</span>}
  1361. {path.map((node, index) => {
  1362. // 获取节点的 score、strategy 和 isSelected
  1363. const nodeScore = node.data.score ? parseFloat(node.data.score) : 0;
  1364. const nodeStrategy = node.data.strategy || '';
  1365. const strategyColor = getStrategyColor(nodeStrategy);
  1366. const nodeIsSelected = node.type === 'note' ? node.data.matchLevel !== 'unsatisfied' : node.data.isSelected !== false;
  1367. const nodeActualType = node.data.nodeType || node.type; // 获取实际节点类型
  1368. return (
  1369. <React.Fragment key={node.id + '-' + index}>
  1370. <span
  1371. onClick={() => {
  1372. const nodeId = node.id;
  1373. // 找到所有祖先节点
  1374. const ancestorIds = [nodeId];
  1375. const findAncestors = (id) => {
  1376. initialEdges.forEach(edge => {
  1377. if (edge.target === id && !ancestorIds.includes(edge.source)) {
  1378. ancestorIds.push(edge.source);
  1379. findAncestors(edge.source);
  1380. }
  1381. });
  1382. };
  1383. findAncestors(nodeId);
  1384. // 如果节点或其祖先被隐藏,先恢复它们
  1385. setHiddenNodes(prev => {
  1386. const newSet = new Set(prev);
  1387. ancestorIds.forEach(id => newSet.delete(id));
  1388. return newSet;
  1389. });
  1390. // 展开目录树中到达该节点的路径
  1391. // 需要找到所有包含该节点的树路径的 treeKey,并展开它们的父节点
  1392. setCollapsedTreeNodes(prev => {
  1393. const newSet = new Set(prev);
  1394. // 清空所有折叠状态,让目录树完全展开到选中节点
  1395. // 这样可以确保选中节点在目录中可见
  1396. return new Set();
  1397. });
  1398. setSelectedNodeId(nodeId);
  1399. setTimeout(() => {
  1400. fitView({
  1401. nodes: [{ id: nodeId }],
  1402. duration: 800,
  1403. padding: 0.3,
  1404. });
  1405. }, 100);
  1406. }}
  1407. style={{
  1408. padding: '6px 8px',
  1409. borderRadius: '4px',
  1410. background: 'white',
  1411. border: index === path.length - 1 ? '2px solid #3b82f6' : '1px solid #d1d5db',
  1412. color: '#374151',
  1413. fontWeight: index === path.length - 1 ? '600' : '400',
  1414. width: '180px',
  1415. cursor: 'pointer',
  1416. transition: 'all 0.2s ease',
  1417. position: 'relative',
  1418. display: 'inline-flex',
  1419. flexDirection: 'column',
  1420. gap: '4px',
  1421. }}
  1422. onMouseEnter={(e) => {
  1423. e.currentTarget.style.opacity = '0.8';
  1424. }}
  1425. onMouseLeave={(e) => {
  1426. e.currentTarget.style.opacity = '1';
  1427. }}
  1428. title={\`\${node.data.title || node.id} (Score: \${nodeScore.toFixed(2)}, Strategy: \${nodeStrategy}, Selected: \${nodeIsSelected})\`}
  1429. >
  1430. {/* 上半部分:竖线 + 图标 + 文字 + 分数 */}
  1431. <div style={{
  1432. display: 'flex',
  1433. alignItems: 'center',
  1434. gap: '6px',
  1435. }}>
  1436. {/* 策略类型竖线 */}
  1437. <div style={{
  1438. width: '3px',
  1439. height: '16px',
  1440. background: strategyColor,
  1441. borderRadius: '2px',
  1442. flexShrink: 0,
  1443. }} />
  1444. {/* 节点文字 */}
  1445. <span style={{
  1446. flex: 1,
  1447. fontSize: '12px',
  1448. color: nodeIsSelected ? '#374151' : '#ef4444',
  1449. }}>
  1450. {truncateMiddle(node.data.title || node.id, 18)}
  1451. </span>
  1452. {/* 分数显示 - 步骤和轮次节点不显示分数 */}
  1453. {nodeActualType !== 'step' && nodeActualType !== 'round' && (
  1454. <span style={{
  1455. fontSize: '10px',
  1456. color: '#6b7280',
  1457. fontWeight: '500',
  1458. flexShrink: 0,
  1459. }}>
  1460. {nodeScore.toFixed(2)}
  1461. </span>
  1462. )}
  1463. </div>
  1464. {/* 分数下划线 - 步骤和轮次节点不显示 */}
  1465. {nodeActualType !== 'step' && nodeActualType !== 'round' && (
  1466. <div style={{
  1467. width: (nodeScore * 100) + '%',
  1468. height: '2px',
  1469. background: getScoreColor(nodeScore),
  1470. borderRadius: '1px',
  1471. marginLeft: '9px',
  1472. }} />
  1473. )}
  1474. </span>
  1475. {index < path.length - 1 && <span style={{ color: '#9ca3af' }}>›</span>}
  1476. </React.Fragment>
  1477. )})}
  1478. </div>
  1479. ))}
  1480. </div>
  1481. );
  1482. })()}
  1483. </div>
  1484. ) : (
  1485. <div style={{ fontSize: '13px', color: '#9ca3af', textAlign: 'center' }}>
  1486. 选择一个节点查看路径
  1487. </div>
  1488. )}
  1489. </div>
  1490. </div>
  1491. {/* 主内容区:目录 + 画布 */}
  1492. <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
  1493. {/* 左侧目录树 */}
  1494. <div style={{
  1495. width: '320px',
  1496. background: 'white',
  1497. borderRight: '1px solid #e5e7eb',
  1498. display: 'flex',
  1499. flexDirection: 'column',
  1500. flexShrink: 0,
  1501. }}>
  1502. <div style={{
  1503. padding: '12px 16px',
  1504. borderBottom: '1px solid #e5e7eb',
  1505. display: 'flex',
  1506. justifyContent: 'space-between',
  1507. alignItems: 'center',
  1508. }}>
  1509. <span style={{
  1510. fontWeight: '600',
  1511. fontSize: '14px',
  1512. color: '#111827',
  1513. }}>
  1514. 节点目录
  1515. </span>
  1516. <div style={{ display: 'flex', gap: '6px' }}>
  1517. <button
  1518. onClick={() => {
  1519. setCollapsedTreeNodes(new Set());
  1520. }}
  1521. style={{
  1522. fontSize: '11px',
  1523. padding: '4px 8px',
  1524. borderRadius: '4px',
  1525. border: '1px solid #d1d5db',
  1526. background: 'white',
  1527. color: '#6b7280',
  1528. cursor: 'pointer',
  1529. fontWeight: '500',
  1530. }}
  1531. title="展开全部节点"
  1532. >
  1533. 全部展开
  1534. </button>
  1535. <button
  1536. onClick={() => {
  1537. const getAllTreeKeys = (nodes) => {
  1538. const keys = new Set();
  1539. const traverse = (node) => {
  1540. if (node.children && node.children.length > 0) {
  1541. keys.add(node.treeKey);
  1542. node.children.forEach(traverse);
  1543. }
  1544. };
  1545. nodes.forEach(traverse);
  1546. return keys;
  1547. };
  1548. setCollapsedTreeNodes(getAllTreeKeys(treeRoots));
  1549. }}
  1550. style={{
  1551. fontSize: '11px',
  1552. padding: '4px 8px',
  1553. borderRadius: '4px',
  1554. border: '1px solid #d1d5db',
  1555. background: 'white',
  1556. color: '#6b7280',
  1557. cursor: 'pointer',
  1558. fontWeight: '500',
  1559. }}
  1560. title="折叠全部节点"
  1561. >
  1562. 全部折叠
  1563. </button>
  1564. <button
  1565. onClick={copyTreeToClipboard}
  1566. style={{
  1567. fontSize: '11px',
  1568. padding: '4px 8px',
  1569. borderRadius: '4px',
  1570. border: '1px solid #3b82f6',
  1571. background: '#3b82f6',
  1572. color: 'white',
  1573. cursor: 'pointer',
  1574. fontWeight: '500',
  1575. transition: 'all 0.2s',
  1576. }}
  1577. onMouseEnter={(e) => e.currentTarget.style.background = '#2563eb'}
  1578. onMouseLeave={(e) => e.currentTarget.style.background = '#3b82f6'}
  1579. title="复制树形结构为文本格式"
  1580. >
  1581. 📋 复制树形结构
  1582. </button>
  1583. </div>
  1584. </div>
  1585. <div style={{
  1586. flex: 1,
  1587. overflowX: 'auto',
  1588. overflowY: 'auto',
  1589. padding: '8px',
  1590. }}>
  1591. <div style={{ minWidth: 'fit-content' }}>
  1592. {renderTree(treeRoots)}
  1593. </div>
  1594. </div>
  1595. </div>
  1596. {/* 画布区域 */}
  1597. <div style={{ flex: 1, position: 'relative' }}>
  1598. {/* 右侧图例 */}
  1599. <div style={{
  1600. position: 'absolute',
  1601. top: '20px',
  1602. right: '20px',
  1603. background: 'white',
  1604. padding: '16px',
  1605. borderRadius: '12px',
  1606. boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
  1607. zIndex: 1000,
  1608. maxWidth: '260px',
  1609. border: '1px solid #e5e7eb',
  1610. }}>
  1611. <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
  1612. <h3 style={{ fontSize: '14px', fontWeight: '600', color: '#111827', margin: 0 }}>图例</h3>
  1613. <button
  1614. onClick={() => setFocusMode(!focusMode)}
  1615. style={{
  1616. fontSize: '11px',
  1617. padding: '4px 8px',
  1618. borderRadius: '4px',
  1619. border: '1px solid',
  1620. borderColor: focusMode ? '#3b82f6' : '#d1d5db',
  1621. background: focusMode ? '#3b82f6' : 'white',
  1622. color: focusMode ? 'white' : '#6b7280',
  1623. cursor: 'pointer',
  1624. fontWeight: '500',
  1625. }}
  1626. title={focusMode ? '关闭聚焦模式' : '开启聚焦模式'}
  1627. >
  1628. {focusMode ? '🎯 聚焦' : '📊 全图'}
  1629. </button>
  1630. </div>
  1631. <div style={{ fontSize: '12px' }}>
  1632. {/* 画布节点展开/折叠控制 */}
  1633. <div style={{ marginBottom: '12px', paddingBottom: '12px', borderBottom: '1px solid #f3f4f6' }}>
  1634. <div style={{ fontSize: '12px', fontWeight: '500', marginBottom: '8px', color: '#374151' }}>节点控制</div>
  1635. <div style={{ display: 'flex', gap: '6px' }}>
  1636. <button
  1637. onClick={() => {
  1638. setCollapsedNodes(new Set());
  1639. }}
  1640. style={{
  1641. fontSize: '11px',
  1642. padding: '4px 8px',
  1643. borderRadius: '4px',
  1644. border: '1px solid #d1d5db',
  1645. background: 'white',
  1646. color: '#6b7280',
  1647. cursor: 'pointer',
  1648. fontWeight: '500',
  1649. flex: 1,
  1650. }}
  1651. title="展开画布中所有节点的子节点"
  1652. >
  1653. 全部展开
  1654. </button>
  1655. <button
  1656. onClick={() => {
  1657. const allNodeIds = new Set(initialNodes.map(n => n.id));
  1658. setCollapsedNodes(allNodeIds);
  1659. }}
  1660. style={{
  1661. fontSize: '11px',
  1662. padding: '4px 8px',
  1663. borderRadius: '4px',
  1664. border: '1px solid #d1d5db',
  1665. background: 'white',
  1666. color: '#6b7280',
  1667. cursor: 'pointer',
  1668. fontWeight: '500',
  1669. flex: 1,
  1670. }}
  1671. title="折叠画布中所有节点的子节点"
  1672. >
  1673. 全部折叠
  1674. </button>
  1675. </div>
  1676. </div>
  1677. <div style={{ paddingTop: '12px', borderTop: '1px solid #f3f4f6' }}>
  1678. <div style={{ fontSize: '12px', fontWeight: '500', marginBottom: '8px', color: '#374151' }}>策略类型</div>
  1679. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1680. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#10b981', opacity: 0.7 }}></div>
  1681. <span style={{ color: '#6b7280', fontSize: '11px' }}>初始分词</span>
  1682. </div>
  1683. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1684. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#06b6d4', opacity: 0.7 }}></div>
  1685. <span style={{ color: '#6b7280', fontSize: '11px' }}>调用sug</span>
  1686. </div>
  1687. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1688. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#f59e0b', opacity: 0.7 }}></div>
  1689. <span style={{ color: '#6b7280', fontSize: '11px' }}>同义改写</span>
  1690. </div>
  1691. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1692. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#3b82f6', opacity: 0.7 }}></div>
  1693. <span style={{ color: '#6b7280', fontSize: '11px' }}>加词</span>
  1694. </div>
  1695. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1696. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#8b5cf6', opacity: 0.7 }}></div>
  1697. <span style={{ color: '#6b7280', fontSize: '11px' }}>抽象改写</span>
  1698. </div>
  1699. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1700. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#ec4899', opacity: 0.7 }}></div>
  1701. <span style={{ color: '#6b7280', fontSize: '11px' }}>基于部分匹配改进</span>
  1702. </div>
  1703. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1704. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#a855f7', opacity: 0.7 }}></div>
  1705. <span style={{ color: '#6b7280', fontSize: '11px' }}>结果分支-抽象改写</span>
  1706. </div>
  1707. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1708. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#fb923c', opacity: 0.7 }}></div>
  1709. <span style={{ color: '#6b7280', fontSize: '11px' }}>结果分支-同义改写</span>
  1710. </div>
  1711. </div>
  1712. <div style={{
  1713. marginTop: '12px',
  1714. paddingTop: '12px',
  1715. borderTop: '1px solid #f3f4f6',
  1716. fontSize: '11px',
  1717. color: '#9ca3af',
  1718. lineHeight: '1.5',
  1719. }}>
  1720. 💡 点击节点左上角 × 隐藏节点
  1721. </div>
  1722. {/* 隐藏节点列表 - 在图例内部 */}
  1723. {hiddenNodes.size > 0 && (
  1724. <div style={{
  1725. marginTop: '12px',
  1726. paddingTop: '12px',
  1727. borderTop: '1px solid #f3f4f6',
  1728. }}>
  1729. <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
  1730. <h4 style={{ fontSize: '12px', fontWeight: '600', color: '#111827' }}>已隐藏节点</h4>
  1731. <button
  1732. onClick={() => setHiddenNodes(new Set())}
  1733. style={{
  1734. fontSize: '10px',
  1735. color: '#3b82f6',
  1736. background: 'none',
  1737. border: 'none',
  1738. cursor: 'pointer',
  1739. textDecoration: 'underline',
  1740. }}
  1741. >
  1742. 全部恢复
  1743. </button>
  1744. </div>
  1745. <div style={{ fontSize: '12px', maxHeight: '200px', overflow: 'auto' }}>
  1746. {Array.from(hiddenNodes).map(nodeId => {
  1747. const node = initialNodes.find(n => n.id === nodeId);
  1748. if (!node) return null;
  1749. return (
  1750. <div
  1751. key={nodeId}
  1752. style={{
  1753. display: 'flex',
  1754. justifyContent: 'space-between',
  1755. alignItems: 'center',
  1756. padding: '6px 8px',
  1757. margin: '4px 0',
  1758. background: '#f9fafb',
  1759. borderRadius: '6px',
  1760. fontSize: '11px',
  1761. }}
  1762. >
  1763. <span
  1764. style={{
  1765. flex: 1,
  1766. overflow: 'hidden',
  1767. textOverflow: 'ellipsis',
  1768. whiteSpace: 'nowrap',
  1769. color: '#374151',
  1770. }}
  1771. title={node.data.title || nodeId}
  1772. >
  1773. {node.data.title || nodeId}
  1774. </span>
  1775. <button
  1776. onClick={() => {
  1777. setHiddenNodes(prev => {
  1778. const newSet = new Set(prev);
  1779. newSet.delete(nodeId);
  1780. return newSet;
  1781. });
  1782. }}
  1783. style={{
  1784. marginLeft: '8px',
  1785. fontSize: '10px',
  1786. color: '#10b981',
  1787. background: 'none',
  1788. border: 'none',
  1789. cursor: 'pointer',
  1790. flexShrink: 0,
  1791. }}
  1792. >
  1793. 恢复
  1794. </button>
  1795. </div>
  1796. );
  1797. })}
  1798. </div>
  1799. </div>
  1800. )}
  1801. </div>
  1802. </div>
  1803. {/* React Flow 画布 */}
  1804. <ReactFlow
  1805. nodes={nodes}
  1806. edges={edges}
  1807. nodeTypes={nodeTypes}
  1808. fitView
  1809. fitViewOptions={{ padding: 0.2, duration: 500 }}
  1810. minZoom={0.1}
  1811. maxZoom={1.5}
  1812. nodesDraggable={true}
  1813. nodesConnectable={false}
  1814. elementsSelectable={true}
  1815. defaultEdgeOptions={{
  1816. type: 'smoothstep',
  1817. }}
  1818. proOptions={{ hideAttribution: true }}
  1819. onNodeClick={(event, clickedNode) => {
  1820. setSelectedNodeId(clickedNode.id);
  1821. }}
  1822. >
  1823. <Controls style={{ bottom: '20px', left: 'auto', right: '20px' }} />
  1824. <Background variant="dots" gap={20} size={1} color="#e5e7eb" />
  1825. </ReactFlow>
  1826. </div>
  1827. </div>
  1828. </div>
  1829. );
  1830. }
  1831. function App() {
  1832. return (
  1833. <ReactFlowProvider>
  1834. <FlowContent />
  1835. </ReactFlowProvider>
  1836. );
  1837. }
  1838. const root = createRoot(document.getElementById('root'));
  1839. root.render(<App />);
  1840. `;
  1841. fs.writeFileSync(reactComponentPath, reactComponent);
  1842. // 使用 esbuild 打包
  1843. console.log('🎨 Building modern visualization...');
  1844. build({
  1845. entryPoints: [reactComponentPath],
  1846. bundle: true,
  1847. outfile: path.join(__dirname, 'bundle_v2.js'),
  1848. format: 'iife',
  1849. loader: {
  1850. '.css': 'css',
  1851. },
  1852. minify: false,
  1853. sourcemap: 'inline',
  1854. // 强制所有 React 引用指向同一个位置,避免多副本
  1855. alias: {
  1856. 'react': path.join(__dirname, 'node_modules/react'),
  1857. 'react-dom': path.join(__dirname, 'node_modules/react-dom'),
  1858. 'react/jsx-runtime': path.join(__dirname, 'node_modules/react/jsx-runtime'),
  1859. 'react/jsx-dev-runtime': path.join(__dirname, 'node_modules/react/jsx-dev-runtime'),
  1860. },
  1861. }).then(() => {
  1862. // 读取打包后的 JS
  1863. const bundleJs = fs.readFileSync(path.join(__dirname, 'bundle_v2.js'), 'utf-8');
  1864. // 读取 CSS
  1865. const cssPath = path.join(__dirname, 'node_modules/@xyflow/react/dist/style.css');
  1866. const css = fs.readFileSync(cssPath, 'utf-8');
  1867. // 生成最终 HTML
  1868. const html = `<!DOCTYPE html>
  1869. <html lang="zh-CN">
  1870. <head>
  1871. <meta charset="UTF-8">
  1872. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1873. <title>查询图可视化</title>
  1874. <link rel="preconnect" href="https://fonts.googleapis.com">
  1875. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  1876. <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
  1877. <script src="https://unpkg.com/dagre@0.8.5/dist/dagre.min.js"></script>
  1878. <script>
  1879. // 过滤特定的 React 警告
  1880. const originalError = console.error;
  1881. console.error = (...args) => {
  1882. if (typeof args[0] === 'string' && args[0].includes('Each child in a list should have a unique "key" prop')) {
  1883. return;
  1884. }
  1885. originalError.apply(console, args);
  1886. };
  1887. </script>
  1888. <style>
  1889. * {
  1890. margin: 0;
  1891. padding: 0;
  1892. box-sizing: border-box;
  1893. }
  1894. body {
  1895. font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  1896. overflow: hidden;
  1897. -webkit-font-smoothing: antialiased;
  1898. -moz-osx-font-smoothing: grayscale;
  1899. }
  1900. #root {
  1901. width: 100vw;
  1902. height: 100vh;
  1903. }
  1904. ${css}
  1905. /* 自定义样式覆盖 */
  1906. .react-flow__edge-path {
  1907. stroke-linecap: round;
  1908. }
  1909. .react-flow__controls {
  1910. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  1911. border: 1px solid #e5e7eb;
  1912. border-radius: 8px;
  1913. }
  1914. .react-flow__controls-button {
  1915. border: none;
  1916. border-bottom: 1px solid #e5e7eb;
  1917. }
  1918. .react-flow__controls-button:hover {
  1919. background: #f9fafb;
  1920. }
  1921. </style>
  1922. </head>
  1923. <body>
  1924. <div id="root"></div>
  1925. <script>${bundleJs}</script>
  1926. </body>
  1927. </html>`;
  1928. // 写入输出文件
  1929. fs.writeFileSync(outputFile, html);
  1930. // 清理临时文件
  1931. fs.unlinkSync(reactComponentPath);
  1932. fs.unlinkSync(path.join(__dirname, 'bundle_v2.js'));
  1933. console.log('✅ Visualization generated: ' + outputFile);
  1934. console.log('📊 Nodes: ' + Object.keys(data.nodes).length);
  1935. console.log('🔗 Edges: ' + data.edges.length);
  1936. }).catch(error => {
  1937. console.error('❌ Build error:', error);
  1938. process.exit(1);
  1939. });