index.js 129 KB

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