index.js 82 KB

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