index.js 83 KB

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