index.js 97 KB

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