index.js 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162
  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. {data.interact_info && (
  461. <div style={{
  462. display: 'flex',
  463. gap: '8px',
  464. marginBottom: '8px',
  465. flexWrap: 'wrap',
  466. fontSize: '11px',
  467. color: '#9f1239',
  468. }}>
  469. {data.interact_info.liked_count > 0 && (
  470. <span style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>
  471. ❤️ {data.interact_info.liked_count}
  472. </span>
  473. )}
  474. {data.interact_info.collected_count > 0 && (
  475. <span style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>
  476. ⭐ {data.interact_info.collected_count}
  477. </span>
  478. )}
  479. {data.interact_info.comment_count > 0 && (
  480. <span style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>
  481. 💬 {data.interact_info.comment_count}
  482. </span>
  483. )}
  484. {data.interact_info.shared_count > 0 && (
  485. <span style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>
  486. 🔗 {data.interact_info.shared_count}
  487. </span>
  488. )}
  489. </div>
  490. )}
  491. {/* 标签 */}
  492. {(data.matchLevel || data.score) && (
  493. <div style={{ display: 'flex', gap: '6px', marginBottom: '8px', flexWrap: 'wrap' }}>
  494. {data.matchLevel && (
  495. <span style={{
  496. display: 'inline-block',
  497. padding: '2px 8px',
  498. borderRadius: '12px',
  499. background: '#fff1f2',
  500. color: '#be123c',
  501. fontSize: '10px',
  502. fontWeight: '500',
  503. }}>
  504. {data.matchLevel}
  505. </span>
  506. )}
  507. {data.score && (
  508. <span style={{
  509. display: 'inline-block',
  510. padding: '2px 8px',
  511. borderRadius: '12px',
  512. background: '#fff7ed',
  513. color: '#c2410c',
  514. fontSize: '10px',
  515. fontWeight: '500',
  516. }}>
  517. Score: {data.score}
  518. </span>
  519. )}
  520. </div>
  521. )}
  522. {/* 描述 */}
  523. {expanded && data.description && (
  524. <div style={{
  525. fontSize: '11px',
  526. color: '#9f1239',
  527. lineHeight: '1.5',
  528. paddingTop: '8px',
  529. borderTop: '1px solid #fbcfe8',
  530. }}>
  531. {data.description}
  532. </div>
  533. )}
  534. {/* 评估理由 */}
  535. {expanded && data.evaluationReason && (
  536. <div style={{
  537. fontSize: '10px',
  538. color: '#831843',
  539. lineHeight: '1.5',
  540. paddingTop: '8px',
  541. marginTop: '8px',
  542. borderTop: '1px solid #fbcfe8',
  543. }}>
  544. <strong style={{ color: '#9f1239' }}>评估:</strong>
  545. <div style={{ marginTop: '2px' }}>{data.evaluationReason}</div>
  546. </div>
  547. )}
  548. </div>
  549. <Handle
  550. type="source"
  551. position={sourcePosition || Position.Right}
  552. style={{ background: '#ec4899', width: 8, height: 8 }}
  553. />
  554. </div>
  555. );
  556. }
  557. const nodeTypes = {
  558. query: QueryNode,
  559. note: NoteNode,
  560. };
  561. // 根据 score 获取颜色
  562. function getScoreColor(score) {
  563. if (score >= 0.7) return '#10b981'; // 绿色 - 高分
  564. if (score >= 0.4) return '#f59e0b'; // 橙色 - 中分
  565. return '#ef4444'; // 红色 - 低分
  566. }
  567. // 截断文本,保留头尾,中间显示省略号
  568. function truncateMiddle(text, maxLength = 20) {
  569. if (!text || text.length <= maxLength) return text;
  570. const headLength = Math.ceil(maxLength * 0.4);
  571. const tailLength = Math.floor(maxLength * 0.4);
  572. const head = text.substring(0, headLength);
  573. const tail = text.substring(text.length - tailLength);
  574. return \`\${head}...\${tail}\`;
  575. }
  576. // 根据策略获取颜色
  577. function getStrategyColor(strategy) {
  578. const strategyColors = {
  579. '初始分词': '#10b981',
  580. '调用sug': '#06b6d4',
  581. '同义改写': '#f59e0b',
  582. '加词': '#3b82f6',
  583. '抽象改写': '#8b5cf6',
  584. '基于部分匹配改进': '#ec4899',
  585. '结果分支-抽象改写': '#a855f7',
  586. '结果分支-同义改写': '#fb923c',
  587. // v6.1.2.8 新增策略
  588. '原始问题': '#6b21a8',
  589. '来自分词': '#10b981',
  590. '加词生成': '#ef4444',
  591. '建议词': '#06b6d4',
  592. '执行搜索': '#8b5cf6',
  593. };
  594. return strategyColors[strategy] || '#9ca3af';
  595. }
  596. // 树节点组件
  597. function TreeNode({ node, level, children, isCollapsed, onToggle, isSelected, onSelect }) {
  598. const hasChildren = children && children.length > 0;
  599. const score = node.data.score ? parseFloat(node.data.score) : 0;
  600. const strategy = node.data.strategy || '';
  601. const strategyColor = getStrategyColor(strategy);
  602. const nodeActualType = node.data.nodeType || node.type; // 获取实际节点类型
  603. return (
  604. <div style={{ marginLeft: level * 12 + 'px' }}>
  605. <div
  606. style={{
  607. padding: '6px 8px',
  608. borderRadius: '4px',
  609. cursor: 'pointer',
  610. background: 'transparent',
  611. border: isSelected ? '1px solid #3b82f6' : '1px solid transparent',
  612. display: 'flex',
  613. alignItems: 'center',
  614. gap: '6px',
  615. transition: 'all 0.2s ease',
  616. position: 'relative',
  617. overflow: 'visible',
  618. }}
  619. onMouseEnter={(e) => {
  620. if (!isSelected) e.currentTarget.style.background = '#f9fafb';
  621. }}
  622. onMouseLeave={(e) => {
  623. if (!isSelected) e.currentTarget.style.background = 'transparent';
  624. }}
  625. >
  626. {/* 策略类型竖线 */}
  627. <div style={{
  628. width: '3px',
  629. height: '20px',
  630. background: strategyColor,
  631. borderRadius: '2px',
  632. flexShrink: 0,
  633. position: 'relative',
  634. zIndex: 1,
  635. }} />
  636. {hasChildren && (
  637. <span
  638. style={{
  639. fontSize: '10px',
  640. color: '#6b7280',
  641. cursor: 'pointer',
  642. width: '16px',
  643. textAlign: 'center',
  644. position: 'relative',
  645. zIndex: 1,
  646. }}
  647. onClick={(e) => {
  648. e.stopPropagation();
  649. onToggle();
  650. }}
  651. >
  652. {isCollapsed ? '▶' : '▼'}
  653. </span>
  654. )}
  655. {!hasChildren && <span style={{ width: '16px', position: 'relative', zIndex: 1 }}></span>}
  656. <div
  657. style={{
  658. flex: 1,
  659. fontSize: '12px',
  660. color: '#374151',
  661. position: 'relative',
  662. zIndex: 1,
  663. minWidth: 0,
  664. display: 'flex',
  665. flexDirection: 'column',
  666. gap: '4px',
  667. }}
  668. onClick={onSelect}
  669. >
  670. <div style={{
  671. display: 'flex',
  672. alignItems: 'center',
  673. gap: '8px',
  674. }}>
  675. <div style={{
  676. fontWeight: level === 0 ? '600' : '400',
  677. maxWidth: '180px',
  678. flex: 1,
  679. minWidth: 0,
  680. color: (node.type === 'note' ? node.data.matchLevel === 'unsatisfied' : node.data.isSelected === false) ? '#ef4444' : '#374151',
  681. }}
  682. title={node.data.title || node.id}
  683. >
  684. {truncateMiddle(node.data.title || node.id, 18)}
  685. </div>
  686. {/* 分数显示 - 步骤和轮次节点不显示分数 */}
  687. {nodeActualType !== 'step' && nodeActualType !== 'round' && (
  688. <span style={{
  689. fontSize: '11px',
  690. color: '#6b7280',
  691. fontWeight: '500',
  692. flexShrink: 0,
  693. }}>
  694. {score.toFixed(2)}
  695. </span>
  696. )}
  697. </div>
  698. {/* 分数下划线 - 步骤和轮次节点不显示 */}
  699. {nodeActualType !== 'step' && nodeActualType !== 'round' && (
  700. <div style={{
  701. width: (score * 100) + '%',
  702. height: '2px',
  703. background: getScoreColor(score),
  704. borderRadius: '1px',
  705. }} />
  706. )}
  707. </div>
  708. </div>
  709. {hasChildren && !isCollapsed && (
  710. <div>
  711. {children}
  712. </div>
  713. )}
  714. </div>
  715. );
  716. }
  717. // 使用 dagre 自动布局
  718. function getLayoutedElements(nodes, edges, direction = 'LR') {
  719. console.log('🎯 Starting layout with dagre...');
  720. console.log('Input:', nodes.length, 'nodes,', edges.length, 'edges');
  721. // 检查 dagre 是否加载
  722. if (typeof window === 'undefined' || typeof window.dagre === 'undefined') {
  723. console.warn('⚠️ Dagre not loaded, using fallback layout');
  724. // 降级到简单布局
  725. const levelGroups = {};
  726. nodes.forEach(node => {
  727. const level = node.data.level || 0;
  728. if (!levelGroups[level]) levelGroups[level] = [];
  729. levelGroups[level].push(node);
  730. });
  731. Object.entries(levelGroups).forEach(([level, nodeList]) => {
  732. const x = parseInt(level) * 350;
  733. nodeList.forEach((node, index) => {
  734. node.position = { x, y: index * 150 };
  735. node.targetPosition = 'left';
  736. node.sourcePosition = 'right';
  737. });
  738. });
  739. return { nodes, edges };
  740. }
  741. try {
  742. const dagreGraph = new window.dagre.graphlib.Graph();
  743. dagreGraph.setDefaultEdgeLabel(() => ({}));
  744. const isHorizontal = direction === 'LR';
  745. dagreGraph.setGraph({
  746. rankdir: direction,
  747. nodesep: 120, // 垂直间距 - 增加以避免节点重叠
  748. ranksep: 280, // 水平间距 - 增加以容纳更宽的节点
  749. });
  750. // 添加节点 - 根据节点类型设置不同的尺寸
  751. nodes.forEach((node) => {
  752. let nodeWidth = 280;
  753. let nodeHeight = 180;
  754. // note 节点有轮播图,需要更大的空间
  755. if (node.type === 'note') {
  756. nodeWidth = 320;
  757. nodeHeight = 350; // 增加高度以容纳轮播图
  758. }
  759. dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
  760. });
  761. // 添加边
  762. edges.forEach((edge) => {
  763. dagreGraph.setEdge(edge.source, edge.target);
  764. });
  765. // 计算布局
  766. window.dagre.layout(dagreGraph);
  767. console.log('✅ Dagre layout completed');
  768. // 更新节点位置和 handle 位置
  769. nodes.forEach((node) => {
  770. const nodeWithPosition = dagreGraph.node(node.id);
  771. if (!nodeWithPosition) {
  772. console.warn('Node position not found for:', node.id);
  773. return;
  774. }
  775. node.targetPosition = isHorizontal ? 'left' : 'top';
  776. node.sourcePosition = isHorizontal ? 'right' : 'bottom';
  777. // 根据节点类型获取尺寸
  778. let nodeWidth = 280;
  779. let nodeHeight = 180;
  780. if (node.type === 'note') {
  781. nodeWidth = 320;
  782. nodeHeight = 350;
  783. }
  784. // 将 dagre 的中心点位置转换为 React Flow 的左上角位置
  785. node.position = {
  786. x: nodeWithPosition.x - nodeWidth / 2,
  787. y: nodeWithPosition.y - nodeHeight / 2,
  788. };
  789. });
  790. console.log('✅ Layout completed, sample node:', nodes[0]);
  791. return { nodes, edges };
  792. } catch (error) {
  793. console.error('❌ Error in dagre layout:', error);
  794. console.error('Error details:', error.message, error.stack);
  795. // 降级处理
  796. console.log('Using fallback layout...');
  797. const levelGroups = {};
  798. nodes.forEach(node => {
  799. const level = node.data.level || 0;
  800. if (!levelGroups[level]) levelGroups[level] = [];
  801. levelGroups[level].push(node);
  802. });
  803. Object.entries(levelGroups).forEach(([level, nodeList]) => {
  804. const x = parseInt(level) * 350;
  805. nodeList.forEach((node, index) => {
  806. node.position = { x, y: index * 150 };
  807. node.targetPosition = 'left';
  808. node.sourcePosition = 'right';
  809. });
  810. });
  811. return { nodes, edges };
  812. }
  813. }
  814. function transformData(data) {
  815. const nodes = [];
  816. const edges = [];
  817. const originalIdToCanvasId = {}; // 原始ID -> 画布ID的映射
  818. const canvasIdToNodeData = {}; // 避免重复创建相同的节点
  819. // 创建节点
  820. Object.entries(data.nodes).forEach(([originalId, node]) => {
  821. // 统一处理所有类型的节点
  822. const nodeType = node.type || 'query';
  823. // 直接使用originalId作为canvasId,避免冲突
  824. const canvasId = originalId;
  825. originalIdToCanvasId[originalId] = canvasId;
  826. // 如果这个 canvasId 还没有创建过节点,则创建
  827. if (!canvasIdToNodeData[canvasId]) {
  828. canvasIdToNodeData[canvasId] = true;
  829. // 根据节点类型创建不同的数据结构
  830. if (nodeType === 'note' || nodeType === 'post') {
  831. nodes.push({
  832. id: canvasId,
  833. originalId: originalId,
  834. type: 'note',
  835. data: {
  836. title: node.query || node.title || '帖子',
  837. matchLevel: node.match_level,
  838. score: node.relevance_score ? node.relevance_score.toFixed(2) : '0.00',
  839. description: node.body_text || node.desc || '',
  840. isSelected: node.is_selected !== undefined ? node.is_selected : true,
  841. imageList: node.image_list || [],
  842. noteUrl: node.note_url || '',
  843. evaluationReason: node.evaluation_reason || '',
  844. interact_info: node.interact_info || {},
  845. nodeType: nodeType,
  846. },
  847. position: { x: 0, y: 0 },
  848. });
  849. } else {
  850. // query, seg, q, search, root 等节点
  851. let displayTitle = node.query || originalId;
  852. nodes.push({
  853. id: canvasId,
  854. originalId: originalId,
  855. type: 'query', // 使用 query 组件渲染所有非note节点
  856. data: {
  857. title: displayTitle,
  858. level: node.level || 0,
  859. score: node.relevance_score ? node.relevance_score.toFixed(2) : '0.00',
  860. strategy: node.strategy || '',
  861. parent: node.parent_query || '',
  862. isSelected: node.is_selected !== undefined ? node.is_selected : true,
  863. evaluationReason: node.evaluation_reason || '',
  864. nodeType: nodeType, // 传递实际节点类型用于样式
  865. searchCount: node.search_count, // search 节点特有
  866. totalPosts: node.total_posts, // search 节点特有
  867. },
  868. position: { x: 0, y: 0 },
  869. });
  870. }
  871. }
  872. });
  873. // 创建边 - 使用虚线样式,映射到画布ID
  874. data.edges.forEach((edge, index) => {
  875. const edgeColors = {
  876. '初始分词': '#10b981',
  877. '调用sug': '#06b6d4',
  878. '同义改写': '#f59e0b',
  879. '加词': '#3b82f6',
  880. '抽象改写': '#8b5cf6',
  881. '基于部分匹配改进': '#ec4899',
  882. '结果分支-抽象改写': '#a855f7',
  883. '结果分支-同义改写': '#fb923c',
  884. 'query_to_note': '#ec4899',
  885. };
  886. const color = edgeColors[edge.strategy] || edgeColors[edge.edge_type] || '#d1d5db';
  887. const isNoteEdge = edge.edge_type === 'query_to_note';
  888. edges.push({
  889. id: \`edge-\${index}\`,
  890. source: originalIdToCanvasId[edge.from], // 使用画布ID
  891. target: originalIdToCanvasId[edge.to], // 使用画布ID
  892. type: 'simplebezier', // 使用简单贝塞尔曲线
  893. animated: isNoteEdge,
  894. style: {
  895. stroke: color,
  896. strokeWidth: isNoteEdge ? 2.5 : 2,
  897. strokeDasharray: isNoteEdge ? '5,5' : '8,4',
  898. },
  899. markerEnd: {
  900. type: 'arrowclosed',
  901. color: color,
  902. width: 20,
  903. height: 20,
  904. },
  905. });
  906. });
  907. // 使用 dagre 自动计算布局 - 从左到右
  908. return getLayoutedElements(nodes, edges, 'LR');
  909. }
  910. function FlowContent() {
  911. const { nodes: initialNodes, edges: initialEdges } = useMemo(() => {
  912. console.log('🔍 Transforming data...');
  913. const result = transformData(data);
  914. console.log('✅ Transformed:', result.nodes.length, 'nodes,', result.edges.length, 'edges');
  915. return result;
  916. }, []);
  917. // 初始化:找出所有有子节点的节点,默认折叠(画布节点)
  918. const initialCollapsedNodes = useMemo(() => {
  919. const nodesWithChildren = new Set();
  920. initialEdges.forEach(edge => {
  921. nodesWithChildren.add(edge.source);
  922. });
  923. // 排除根节点(level 0),让根节点默认展开
  924. const rootNode = initialNodes.find(n => n.data.level === 0);
  925. if (rootNode) {
  926. nodesWithChildren.delete(rootNode.id);
  927. }
  928. return nodesWithChildren;
  929. }, [initialNodes, initialEdges]);
  930. // 树节点的折叠状态需要在树构建后初始化
  931. const [collapsedNodes, setCollapsedNodes] = useState(() => initialCollapsedNodes);
  932. const [collapsedTreeNodes, setCollapsedTreeNodes] = useState(new Set());
  933. const [selectedNodeId, setSelectedNodeId] = useState(null);
  934. const [hiddenNodes, setHiddenNodes] = useState(new Set()); // 用户手动隐藏的节点
  935. const [focusMode, setFocusMode] = useState(false); // 全局聚焦模式,默认关闭
  936. const [focusedNodeId, setFocusedNodeId] = useState(null); // 单独聚焦的节点ID
  937. // 获取 React Flow 实例以控制画布
  938. const { setCenter, fitView } = useReactFlow();
  939. // 获取某个节点的所有后代节点ID
  940. const getDescendants = useCallback((nodeId) => {
  941. const descendants = new Set();
  942. const queue = [nodeId];
  943. while (queue.length > 0) {
  944. const current = queue.shift();
  945. initialEdges.forEach(edge => {
  946. if (edge.source === current && !descendants.has(edge.target)) {
  947. descendants.add(edge.target);
  948. queue.push(edge.target);
  949. }
  950. });
  951. }
  952. return descendants;
  953. }, [initialEdges]);
  954. // 获取直接父节点
  955. const getDirectParents = useCallback((nodeId) => {
  956. const parents = [];
  957. initialEdges.forEach(edge => {
  958. if (edge.target === nodeId) {
  959. parents.push(edge.source);
  960. }
  961. });
  962. return parents;
  963. }, [initialEdges]);
  964. // 获取直接子节点
  965. const getDirectChildren = useCallback((nodeId) => {
  966. const children = [];
  967. initialEdges.forEach(edge => {
  968. if (edge.source === nodeId) {
  969. children.push(edge.target);
  970. }
  971. });
  972. return children;
  973. }, [initialEdges]);
  974. // 切换节点折叠状态
  975. const toggleNodeCollapse = useCallback((nodeId) => {
  976. setCollapsedNodes(prev => {
  977. const newSet = new Set(prev);
  978. const descendants = getDescendants(nodeId);
  979. if (newSet.has(nodeId)) {
  980. // 展开:移除此节点,但保持其他折叠的节点
  981. newSet.delete(nodeId);
  982. } else {
  983. // 折叠:添加此节点
  984. newSet.add(nodeId);
  985. }
  986. return newSet;
  987. });
  988. }, [getDescendants]);
  989. // 过滤可见的节点和边,并重新计算布局
  990. const { nodes, edges } = useMemo(() => {
  991. const nodesToHide = new Set();
  992. // 判断使用哪个节点ID进行聚焦:优先使用单独聚焦的节点,否则使用全局聚焦模式的选中节点
  993. const effectiveFocusNodeId = focusedNodeId || (focusMode ? selectedNodeId : null);
  994. // 聚焦模式:只显示聚焦节点、其父节点和直接子节点
  995. if (effectiveFocusNodeId) {
  996. const visibleInFocus = new Set([effectiveFocusNodeId]);
  997. // 添加所有父节点
  998. initialEdges.forEach(edge => {
  999. if (edge.target === effectiveFocusNodeId) {
  1000. visibleInFocus.add(edge.source);
  1001. }
  1002. });
  1003. // 添加所有直接子节点
  1004. initialEdges.forEach(edge => {
  1005. if (edge.source === effectiveFocusNodeId) {
  1006. visibleInFocus.add(edge.target);
  1007. }
  1008. });
  1009. // 隐藏不在聚焦范围内的节点
  1010. initialNodes.forEach(node => {
  1011. if (!visibleInFocus.has(node.id)) {
  1012. nodesToHide.add(node.id);
  1013. }
  1014. });
  1015. } else {
  1016. // 非聚焦模式:使用原有的折叠逻辑
  1017. // 收集所有被折叠节点的后代
  1018. collapsedNodes.forEach(collapsedId => {
  1019. const descendants = getDescendants(collapsedId);
  1020. descendants.forEach(id => nodesToHide.add(id));
  1021. });
  1022. }
  1023. // 添加用户手动隐藏的节点
  1024. hiddenNodes.forEach(id => nodesToHide.add(id));
  1025. const visibleNodes = initialNodes
  1026. .filter(node => !nodesToHide.has(node.id))
  1027. .map(node => ({
  1028. ...node,
  1029. data: {
  1030. ...node.data,
  1031. isCollapsed: collapsedNodes.has(node.id),
  1032. hasChildren: initialEdges.some(e => e.source === node.id),
  1033. onToggleCollapse: () => toggleNodeCollapse(node.id),
  1034. onHideSelf: () => {
  1035. setHiddenNodes(prev => {
  1036. const newSet = new Set(prev);
  1037. newSet.add(node.id);
  1038. return newSet;
  1039. });
  1040. },
  1041. onFocus: () => {
  1042. // 切换聚焦状态
  1043. if (focusedNodeId === node.id) {
  1044. setFocusedNodeId(null); // 如果已经聚焦,则取消聚焦
  1045. } else {
  1046. // 先取消之前的聚焦,然后聚焦到当前节点
  1047. setFocusedNodeId(node.id);
  1048. // 延迟聚焦视图到该节点
  1049. setTimeout(() => {
  1050. fitView({
  1051. nodes: [{ id: node.id }],
  1052. duration: 800,
  1053. padding: 0.3,
  1054. });
  1055. }, 100);
  1056. }
  1057. },
  1058. isFocused: focusedNodeId === node.id,
  1059. isHighlighted: selectedNodeId === node.id,
  1060. }
  1061. }));
  1062. const visibleEdges = initialEdges.filter(
  1063. edge => !nodesToHide.has(edge.source) && !nodesToHide.has(edge.target)
  1064. );
  1065. // 重新计算布局 - 只对可见节点
  1066. if (typeof window !== 'undefined' && typeof window.dagre !== 'undefined') {
  1067. try {
  1068. const dagreGraph = new window.dagre.graphlib.Graph();
  1069. dagreGraph.setDefaultEdgeLabel(() => ({}));
  1070. dagreGraph.setGraph({
  1071. rankdir: 'LR',
  1072. nodesep: 120, // 垂直间距 - 增加以避免节点重叠
  1073. ranksep: 280, // 水平间距 - 增加以容纳更宽的节点
  1074. });
  1075. visibleNodes.forEach((node) => {
  1076. let nodeWidth = 280;
  1077. let nodeHeight = 180;
  1078. // note 节点有轮播图,需要更大的空间
  1079. if (node.type === 'note') {
  1080. nodeWidth = 320;
  1081. nodeHeight = 350;
  1082. }
  1083. dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
  1084. });
  1085. visibleEdges.forEach((edge) => {
  1086. dagreGraph.setEdge(edge.source, edge.target);
  1087. });
  1088. window.dagre.layout(dagreGraph);
  1089. visibleNodes.forEach((node) => {
  1090. const nodeWithPosition = dagreGraph.node(node.id);
  1091. if (nodeWithPosition) {
  1092. // 根据节点类型获取对应的尺寸
  1093. let nodeWidth = 280;
  1094. let nodeHeight = 180;
  1095. if (node.type === 'note') {
  1096. nodeWidth = 320;
  1097. nodeHeight = 350;
  1098. }
  1099. node.position = {
  1100. x: nodeWithPosition.x - nodeWidth / 2,
  1101. y: nodeWithPosition.y - nodeHeight / 2,
  1102. };
  1103. node.targetPosition = 'left';
  1104. node.sourcePosition = 'right';
  1105. }
  1106. });
  1107. console.log('✅ Dynamic layout recalculated for', visibleNodes.length, 'visible nodes');
  1108. } catch (error) {
  1109. console.error('❌ Error in dynamic layout:', error);
  1110. }
  1111. }
  1112. return { nodes: visibleNodes, edges: visibleEdges };
  1113. }, [initialNodes, initialEdges, collapsedNodes, hiddenNodes, focusMode, focusedNodeId, getDescendants, toggleNodeCollapse, selectedNodeId]);
  1114. // 构建树形结构 - 允许一个节点有多个父节点
  1115. const buildTree = useCallback(() => {
  1116. const nodeMap = new Map();
  1117. initialNodes.forEach(node => {
  1118. nodeMap.set(node.id, node);
  1119. });
  1120. // 为每个节点创建树节点的副本(允许多次出现)
  1121. const createTreeNode = (nodeId, pathKey) => {
  1122. const node = nodeMap.get(nodeId);
  1123. if (!node) return null;
  1124. return {
  1125. ...node,
  1126. treeKey: pathKey, // 唯一的树路径key,用于React key
  1127. children: []
  1128. };
  1129. };
  1130. // 构建父子关系映射:记录每个节点的所有父节点,去重边
  1131. const parentToChildren = new Map();
  1132. const childToParents = new Map();
  1133. initialEdges.forEach(edge => {
  1134. // 记录父->子关系(去重:同一个父节点到同一个子节点只记录一次)
  1135. if (!parentToChildren.has(edge.source)) {
  1136. parentToChildren.set(edge.source, []);
  1137. }
  1138. const children = parentToChildren.get(edge.source);
  1139. if (!children.includes(edge.target)) {
  1140. children.push(edge.target);
  1141. }
  1142. // 记录子->父关系(用于判断是否有多个父节点,也去重)
  1143. if (!childToParents.has(edge.target)) {
  1144. childToParents.set(edge.target, []);
  1145. }
  1146. const parents = childToParents.get(edge.target);
  1147. if (!parents.includes(edge.source)) {
  1148. parents.push(edge.source);
  1149. }
  1150. });
  1151. // 递归构建树
  1152. const buildSubtree = (nodeId, pathKey, visitedInPath) => {
  1153. // 避免循环引用:如果当前路径中已经访问过这个节点,跳过
  1154. if (visitedInPath.has(nodeId)) {
  1155. return null;
  1156. }
  1157. const treeNode = createTreeNode(nodeId, pathKey);
  1158. if (!treeNode) return null;
  1159. const newVisitedInPath = new Set(visitedInPath);
  1160. newVisitedInPath.add(nodeId);
  1161. const children = parentToChildren.get(nodeId) || [];
  1162. treeNode.children = children
  1163. .map((childId, index) => buildSubtree(childId, pathKey + '-' + childId + '-' + index, newVisitedInPath))
  1164. .filter(child => child !== null);
  1165. return treeNode;
  1166. };
  1167. // 找出所有根节点(没有入边的节点)
  1168. const hasParent = new Set();
  1169. initialEdges.forEach(edge => {
  1170. hasParent.add(edge.target);
  1171. });
  1172. const roots = [];
  1173. initialNodes.forEach((node, index) => {
  1174. if (!hasParent.has(node.id)) {
  1175. const treeNode = buildSubtree(node.id, 'root-' + node.id + '-' + index, new Set());
  1176. if (treeNode) roots.push(treeNode);
  1177. }
  1178. });
  1179. return roots;
  1180. }, [initialNodes, initialEdges]);
  1181. const treeRoots = useMemo(() => buildTree(), [buildTree]);
  1182. // 生成树形文本结构
  1183. const generateTreeText = useCallback(() => {
  1184. const lines = [];
  1185. // 递归生成树形文本
  1186. const traverse = (nodes, prefix = '', isLast = true, depth = 0) => {
  1187. nodes.forEach((node, index) => {
  1188. const isLastNode = index === nodes.length - 1;
  1189. const nodeData = initialNodes.find(n => n.id === node.id)?.data || {};
  1190. const nodeType = nodeData.nodeType || node.data?.nodeType || 'unknown';
  1191. const title = nodeData.title || node.data?.title || node.id;
  1192. // 优先从node.data获取score,然后从nodeData获取
  1193. let score = null;
  1194. if (node.data?.score !== undefined && node.data?.score !== null) {
  1195. score = node.data.score;
  1196. } else if (node.data?.relevance_score !== undefined && node.data?.relevance_score !== null) {
  1197. score = node.data.relevance_score;
  1198. } else if (nodeData.score !== undefined && nodeData.score !== null) {
  1199. score = nodeData.score;
  1200. } else if (nodeData.relevance_score !== undefined && nodeData.relevance_score !== null) {
  1201. score = nodeData.relevance_score;
  1202. }
  1203. const strategy = nodeData.strategy || node.data?.strategy || '';
  1204. // 构建当前行 - score可能是数字或字符串,step/round节点不显示分数
  1205. const connector = isLastNode ? '└─' : '├─';
  1206. let scoreText = '';
  1207. if (nodeType !== 'step' && nodeType !== 'round' && score !== null && score !== undefined) {
  1208. // score可能已经是字符串格式(如 "0.05"),也可能是数字
  1209. const scoreStr = typeof score === 'number' ? score.toFixed(2) : score;
  1210. scoreText = \` (分数: \${scoreStr})\`;
  1211. }
  1212. const strategyText = strategy ? \` [\${strategy}]\` : '';
  1213. lines.push(\`\${prefix}\${connector} \${title}\${scoreText}\${strategyText}\`);
  1214. // 递归处理子节点
  1215. if (node.children && node.children.length > 0) {
  1216. const childPrefix = prefix + (isLastNode ? ' ' : '│ ');
  1217. traverse(node.children, childPrefix, isLastNode, depth + 1);
  1218. }
  1219. });
  1220. };
  1221. // 添加标题
  1222. const rootNode = initialNodes.find(n => n.data?.level === 0);
  1223. if (rootNode) {
  1224. lines.push(\`📊 查询扩展树形结构\`);
  1225. lines.push(\`原始问题: \${rootNode.data.title || rootNode.data.query}\`);
  1226. lines.push('');
  1227. }
  1228. traverse(treeRoots);
  1229. return lines.join('\\n');
  1230. }, [treeRoots, initialNodes]);
  1231. // 复制树形结构到剪贴板
  1232. const copyTreeToClipboard = useCallback(async () => {
  1233. try {
  1234. const treeText = generateTreeText();
  1235. await navigator.clipboard.writeText(treeText);
  1236. alert('✅ 树形结构已复制到剪贴板!');
  1237. } catch (err) {
  1238. console.error('复制失败:', err);
  1239. alert('❌ 复制失败,请手动复制');
  1240. }
  1241. }, [generateTreeText]);
  1242. // 初始化树节点折叠状态
  1243. useEffect(() => {
  1244. const getAllTreeKeys = (nodes) => {
  1245. const keys = new Set();
  1246. const traverse = (node) => {
  1247. if (node.children && node.children.length > 0) {
  1248. // 排除根节点
  1249. if (node.data.level !== 0) {
  1250. keys.add(node.treeKey);
  1251. }
  1252. node.children.forEach(traverse);
  1253. }
  1254. };
  1255. nodes.forEach(traverse);
  1256. return keys;
  1257. };
  1258. setCollapsedTreeNodes(getAllTreeKeys(treeRoots));
  1259. }, [treeRoots]);
  1260. const renderTree = useCallback((treeNodes, level = 0) => {
  1261. return treeNodes.map(node => {
  1262. // 使用 treeKey 来区分树中的不同实例
  1263. const isCollapsed = collapsedTreeNodes.has(node.treeKey);
  1264. const isSelected = selectedNodeId === node.id;
  1265. return (
  1266. <TreeNode
  1267. key={node.treeKey}
  1268. node={node}
  1269. level={level}
  1270. isCollapsed={isCollapsed}
  1271. isSelected={isSelected}
  1272. onToggle={() => {
  1273. setCollapsedTreeNodes(prev => {
  1274. const newSet = new Set(prev);
  1275. if (newSet.has(node.treeKey)) {
  1276. newSet.delete(node.treeKey);
  1277. } else {
  1278. newSet.add(node.treeKey);
  1279. }
  1280. return newSet;
  1281. });
  1282. }}
  1283. onSelect={() => {
  1284. const nodeId = node.id;
  1285. // 展开所有祖先节点
  1286. const ancestorIds = [nodeId];
  1287. const findAncestors = (id) => {
  1288. initialEdges.forEach(edge => {
  1289. if (edge.target === id && !ancestorIds.includes(edge.source)) {
  1290. ancestorIds.push(edge.source);
  1291. findAncestors(edge.source);
  1292. }
  1293. });
  1294. };
  1295. findAncestors(nodeId);
  1296. // 如果节点或其祖先被隐藏,先恢复它们
  1297. setHiddenNodes(prev => {
  1298. const newSet = new Set(prev);
  1299. ancestorIds.forEach(id => newSet.delete(id));
  1300. return newSet;
  1301. });
  1302. setSelectedNodeId(nodeId);
  1303. // 获取选中节点的直接子节点
  1304. const childrenIds = [];
  1305. initialEdges.forEach(edge => {
  1306. if (edge.source === nodeId) {
  1307. childrenIds.push(edge.target);
  1308. }
  1309. });
  1310. setCollapsedNodes(prev => {
  1311. const newSet = new Set(prev);
  1312. // 展开所有祖先节点
  1313. ancestorIds.forEach(id => newSet.delete(id));
  1314. // 展开选中节点本身
  1315. newSet.delete(nodeId);
  1316. // 展开选中节点的直接子节点
  1317. childrenIds.forEach(id => newSet.delete(id));
  1318. return newSet;
  1319. });
  1320. // 延迟聚焦,等待节点展开和布局重新计算
  1321. setTimeout(() => {
  1322. fitView({
  1323. nodes: [{ id: nodeId }],
  1324. duration: 800,
  1325. padding: 0.3,
  1326. });
  1327. }, 300);
  1328. }}
  1329. >
  1330. {node.children && node.children.length > 0 && renderTree(node.children, level + 1)}
  1331. </TreeNode>
  1332. );
  1333. });
  1334. }, [collapsedTreeNodes, selectedNodeId, nodes, setCenter, initialEdges, setCollapsedNodes, fitView]);
  1335. console.log('📊 Rendering with', nodes.length, 'visible nodes and', edges.length, 'visible edges');
  1336. if (nodes.length === 0) {
  1337. return (
  1338. <div style={{ padding: 50, color: 'red', fontSize: 20 }}>
  1339. ERROR: No nodes to display!
  1340. </div>
  1341. );
  1342. }
  1343. return (
  1344. <div style={{ width: '100vw', height: '100vh', background: '#f9fafb', display: 'flex', flexDirection: 'column' }}>
  1345. {/* 顶部面包屑导航栏 */}
  1346. <div style={{
  1347. minHeight: '48px',
  1348. maxHeight: '120px',
  1349. background: 'white',
  1350. borderBottom: '1px solid #e5e7eb',
  1351. display: 'flex',
  1352. alignItems: 'flex-start',
  1353. padding: '12px 24px',
  1354. zIndex: 1000,
  1355. boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)',
  1356. flexShrink: 0,
  1357. overflowY: 'auto',
  1358. }}>
  1359. <div style={{ width: '100%' }}>
  1360. {selectedNodeId ? (
  1361. <div style={{ fontSize: '12px', color: '#6b7280' }}>
  1362. {/* 面包屑导航 - 显示所有路径 */}
  1363. {(() => {
  1364. const selectedNode = nodes.find(n => n.id === selectedNodeId);
  1365. if (!selectedNode) return null;
  1366. // 找到所有从根节点到当前节点的路径
  1367. const findAllPaths = (targetId) => {
  1368. const paths = [];
  1369. const buildPath = (nodeId, currentPath) => {
  1370. const node = initialNodes.find(n => n.id === nodeId);
  1371. if (!node) return;
  1372. const newPath = [node, ...currentPath];
  1373. // 找到所有父节点
  1374. const parents = initialEdges.filter(e => e.target === nodeId).map(e => e.source);
  1375. if (parents.length === 0) {
  1376. // 到达根节点
  1377. paths.push(newPath);
  1378. } else {
  1379. // 递归处理所有父节点
  1380. parents.forEach(parentId => {
  1381. buildPath(parentId, newPath);
  1382. });
  1383. }
  1384. };
  1385. buildPath(targetId, []);
  1386. return paths;
  1387. };
  1388. const allPaths = findAllPaths(selectedNodeId);
  1389. // 去重:将路径转换为字符串进行比较
  1390. const uniquePaths = [];
  1391. const pathStrings = new Set();
  1392. allPaths.forEach(path => {
  1393. const pathString = path.map(n => n.id).join('->');
  1394. if (!pathStrings.has(pathString)) {
  1395. pathStrings.add(pathString);
  1396. uniquePaths.push(path);
  1397. }
  1398. });
  1399. return (
  1400. <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
  1401. {uniquePaths.map((path, pathIndex) => (
  1402. <div key={pathIndex} style={{ display: 'flex', alignItems: 'center', gap: '6px', flexWrap: 'wrap' }}>
  1403. {pathIndex > 0 && <span style={{ color: '#d1d5db', marginRight: '4px' }}>或</span>}
  1404. {path.map((node, index) => {
  1405. // 获取节点的 score、strategy 和 isSelected
  1406. const nodeScore = node.data.score ? parseFloat(node.data.score) : 0;
  1407. const nodeStrategy = node.data.strategy || '';
  1408. const strategyColor = getStrategyColor(nodeStrategy);
  1409. const nodeIsSelected = node.type === 'note' ? node.data.matchLevel !== 'unsatisfied' : node.data.isSelected !== false;
  1410. const nodeActualType = node.data.nodeType || node.type; // 获取实际节点类型
  1411. return (
  1412. <React.Fragment key={node.id + '-' + index}>
  1413. <span
  1414. onClick={() => {
  1415. const nodeId = node.id;
  1416. // 找到所有祖先节点
  1417. const ancestorIds = [nodeId];
  1418. const findAncestors = (id) => {
  1419. initialEdges.forEach(edge => {
  1420. if (edge.target === id && !ancestorIds.includes(edge.source)) {
  1421. ancestorIds.push(edge.source);
  1422. findAncestors(edge.source);
  1423. }
  1424. });
  1425. };
  1426. findAncestors(nodeId);
  1427. // 如果节点或其祖先被隐藏,先恢复它们
  1428. setHiddenNodes(prev => {
  1429. const newSet = new Set(prev);
  1430. ancestorIds.forEach(id => newSet.delete(id));
  1431. return newSet;
  1432. });
  1433. // 展开目录树中到达该节点的路径
  1434. // 需要找到所有包含该节点的树路径的 treeKey,并展开它们的父节点
  1435. setCollapsedTreeNodes(prev => {
  1436. const newSet = new Set(prev);
  1437. // 清空所有折叠状态,让目录树完全展开到选中节点
  1438. // 这样可以确保选中节点在目录中可见
  1439. return new Set();
  1440. });
  1441. setSelectedNodeId(nodeId);
  1442. setTimeout(() => {
  1443. fitView({
  1444. nodes: [{ id: nodeId }],
  1445. duration: 800,
  1446. padding: 0.3,
  1447. });
  1448. }, 100);
  1449. }}
  1450. style={{
  1451. padding: '6px 8px',
  1452. borderRadius: '4px',
  1453. background: 'white',
  1454. border: index === path.length - 1 ? '2px solid #3b82f6' : '1px solid #d1d5db',
  1455. color: '#374151',
  1456. fontWeight: index === path.length - 1 ? '600' : '400',
  1457. width: '180px',
  1458. cursor: 'pointer',
  1459. transition: 'all 0.2s ease',
  1460. position: 'relative',
  1461. display: 'inline-flex',
  1462. flexDirection: 'column',
  1463. gap: '4px',
  1464. }}
  1465. onMouseEnter={(e) => {
  1466. e.currentTarget.style.opacity = '0.8';
  1467. }}
  1468. onMouseLeave={(e) => {
  1469. e.currentTarget.style.opacity = '1';
  1470. }}
  1471. title={\`\${node.data.title || node.id} (Score: \${nodeScore.toFixed(2)}, Strategy: \${nodeStrategy}, Selected: \${nodeIsSelected})\`}
  1472. >
  1473. {/* 上半部分:竖线 + 图标 + 文字 + 分数 */}
  1474. <div style={{
  1475. display: 'flex',
  1476. alignItems: 'center',
  1477. gap: '6px',
  1478. }}>
  1479. {/* 策略类型竖线 */}
  1480. <div style={{
  1481. width: '3px',
  1482. height: '16px',
  1483. background: strategyColor,
  1484. borderRadius: '2px',
  1485. flexShrink: 0,
  1486. }} />
  1487. {/* 节点文字 */}
  1488. <span style={{
  1489. flex: 1,
  1490. fontSize: '12px',
  1491. color: nodeIsSelected ? '#374151' : '#ef4444',
  1492. }}>
  1493. {truncateMiddle(node.data.title || node.id, 18)}
  1494. </span>
  1495. {/* 分数显示 - 步骤和轮次节点不显示分数 */}
  1496. {nodeActualType !== 'step' && nodeActualType !== 'round' && (
  1497. <span style={{
  1498. fontSize: '10px',
  1499. color: '#6b7280',
  1500. fontWeight: '500',
  1501. flexShrink: 0,
  1502. }}>
  1503. {nodeScore.toFixed(2)}
  1504. </span>
  1505. )}
  1506. </div>
  1507. {/* 分数下划线 - 步骤和轮次节点不显示 */}
  1508. {nodeActualType !== 'step' && nodeActualType !== 'round' && (
  1509. <div style={{
  1510. width: (nodeScore * 100) + '%',
  1511. height: '2px',
  1512. background: getScoreColor(nodeScore),
  1513. borderRadius: '1px',
  1514. marginLeft: '9px',
  1515. }} />
  1516. )}
  1517. </span>
  1518. {index < path.length - 1 && <span style={{ color: '#9ca3af' }}>›</span>}
  1519. </React.Fragment>
  1520. )})}
  1521. </div>
  1522. ))}
  1523. </div>
  1524. );
  1525. })()}
  1526. </div>
  1527. ) : (
  1528. <div style={{ fontSize: '13px', color: '#9ca3af', textAlign: 'center' }}>
  1529. 选择一个节点查看路径
  1530. </div>
  1531. )}
  1532. </div>
  1533. </div>
  1534. {/* 主内容区:目录 + 画布 */}
  1535. <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
  1536. {/* 左侧目录树 */}
  1537. <div style={{
  1538. width: '320px',
  1539. background: 'white',
  1540. borderRight: '1px solid #e5e7eb',
  1541. display: 'flex',
  1542. flexDirection: 'column',
  1543. flexShrink: 0,
  1544. }}>
  1545. <div style={{
  1546. padding: '12px 16px',
  1547. borderBottom: '1px solid #e5e7eb',
  1548. display: 'flex',
  1549. justifyContent: 'space-between',
  1550. alignItems: 'center',
  1551. }}>
  1552. <span style={{
  1553. fontWeight: '600',
  1554. fontSize: '14px',
  1555. color: '#111827',
  1556. }}>
  1557. 节点目录
  1558. </span>
  1559. <div style={{ display: 'flex', gap: '6px' }}>
  1560. <button
  1561. onClick={() => {
  1562. setCollapsedTreeNodes(new Set());
  1563. }}
  1564. style={{
  1565. fontSize: '11px',
  1566. padding: '4px 8px',
  1567. borderRadius: '4px',
  1568. border: '1px solid #d1d5db',
  1569. background: 'white',
  1570. color: '#6b7280',
  1571. cursor: 'pointer',
  1572. fontWeight: '500',
  1573. }}
  1574. title="展开全部节点"
  1575. >
  1576. 全部展开
  1577. </button>
  1578. <button
  1579. onClick={() => {
  1580. const getAllTreeKeys = (nodes) => {
  1581. const keys = new Set();
  1582. const traverse = (node) => {
  1583. if (node.children && node.children.length > 0) {
  1584. keys.add(node.treeKey);
  1585. node.children.forEach(traverse);
  1586. }
  1587. };
  1588. nodes.forEach(traverse);
  1589. return keys;
  1590. };
  1591. setCollapsedTreeNodes(getAllTreeKeys(treeRoots));
  1592. }}
  1593. style={{
  1594. fontSize: '11px',
  1595. padding: '4px 8px',
  1596. borderRadius: '4px',
  1597. border: '1px solid #d1d5db',
  1598. background: 'white',
  1599. color: '#6b7280',
  1600. cursor: 'pointer',
  1601. fontWeight: '500',
  1602. }}
  1603. title="折叠全部节点"
  1604. >
  1605. 全部折叠
  1606. </button>
  1607. <button
  1608. onClick={copyTreeToClipboard}
  1609. style={{
  1610. fontSize: '11px',
  1611. padding: '4px 8px',
  1612. borderRadius: '4px',
  1613. border: '1px solid #3b82f6',
  1614. background: '#3b82f6',
  1615. color: 'white',
  1616. cursor: 'pointer',
  1617. fontWeight: '500',
  1618. transition: 'all 0.2s',
  1619. }}
  1620. onMouseEnter={(e) => e.currentTarget.style.background = '#2563eb'}
  1621. onMouseLeave={(e) => e.currentTarget.style.background = '#3b82f6'}
  1622. title="复制树形结构为文本格式"
  1623. >
  1624. 📋 复制树形结构
  1625. </button>
  1626. </div>
  1627. </div>
  1628. <div style={{
  1629. flex: 1,
  1630. overflowX: 'auto',
  1631. overflowY: 'auto',
  1632. padding: '8px',
  1633. }}>
  1634. <div style={{ minWidth: 'fit-content' }}>
  1635. {renderTree(treeRoots)}
  1636. </div>
  1637. </div>
  1638. </div>
  1639. {/* 画布区域 */}
  1640. <div style={{ flex: 1, position: 'relative' }}>
  1641. {/* 右侧图例 */}
  1642. <div style={{
  1643. position: 'absolute',
  1644. top: '20px',
  1645. right: '20px',
  1646. background: 'white',
  1647. padding: '16px',
  1648. borderRadius: '12px',
  1649. boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
  1650. zIndex: 1000,
  1651. maxWidth: '260px',
  1652. border: '1px solid #e5e7eb',
  1653. }}>
  1654. <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
  1655. <h3 style={{ fontSize: '14px', fontWeight: '600', color: '#111827', margin: 0 }}>图例</h3>
  1656. <button
  1657. onClick={() => setFocusMode(!focusMode)}
  1658. style={{
  1659. fontSize: '11px',
  1660. padding: '4px 8px',
  1661. borderRadius: '4px',
  1662. border: '1px solid',
  1663. borderColor: focusMode ? '#3b82f6' : '#d1d5db',
  1664. background: focusMode ? '#3b82f6' : 'white',
  1665. color: focusMode ? 'white' : '#6b7280',
  1666. cursor: 'pointer',
  1667. fontWeight: '500',
  1668. }}
  1669. title={focusMode ? '关闭聚焦模式' : '开启聚焦模式'}
  1670. >
  1671. {focusMode ? '🎯 聚焦' : '📊 全图'}
  1672. </button>
  1673. </div>
  1674. <div style={{ fontSize: '12px' }}>
  1675. {/* 画布节点展开/折叠控制 */}
  1676. <div style={{ marginBottom: '12px', paddingBottom: '12px', borderBottom: '1px solid #f3f4f6' }}>
  1677. <div style={{ fontSize: '12px', fontWeight: '500', marginBottom: '8px', color: '#374151' }}>节点控制</div>
  1678. <div style={{ display: 'flex', gap: '6px' }}>
  1679. <button
  1680. onClick={() => {
  1681. setCollapsedNodes(new Set());
  1682. }}
  1683. style={{
  1684. fontSize: '11px',
  1685. padding: '4px 8px',
  1686. borderRadius: '4px',
  1687. border: '1px solid #d1d5db',
  1688. background: 'white',
  1689. color: '#6b7280',
  1690. cursor: 'pointer',
  1691. fontWeight: '500',
  1692. flex: 1,
  1693. }}
  1694. title="展开画布中所有节点的子节点"
  1695. >
  1696. 全部展开
  1697. </button>
  1698. <button
  1699. onClick={() => {
  1700. const allNodeIds = new Set(initialNodes.map(n => n.id));
  1701. setCollapsedNodes(allNodeIds);
  1702. }}
  1703. style={{
  1704. fontSize: '11px',
  1705. padding: '4px 8px',
  1706. borderRadius: '4px',
  1707. border: '1px solid #d1d5db',
  1708. background: 'white',
  1709. color: '#6b7280',
  1710. cursor: 'pointer',
  1711. fontWeight: '500',
  1712. flex: 1,
  1713. }}
  1714. title="折叠画布中所有节点的子节点"
  1715. >
  1716. 全部折叠
  1717. </button>
  1718. </div>
  1719. </div>
  1720. <div style={{ paddingTop: '12px', borderTop: '1px solid #f3f4f6' }}>
  1721. <div style={{ fontSize: '12px', fontWeight: '500', marginBottom: '8px', color: '#374151' }}>策略类型</div>
  1722. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1723. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#10b981', opacity: 0.7 }}></div>
  1724. <span style={{ color: '#6b7280', fontSize: '11px' }}>初始分词</span>
  1725. </div>
  1726. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1727. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#06b6d4', opacity: 0.7 }}></div>
  1728. <span style={{ color: '#6b7280', fontSize: '11px' }}>调用sug</span>
  1729. </div>
  1730. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1731. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#f59e0b', opacity: 0.7 }}></div>
  1732. <span style={{ color: '#6b7280', fontSize: '11px' }}>同义改写</span>
  1733. </div>
  1734. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1735. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#3b82f6', opacity: 0.7 }}></div>
  1736. <span style={{ color: '#6b7280', fontSize: '11px' }}>加词</span>
  1737. </div>
  1738. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1739. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#8b5cf6', opacity: 0.7 }}></div>
  1740. <span style={{ color: '#6b7280', fontSize: '11px' }}>抽象改写</span>
  1741. </div>
  1742. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1743. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#ec4899', opacity: 0.7 }}></div>
  1744. <span style={{ color: '#6b7280', fontSize: '11px' }}>基于部分匹配改进</span>
  1745. </div>
  1746. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1747. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#a855f7', opacity: 0.7 }}></div>
  1748. <span style={{ color: '#6b7280', fontSize: '11px' }}>结果分支-抽象改写</span>
  1749. </div>
  1750. <div style={{ display: 'flex', alignItems: 'center', margin: '6px 0' }}>
  1751. <div style={{ width: '20px', height: '2px', marginRight: '8px', background: '#fb923c', opacity: 0.7 }}></div>
  1752. <span style={{ color: '#6b7280', fontSize: '11px' }}>结果分支-同义改写</span>
  1753. </div>
  1754. </div>
  1755. <div style={{
  1756. marginTop: '12px',
  1757. paddingTop: '12px',
  1758. borderTop: '1px solid #f3f4f6',
  1759. fontSize: '11px',
  1760. color: '#9ca3af',
  1761. lineHeight: '1.5',
  1762. }}>
  1763. 💡 点击节点左上角 × 隐藏节点
  1764. </div>
  1765. {/* 隐藏节点列表 - 在图例内部 */}
  1766. {hiddenNodes.size > 0 && (
  1767. <div style={{
  1768. marginTop: '12px',
  1769. paddingTop: '12px',
  1770. borderTop: '1px solid #f3f4f6',
  1771. }}>
  1772. <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
  1773. <h4 style={{ fontSize: '12px', fontWeight: '600', color: '#111827' }}>已隐藏节点</h4>
  1774. <button
  1775. onClick={() => setHiddenNodes(new Set())}
  1776. style={{
  1777. fontSize: '10px',
  1778. color: '#3b82f6',
  1779. background: 'none',
  1780. border: 'none',
  1781. cursor: 'pointer',
  1782. textDecoration: 'underline',
  1783. }}
  1784. >
  1785. 全部恢复
  1786. </button>
  1787. </div>
  1788. <div style={{ fontSize: '12px', maxHeight: '200px', overflow: 'auto' }}>
  1789. {Array.from(hiddenNodes).map(nodeId => {
  1790. const node = initialNodes.find(n => n.id === nodeId);
  1791. if (!node) return null;
  1792. return (
  1793. <div
  1794. key={nodeId}
  1795. style={{
  1796. display: 'flex',
  1797. justifyContent: 'space-between',
  1798. alignItems: 'center',
  1799. padding: '6px 8px',
  1800. margin: '4px 0',
  1801. background: '#f9fafb',
  1802. borderRadius: '6px',
  1803. fontSize: '11px',
  1804. }}
  1805. >
  1806. <span
  1807. style={{
  1808. flex: 1,
  1809. overflow: 'hidden',
  1810. textOverflow: 'ellipsis',
  1811. whiteSpace: 'nowrap',
  1812. color: '#374151',
  1813. }}
  1814. title={node.data.title || nodeId}
  1815. >
  1816. {node.data.title || nodeId}
  1817. </span>
  1818. <button
  1819. onClick={() => {
  1820. setHiddenNodes(prev => {
  1821. const newSet = new Set(prev);
  1822. newSet.delete(nodeId);
  1823. return newSet;
  1824. });
  1825. }}
  1826. style={{
  1827. marginLeft: '8px',
  1828. fontSize: '10px',
  1829. color: '#10b981',
  1830. background: 'none',
  1831. border: 'none',
  1832. cursor: 'pointer',
  1833. flexShrink: 0,
  1834. }}
  1835. >
  1836. 恢复
  1837. </button>
  1838. </div>
  1839. );
  1840. })}
  1841. </div>
  1842. </div>
  1843. )}
  1844. </div>
  1845. </div>
  1846. {/* React Flow 画布 */}
  1847. <ReactFlow
  1848. nodes={nodes}
  1849. edges={edges}
  1850. nodeTypes={nodeTypes}
  1851. fitView
  1852. fitViewOptions={{ padding: 0.2, duration: 500 }}
  1853. minZoom={0.1}
  1854. maxZoom={1.5}
  1855. nodesDraggable={true}
  1856. nodesConnectable={false}
  1857. elementsSelectable={true}
  1858. defaultEdgeOptions={{
  1859. type: 'smoothstep',
  1860. }}
  1861. proOptions={{ hideAttribution: true }}
  1862. onNodeClick={(event, clickedNode) => {
  1863. setSelectedNodeId(clickedNode.id);
  1864. }}
  1865. >
  1866. <Controls style={{ bottom: '20px', left: 'auto', right: '20px' }} />
  1867. <Background variant="dots" gap={20} size={1} color="#e5e7eb" />
  1868. </ReactFlow>
  1869. </div>
  1870. </div>
  1871. </div>
  1872. );
  1873. }
  1874. function App() {
  1875. return (
  1876. <ReactFlowProvider>
  1877. <FlowContent />
  1878. </ReactFlowProvider>
  1879. );
  1880. }
  1881. const root = createRoot(document.getElementById('root'));
  1882. root.render(<App />);
  1883. `;
  1884. fs.writeFileSync(reactComponentPath, reactComponent);
  1885. // 使用 esbuild 打包
  1886. console.log('🎨 Building modern visualization...');
  1887. build({
  1888. entryPoints: [reactComponentPath],
  1889. bundle: true,
  1890. outfile: path.join(__dirname, 'bundle_v2.js'),
  1891. format: 'iife',
  1892. loader: {
  1893. '.css': 'css',
  1894. },
  1895. minify: false,
  1896. sourcemap: 'inline',
  1897. // 强制所有 React 引用指向同一个位置,避免多副本
  1898. alias: {
  1899. 'react': path.join(__dirname, 'node_modules/react'),
  1900. 'react-dom': path.join(__dirname, 'node_modules/react-dom'),
  1901. 'react/jsx-runtime': path.join(__dirname, 'node_modules/react/jsx-runtime'),
  1902. 'react/jsx-dev-runtime': path.join(__dirname, 'node_modules/react/jsx-dev-runtime'),
  1903. },
  1904. }).then(() => {
  1905. // 读取打包后的 JS
  1906. const bundleJs = fs.readFileSync(path.join(__dirname, 'bundle_v2.js'), 'utf-8');
  1907. // 读取 CSS
  1908. const cssPath = path.join(__dirname, 'node_modules/@xyflow/react/dist/style.css');
  1909. const css = fs.readFileSync(cssPath, 'utf-8');
  1910. // 生成最终 HTML
  1911. const html = `<!DOCTYPE html>
  1912. <html lang="zh-CN">
  1913. <head>
  1914. <meta charset="UTF-8">
  1915. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1916. <title>查询图可视化</title>
  1917. <link rel="preconnect" href="https://fonts.googleapis.com">
  1918. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  1919. <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
  1920. <script src="https://unpkg.com/dagre@0.8.5/dist/dagre.min.js"></script>
  1921. <script>
  1922. // 过滤特定的 React 警告
  1923. const originalError = console.error;
  1924. console.error = (...args) => {
  1925. if (typeof args[0] === 'string' && args[0].includes('Each child in a list should have a unique "key" prop')) {
  1926. return;
  1927. }
  1928. originalError.apply(console, args);
  1929. };
  1930. </script>
  1931. <style>
  1932. * {
  1933. margin: 0;
  1934. padding: 0;
  1935. box-sizing: border-box;
  1936. }
  1937. body {
  1938. font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  1939. overflow: hidden;
  1940. -webkit-font-smoothing: antialiased;
  1941. -moz-osx-font-smoothing: grayscale;
  1942. }
  1943. #root {
  1944. width: 100vw;
  1945. height: 100vh;
  1946. }
  1947. ${css}
  1948. /* 自定义样式覆盖 */
  1949. .react-flow__edge-path {
  1950. stroke-linecap: round;
  1951. }
  1952. .react-flow__controls {
  1953. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  1954. border: 1px solid #e5e7eb;
  1955. border-radius: 8px;
  1956. }
  1957. .react-flow__controls-button {
  1958. border: none;
  1959. border-bottom: 1px solid #e5e7eb;
  1960. }
  1961. .react-flow__controls-button:hover {
  1962. background: #f9fafb;
  1963. }
  1964. </style>
  1965. </head>
  1966. <body>
  1967. <div id="root"></div>
  1968. <script>${bundleJs}</script>
  1969. </body>
  1970. </html>`;
  1971. // 写入输出文件
  1972. fs.writeFileSync(outputFile, html);
  1973. // 清理临时文件
  1974. fs.unlinkSync(reactComponentPath);
  1975. fs.unlinkSync(path.join(__dirname, 'bundle_v2.js'));
  1976. console.log('✅ Visualization generated: ' + outputFile);
  1977. console.log('📊 Nodes: ' + Object.keys(data.nodes).length);
  1978. console.log('🔗 Edges: ' + data.edges.length);
  1979. }).catch(error => {
  1980. console.error('❌ Build error:', error);
  1981. process.exit(1);
  1982. });