index.js 87 KB

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