index.js 129 KB

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