index.js 128 KB

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