index.js 91 KB

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