index.js 111 KB

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