index.js 115 KB

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