index.js 97 KB

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