knowledge-mindmap-graph.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. class KnowledgeMindmapGraph {
  2. constructor(options = {}) {
  3. this.graph = null;
  4. this.rawTree = null;
  5. this.treeData = null;
  6. this.relationEdges = [];
  7. this.masteryData = {};
  8. this.masteryCache = {};
  9. this.stats = { nodes: 0, extraEdges: 0 };
  10. this.containerId = options.containerId || 'knowledge-mindmap';
  11. this.livewireMethod = options.livewireMethod || 'openDrawer';
  12. this.onNodeSelect = options.onNodeSelect || null;
  13. this.livewireId = options.livewireId || null;
  14. this.highlightLowMastery = options.highlightLowMastery ?? true;
  15. this.emitSelection = options.emitSelection ?? true;
  16. this.tooltipEl = null;
  17. this.nodeIdSet = new Set();
  18. this.lockRules = options.lockRules || [
  19. { prerequisite: 'P04', target: 'P05', threshold: 0.6 },
  20. { prerequisite: 'P05', target: 'P06', threshold: 0.6 },
  21. ];
  22. this.parentMap = {};
  23. this.setMasteryData(options.masteryData || {});
  24. }
  25. async init() {
  26. try {
  27. await this.loadData();
  28. this.applyUnlockRules(this.treeData);
  29. this.applyInitialCollapse(this.treeData);
  30. this.expandForMastery();
  31. this.renderGraph();
  32. this.bindEvents();
  33. this.setupLivewireListeners();
  34. window.addEventListener('resize', () => this.resizeGraph());
  35. } catch (error) {
  36. console.error('初始化思维导图失败', error);
  37. }
  38. }
  39. async loadData() {
  40. const [treeResp, edgesResp] = await Promise.all([
  41. fetch('/data/tree.json'),
  42. fetch('/data/edges.json'),
  43. ]);
  44. this.rawTree = await treeResp.json();
  45. const edges = await edgesResp.json();
  46. const rawEdges = Array.isArray(edges) ? edges : edges?.edges || [];
  47. this.masteryCache = {};
  48. this.treeData = this.transformNode(this.rawTree);
  49. this.buildParentMap(this.treeData);
  50. this.relationEdges = this.normalizeEdges(rawEdges);
  51. const flatIds = [];
  52. this.collectIds(this.treeData, flatIds);
  53. console.log('知识点总数', flatIds.length, '列表:', flatIds);
  54. this.nodeIdSet = new Set(flatIds);
  55. this.logMasteryCoverage();
  56. this.stats = {
  57. nodes: this.countNodes(this.treeData),
  58. extraEdges: this.relationEdges.length,
  59. };
  60. }
  61. transformNode(node, depth = 0) {
  62. if (!node) return null;
  63. const id =
  64. node.code ||
  65. node.id ||
  66. node.label ||
  67. `node-${Math.random().toString(36).slice(2, 8)}`;
  68. const label = node.name || node.label || node.code || node.id || id;
  69. const masteryInfo = this.masteryData[id] || null;
  70. const masteryLevel = this.getMasteryLevel(id);
  71. const accuracy = this.toNumber(masteryInfo?.accuracy_rate);
  72. const recommended = masteryLevel < 0.6;
  73. const model = {
  74. id,
  75. label: `${id} · ${label}`,
  76. depth,
  77. locked: false,
  78. collapsed: depth > 0 && (node.children || []).length > 0, // 默认折叠所有有子节点的节点(除根节点)
  79. meta: {
  80. code: id,
  81. name: label,
  82. mastery_level: masteryLevel,
  83. accuracy_rate: accuracy,
  84. total_attempts: this.toNumber(masteryInfo?.total_attempts),
  85. mastery_info: masteryInfo,
  86. has_mastery: Boolean(masteryInfo),
  87. recommended,
  88. },
  89. children: (node.children || [])
  90. .map((child) => this.transformNode(child, depth + 1))
  91. .filter(Boolean),
  92. };
  93. return model;
  94. }
  95. getMasteryLevel(id) {
  96. if (this.masteryCache[id] !== undefined) {
  97. return this.masteryCache[id];
  98. }
  99. const remote = this.masteryData[id]?.mastery_level;
  100. const value = this.normalizeMasteryLevel(remote);
  101. this.masteryCache[id] = value;
  102. return value;
  103. }
  104. applyUnlockRules(node) {
  105. if (!node) return;
  106. const rule = this.lockRules.find((item) => item.target === node.id);
  107. const prereqMastery = rule
  108. ? this.masteryCache[rule.prerequisite] ?? 0
  109. : 1;
  110. const lockedByRule = rule ? prereqMastery < rule.threshold : false;
  111. node.locked = lockedByRule;
  112. if (node.locked) {
  113. node.meta.lock_reason = lockedByRule
  114. ? `需先掌握前置知识点:${rule.prerequisite}`
  115. : '需先掌握前置知识点';
  116. }
  117. node.children.forEach((child) => this.applyUnlockRules(child));
  118. }
  119. applyInitialCollapse(node, depth = 0) {
  120. if (!node) return;
  121. // 默认折叠所有有子节点的节点(除了根节点)
  122. if (depth > 0 && node.children.length > 0) {
  123. node.collapsed = true;
  124. }
  125. node.children.forEach((child) =>
  126. this.applyInitialCollapse(child, depth + 1)
  127. );
  128. }
  129. expandForMastery() {
  130. if (!this.treeData) return;
  131. const masteryKeys = new Set(Object.keys(this.masteryData || {}));
  132. if (!masteryKeys.size) return;
  133. this.expandNodesForMastery(this.treeData, masteryKeys);
  134. }
  135. expandNodesForMastery(node, masteryKeys) {
  136. if (!node) return false;
  137. const hasMastery = masteryKeys.has(node.id);
  138. let childHas = false;
  139. (node.children || []).forEach((child) => {
  140. if (this.expandNodesForMastery(child, masteryKeys)) {
  141. childHas = true;
  142. }
  143. });
  144. if (hasMastery || childHas) {
  145. node.collapsed = false;
  146. }
  147. return hasMastery || childHas;
  148. }
  149. countNodes(node) {
  150. if (!node) return 0;
  151. return (
  152. 1 +
  153. node.children.reduce(
  154. (sum, child) => sum + this.countNodes(child),
  155. 0
  156. )
  157. );
  158. }
  159. normalizeEdges(rawEdges) {
  160. const seen = new Set();
  161. const normalized = [];
  162. const styleMap = {
  163. prerequisite: { stroke: '#60a5fa', lineDash: [10, 8], lineWidth: 3, label: '前置' },
  164. successor: { stroke: '#7dd3fc', lineWidth: 3, label: '后继' },
  165. crosslink: { stroke: '#fb923c', lineDash: [8, 6], lineWidth: 2.5, label: '跨联' },
  166. sibling: { stroke: '#94a3b8', lineDash: [6, 6], lineWidth: 2.5, label: '同级' },
  167. };
  168. (rawEdges || []).forEach((edge, index) => {
  169. if (!edge?.source || !edge?.target) return;
  170. const key = `${edge.source}-${edge.target}-${edge.type}`;
  171. if (seen.has(key)) return;
  172. seen.add(key);
  173. const category = edge.type || 'successor';
  174. const renderType =
  175. category === 'successor' ? 'cubic-horizontal' : 'quadratic';
  176. const baseStyle = styleMap[category] || {
  177. stroke: '#cbd5e1',
  178. lineWidth: 2.5,
  179. };
  180. const label = baseStyle.label || edge.label || category;
  181. const arrowStroke = baseStyle.stroke || '#cbd5e1';
  182. const style = {
  183. ...baseStyle,
  184. endArrow: {
  185. path: 'M 0,0 L 8,4 L 0,8 z',
  186. fill: arrowStroke,
  187. d: 8,
  188. },
  189. startArrow: false,
  190. };
  191. normalized.push({
  192. id: `rel-${index}`,
  193. source: edge.source,
  194. target: edge.target,
  195. type: renderType,
  196. edgeType: category,
  197. style: {
  198. ...style,
  199. },
  200. label,
  201. comment: edge.comment || edge.note || '',
  202. });
  203. });
  204. return normalized;
  205. }
  206. collectIds(node, bucket) {
  207. if (!node) return;
  208. bucket.push(node.id);
  209. (node.children || []).forEach((child) => this.collectIds(child, bucket));
  210. }
  211. renderGraph() {
  212. const container = document.getElementById(this.containerId);
  213. if (!container) return;
  214. const bounds = container.getBoundingClientRect();
  215. const width = Math.max(bounds.width, 640);
  216. const height = Math.max(bounds.height, 640);
  217. // 直接在数据层面设置折叠状态
  218. this.setCollapsedState(this.treeData);
  219. this.graph = new G6.TreeGraph({
  220. container: this.containerId,
  221. width,
  222. height,
  223. modes: {
  224. default: [
  225. 'drag-canvas',
  226. 'zoom-canvas',
  227. {
  228. type: 'collapse-expand',
  229. trigger: 'click',
  230. onChange: (item, collapsed) => {
  231. if (!item) return;
  232. item.getModel().collapsed = collapsed;
  233. return true;
  234. },
  235. },
  236. ],
  237. },
  238. defaultNode: {
  239. type: 'hexagon-card',
  240. size: 110,
  241. },
  242. defaultEdge: {
  243. type: 'cubic-horizontal',
  244. style: {
  245. stroke: '#cbd5e1',
  246. lineWidth: 2,
  247. },
  248. },
  249. nodeStateStyles: {
  250. hover: { shadowColor: '#38bdf8', shadowBlur: 24 },
  251. selected: { shadowColor: '#fb923c', shadowBlur: 28 },
  252. dimmed: { opacity: 0.3 },
  253. weak: { opacity: 0.6 },
  254. locked: { opacity: 0.35, cursor: 'not-allowed' },
  255. },
  256. edgeStateStyles: {
  257. hover: { lineWidth: 3, stroke: '#38bdf8' },
  258. connected: { opacity: 0.95, lineWidth: 3 },
  259. dimmed: { opacity: 0.25 },
  260. crosshover: { stroke: '#fb923c', lineWidth: 3 },
  261. glow: { shadowColor: '#facc15', shadowBlur: 12 },
  262. },
  263. layout: {
  264. type: 'mindmap',
  265. direction: 'H',
  266. getHeight: () => 110,
  267. getWidth: () => 150,
  268. getVGap: () => 18,
  269. getHGap: () => 50,
  270. preventOverlap: true,
  271. },
  272. });
  273. this.graph.data(this.treeData);
  274. this.graph.render();
  275. this.graph.fitView(12);
  276. // 暴露实例便于调试
  277. window.KnowledgeMindmapGraphInstance = this;
  278. window.KnowledgeMindmapG6Graph = this.graph;
  279. // 边提示
  280. this.bindEdgeTooltip();
  281. this.applyNodeStates();
  282. this.startEdgeFlows();
  283. this.focusOnLowestMastery();
  284. this.repaintNodes();
  285. // 折叠/展开或重新布局后重新挂载关联线
  286. this.graph.on('afterlayout', () => {
  287. this.redrawRelationEdges();
  288. });
  289. }
  290. setCollapsedState(nodeData, depth = 0) {
  291. if (!nodeData) return;
  292. // 折叠除根节点外的所有有子节点的节点
  293. if (depth > 0 && nodeData.children && nodeData.children.length > 0) {
  294. if (nodeData.collapsed === undefined) {
  295. nodeData.collapsed = true;
  296. }
  297. }
  298. // 递归处理子节点
  299. if (nodeData.children) {
  300. nodeData.children.forEach(child => this.setCollapsedState(child, depth + 1));
  301. }
  302. }
  303. clearRelationEdges() {
  304. if (!this.graph) return;
  305. this.graph.getEdges().forEach((edge) => {
  306. const id = edge.getModel()?.id || '';
  307. if (id.startsWith('rel-')) {
  308. this.graph.removeItem(edge);
  309. }
  310. });
  311. }
  312. drawRelationEdges() {
  313. if (!this.graph || !this.relationEdges.length) return;
  314. this.relationEdges.forEach((edge) => {
  315. // 尝试将隐藏节点映射到可见的父节点,避免关联线丢失
  316. let sourceId = edge.source;
  317. let targetId = edge.target;
  318. const resolveVisible = (id) => {
  319. let cur = id;
  320. while (cur) {
  321. if (this.graph.findById(cur)) return cur;
  322. cur = this.parentMap[cur];
  323. }
  324. return null;
  325. };
  326. if (!this.graph.findById(sourceId)) {
  327. const fallback = resolveVisible(sourceId);
  328. if (fallback) sourceId = fallback;
  329. }
  330. if (!this.graph.findById(targetId)) {
  331. const fallback = resolveVisible(targetId);
  332. if (fallback) targetId = fallback;
  333. }
  334. const sourceVisible = this.graph.findById(sourceId);
  335. const targetVisible = this.graph.findById(targetId);
  336. // 若两端都找不到可见节点,直接跳过
  337. if (!sourceVisible && !targetVisible) {
  338. return;
  339. }
  340. // 若只有一端可见,则将不可见端提升到其最近的可见父节点(若仍不可见则跳过)
  341. if (!sourceVisible) {
  342. const resolved = resolveVisible(edge.source);
  343. if (!resolved || !this.graph.findById(resolved)) return;
  344. sourceId = resolved;
  345. }
  346. if (!targetVisible) {
  347. const resolved = resolveVisible(edge.target);
  348. if (!resolved || !this.graph.findById(resolved)) return;
  349. targetId = resolved;
  350. }
  351. this.graph.addItem('edge', { ...edge, source: sourceId, target: targetId });
  352. });
  353. }
  354. applyNodeStates() {
  355. if (!this.graph) return;
  356. this.graph.getNodes().forEach((node) => {
  357. const model = node.getModel();
  358. const mastery = model.meta?.mastery_level ?? 0;
  359. const hasMastery =
  360. model.meta?.has_mastery ?? Boolean(this.masteryData[model.id]);
  361. this.graph.setItemState(node, 'dimmed', !hasMastery);
  362. if (model.locked) {
  363. this.graph.setItemState(node, 'locked', true);
  364. }
  365. if (hasMastery && mastery < 0.4 && this.highlightLowMastery) {
  366. this.graph.setItemState(node, 'weak', true);
  367. }
  368. if (hasMastery && mastery >= 0.8 && !model.locked) {
  369. this.playHalo(node);
  370. }
  371. });
  372. }
  373. startEdgeFlows() {
  374. if (!this.graph) return;
  375. const nodeMap = new Map(
  376. this.graph
  377. .getNodes()
  378. .map((node) => [node.getModel().id, node.getModel()])
  379. );
  380. this.graph.getEdges().forEach((edge) => {
  381. const model = edge.getModel();
  382. const sourceMastery =
  383. nodeMap.get(model.source)?.meta?.mastery_level ?? 0;
  384. const category = model.edgeType || model.type;
  385. if (sourceMastery >= 0.8 && category !== 'crosslink') {
  386. this.animateEdgeFlow(edge, '#facc15');
  387. }
  388. });
  389. }
  390. animateEdgeFlow(edge, color) {
  391. if (!edge || edge.__flowing) return;
  392. const keyShape = edge.getKeyShape?.();
  393. if (!keyShape || !keyShape.getTotalLength) return;
  394. const totalLength = keyShape.getTotalLength();
  395. keyShape.attr('lineDash', [20, 12]);
  396. keyShape.attr('stroke', color);
  397. edge.__flowing = true;
  398. keyShape.animate(
  399. (ratio) => ({
  400. lineDashOffset: -ratio * totalLength,
  401. opacity: 0.8 + 0.2 * Math.sin(ratio * Math.PI),
  402. }),
  403. { duration: 1600, repeat: true }
  404. );
  405. }
  406. playHalo(node) {
  407. const group = node.getContainer();
  408. const keyShape = node.getKeyShape();
  409. if (!group || !keyShape) return;
  410. const bbox = keyShape.getBBox();
  411. const halo = group.addShape('circle', {
  412. attrs: {
  413. x: bbox.centerX,
  414. y: bbox.centerY,
  415. r: Math.max(bbox.width, bbox.height) * 0.65,
  416. stroke: '#facc15',
  417. lineWidth: 2,
  418. opacity: 0.4,
  419. },
  420. name: 'halo-shape',
  421. });
  422. halo.animate(
  423. (ratio) => ({
  424. r: halo.attr('r') + ratio * 16,
  425. opacity: 0.4 - ratio * 0.4,
  426. }),
  427. {
  428. duration: 1200,
  429. easing: 'easeCubic',
  430. repeat: false,
  431. removeOnEnd: true,
  432. }
  433. );
  434. }
  435. bindEvents() {
  436. if (!this.graph) return;
  437. this.graph.on('node:mouseenter', (evt) => {
  438. const item = evt.item;
  439. if (!item || item.getModel().locked) return;
  440. this.graph.setItemState(item, 'hover', true);
  441. this.highlightNeighbors(item.getModel().id);
  442. this.showTooltip(evt, item.getModel());
  443. });
  444. this.graph.on('node:mouseleave', (evt) => {
  445. const item = evt.item;
  446. if (!item) return;
  447. this.graph.setItemState(item, 'hover', false);
  448. this.clearNeighborHighlight();
  449. this.hideTooltip();
  450. });
  451. this.graph.on('node:click', (evt) => {
  452. const model = evt.item?.getModel();
  453. if (!model) return;
  454. if (model.locked) {
  455. return;
  456. }
  457. this.graph.getNodes().forEach((node) => {
  458. this.graph.clearItemStates(node);
  459. });
  460. this.graph.setItemState(evt.item, 'selected', true);
  461. this.flashNode(evt.item);
  462. if (this.emitSelection) {
  463. this.notifySelection(model);
  464. }
  465. this.showTooltip(evt, model);
  466. });
  467. this.graph.on('canvas:click', () => {
  468. this.graph.getNodes().forEach((node) => {
  469. this.graph.clearItemStates(node);
  470. });
  471. this.clearNeighborHighlight();
  472. this.hideTooltip();
  473. });
  474. }
  475. flashNode(item) {
  476. const keyShape = item?.getKeyShape?.();
  477. if (!keyShape) return;
  478. keyShape.animate({ opacity: 0.8 }, { duration: 80 });
  479. keyShape.animate({ opacity: 1 }, { duration: 200, delay: 80 });
  480. }
  481. highlightNeighbors(nodeId) {
  482. const connected = new Set([nodeId]);
  483. this.graph.getEdges().forEach((edge) => {
  484. const model = edge.getModel();
  485. const related =
  486. model.source === nodeId || model.target === nodeId;
  487. this.graph.setItemState(edge, 'hover', related);
  488. const category = model.edgeType || model.type;
  489. if (category === 'crosslink') {
  490. this.graph.setItemState(edge, 'crosshover', related);
  491. }
  492. if (related) {
  493. connected.add(model.source);
  494. connected.add(model.target);
  495. } else {
  496. this.graph.clearItemStates(edge, ['hover', 'crosshover']);
  497. }
  498. });
  499. this.graph.getNodes().forEach((node) => {
  500. const id = node.getModel().id;
  501. this.graph.setItemState(node, 'dimmed', !connected.has(id));
  502. });
  503. }
  504. clearNeighborHighlight() {
  505. this.graph.getEdges().forEach((edge) => {
  506. this.graph.clearItemStates(edge, ['hover', 'crosshover']);
  507. });
  508. this.graph.getNodes().forEach((node) => {
  509. this.graph.setItemState(node, 'dimmed', false);
  510. });
  511. }
  512. notifySelection(model) {
  513. if (typeof this.onNodeSelect === 'function') {
  514. this.onNodeSelect(model);
  515. return;
  516. }
  517. if (!window.Livewire) return;
  518. const targetId =
  519. this.livewireId ||
  520. document
  521. .querySelector('[data-knowledge-mindmap-root] [wire\\:id], [wire\\:id]')
  522. ?.getAttribute('wire:id');
  523. const component = targetId ? window.Livewire.find(targetId) : null;
  524. if (component?.call) {
  525. component.call(this.livewireMethod, model.id);
  526. }
  527. }
  528. ensureTooltipEl() {
  529. if (this.tooltipEl) return this.tooltipEl;
  530. const div = document.createElement('div');
  531. div.style.position = 'fixed';
  532. div.style.zIndex = '9999';
  533. div.style.pointerEvents = 'none';
  534. div.style.padding = '10px 12px';
  535. div.style.background = 'rgba(15,23,42,0.95)';
  536. div.style.color = '#e2e8f0';
  537. div.style.borderRadius = '10px';
  538. div.style.boxShadow = '0 10px 30px rgba(0,0,0,0.18)';
  539. div.style.fontSize = '12px';
  540. div.style.lineHeight = '1.4';
  541. document.body.appendChild(div);
  542. this.tooltipEl = div;
  543. return div;
  544. }
  545. showTooltip(evt, model) {
  546. const tip = this.ensureTooltipEl();
  547. const mastery = (model.meta?.mastery_level ?? 0) * 100;
  548. const attempts = model.meta?.total_attempts ?? 0;
  549. const recommended = model.meta?.recommended ? '是' : '否';
  550. const locked = model.locked ? '是' : '否';
  551. tip.innerHTML = `
  552. <div style="font-weight:700;font-size:13px;">${model.id} · ${model.meta?.name || model.label}</div>
  553. <div>掌握度:${mastery.toFixed(1)}%</div>
  554. <div>推荐练习:${recommended}</div>
  555. <div>尝试次数:${attempts}</div>
  556. <div>锁定:${locked}</div>
  557. `;
  558. const x =
  559. evt?.clientX ??
  560. evt?.canvasX ??
  561. evt?.x ??
  562. evt?.event?.clientX ??
  563. 0;
  564. const y =
  565. evt?.clientY ??
  566. evt?.canvasY ??
  567. evt?.y ??
  568. evt?.event?.clientY ??
  569. 0;
  570. tip.style.left = `${x + 16}px`;
  571. tip.style.top = `${y + 12}px`;
  572. tip.style.opacity = '1';
  573. }
  574. hideTooltip() {
  575. if (!this.tooltipEl) return;
  576. this.tooltipEl.style.opacity = '0';
  577. }
  578. setupLivewireListeners() {
  579. ['mastery-updated', 'mindmap-mastery-updated'].forEach((event) => {
  580. window.addEventListener(event, (detailEvent) => {
  581. const payload =
  582. detailEvent.detail?.data ??
  583. detailEvent.detail ??
  584. {};
  585. this.setMasteryData(payload);
  586. this.refreshGraph();
  587. });
  588. });
  589. }
  590. focusOnLowestMastery() {
  591. if (!this.graph) return;
  592. const entries = Object.entries(this.masteryData || {}).filter(
  593. ([, value]) =>
  594. value && typeof value.mastery_level === 'number'
  595. );
  596. if (!entries.length) return;
  597. let targetId = null;
  598. let minLevel = Infinity;
  599. entries.forEach(([id, value]) => {
  600. const level = value.mastery_level;
  601. if (typeof level === 'number' && level < minLevel) {
  602. minLevel = level;
  603. targetId = id;
  604. }
  605. });
  606. if (!targetId) return;
  607. this.graph.getNodes().forEach((node) => {
  608. this.graph.clearItemStates(node);
  609. });
  610. const item = this.graph.findById(targetId);
  611. if (item) {
  612. this.graph.focusItem(item, true, {
  613. easing: 'easeCubic',
  614. duration: 500,
  615. });
  616. this.graph.setItemState(item, 'selected', true);
  617. }
  618. }
  619. refreshGraph() {
  620. if (!this.graph || !this.rawTree) return;
  621. this.masteryCache = {};
  622. this.treeData = this.transformNode(this.rawTree);
  623. this.buildParentMap(this.treeData);
  624. const flatIds = [];
  625. this.collectIds(this.treeData, flatIds);
  626. this.nodeIdSet = new Set(flatIds);
  627. this.logMasteryCoverage();
  628. this.applyUnlockRules(this.treeData);
  629. this.applyInitialCollapse(this.treeData);
  630. this.expandForMastery();
  631. // 强制全量重绘,确保 meta/颜色更新
  632. this.graph.clear();
  633. this.graph.data(this.treeData);
  634. this.graph.render();
  635. this.repaintNodes();
  636. this.graph.fitView(12);
  637. // 暴露实例便于调试(刷新后仍可用)
  638. window.KnowledgeMindmapGraphInstance = this;
  639. window.KnowledgeMindmapG6Graph = this.graph;
  640. this.clearRelationEdges();
  641. this.drawRelationEdges();
  642. this.applyNodeStates();
  643. this.startEdgeFlows();
  644. this.focusOnLowestMastery();
  645. this.graph.paint();
  646. }
  647. bindEdgeTooltip() {
  648. if (!this.graph) return;
  649. const tooltipEl = document.createElement('div');
  650. tooltipEl.style.position = 'fixed';
  651. tooltipEl.style.pointerEvents = 'none';
  652. tooltipEl.style.zIndex = '9999';
  653. tooltipEl.style.display = 'none';
  654. tooltipEl.style.background = 'rgba(15,23,42,0.95)';
  655. tooltipEl.style.color = '#e2e8f0';
  656. tooltipEl.style.padding = '8px 10px';
  657. tooltipEl.style.borderRadius = '8px';
  658. tooltipEl.style.boxShadow = '0 10px 30px rgba(0,0,0,0.18)';
  659. tooltipEl.style.fontSize = '12px';
  660. tooltipEl.style.lineHeight = '1.4';
  661. document.body.appendChild(tooltipEl);
  662. const show = (html, x, y) => {
  663. tooltipEl.innerHTML = html;
  664. tooltipEl.style.left = `${x + 12}px`;
  665. tooltipEl.style.top = `${y + 12}px`;
  666. tooltipEl.style.display = 'block';
  667. };
  668. const hide = () => {
  669. tooltipEl.style.display = 'none';
  670. };
  671. const buildHtml = (model) => {
  672. return `
  673. <div style="font-weight:700;font-size:13px;margin-bottom:4px;">${model.label || '关联'}</div>
  674. <div style="font-size:12px;">${model.source || ''} → ${model.target || ''}</div>
  675. ${model.comment ? `<div style="font-size:11px;color:#cbd5e1;margin-top:4px;white-space:pre-line;">${model.comment}</div>` : ''}
  676. `;
  677. };
  678. this.graph.on('edge:mouseenter', (evt) => {
  679. const model = evt?.item?.getModel?.() || {};
  680. const { clientX, clientY } = evt;
  681. show(buildHtml(model), clientX, clientY);
  682. });
  683. this.graph.on('edge:mouseleave', () => hide());
  684. }
  685. redrawRelationEdges() {
  686. this.clearRelationEdges();
  687. this.drawRelationEdges();
  688. }
  689. forceCollapseNodes() {
  690. if (!this.graph) return;
  691. }
  692. forceCollapse() {
  693. if (!this.graph) {
  694. setTimeout(() => this.forceCollapse(), 200);
  695. return;
  696. }
  697. const nodes = this.graph.getNodes();
  698. let collapsedCount = 0;
  699. nodes.forEach(node => {
  700. const model = node.getModel();
  701. // 折叠除根节点外的所有有子节点的节点
  702. if (
  703. this.masteryData[model.id] ||
  704. (model.meta && this.masteryData[model.meta.code])
  705. ) {
  706. model.collapsed = false;
  707. return;
  708. }
  709. if (model.depth > 0 && model.children && model.children.length > 0) {
  710. try {
  711. this.graph.collapseItem(node);
  712. collapsedCount++;
  713. } catch (error) {
  714. console.error('折叠节点失败:', model.id, error);
  715. }
  716. }
  717. });
  718. // 重新渲染和适配视图
  719. this.graph.refresh();
  720. this.graph.fitView(12);
  721. }
  722. resizeGraph() {
  723. if (!this.graph) return;
  724. const container = document.getElementById(this.containerId);
  725. if (!container) return;
  726. this.graph.changeSize(container.clientWidth, container.clientHeight);
  727. this.graph.fitView(12);
  728. }
  729. setMasteryData(payload = {}) {
  730. this.masteryData = this.normalizeMasteryPayload(payload);
  731. this.masteryCache = {};
  732. this.logMasteryCoverage();
  733. }
  734. normalizeMasteryPayload(payload = {}) {
  735. // 支持 {masteries: []} / {data: []} / {Target: {KP: {...}}} / 直接的键值对
  736. const map = {};
  737. const addEntry = (entry, fallbackKey = null) => {
  738. if (!entry || typeof entry !== 'object') return;
  739. const code =
  740. entry.kp_code ||
  741. entry.code ||
  742. entry.id ||
  743. fallbackKey;
  744. if (!code) return;
  745. const masteryLevel = this.normalizeMasteryLevel(
  746. entry.mastery_level
  747. );
  748. map[code] = {
  749. ...entry,
  750. kp_code: code,
  751. mastery_level: masteryLevel,
  752. };
  753. };
  754. const normalizeCandidate = (candidate) => {
  755. if (!candidate) return;
  756. if (Array.isArray(candidate)) {
  757. candidate.forEach((item) => addEntry(item));
  758. return;
  759. }
  760. if (typeof candidate === 'object') {
  761. Object.entries(candidate).forEach(([key, value]) =>
  762. addEntry(value, key)
  763. );
  764. }
  765. };
  766. normalizeCandidate(payload.masteries);
  767. normalizeCandidate(payload.data);
  768. normalizeCandidate(payload.Target);
  769. // 允许直接传入键值对
  770. normalizeCandidate(payload);
  771. return map;
  772. }
  773. normalizeMasteryLevel(value) {
  774. const num = this.toNumber(value);
  775. if (!Number.isFinite(num)) return 0;
  776. return Math.max(0, Math.min(1, num));
  777. }
  778. toNumber(value) {
  779. const num = Number(value);
  780. return Number.isFinite(num) ? num : 0;
  781. }
  782. repaintNodes() {
  783. if (!this.graph || !this.treeData) return;
  784. const nodeMap = {};
  785. const walk = (node) => {
  786. if (!node) return;
  787. nodeMap[node.id] = node;
  788. (node.children || []).forEach((child) => walk(child));
  789. };
  790. walk(this.treeData);
  791. let updatedCount = 0;
  792. let firstUpdated = null;
  793. this.graph.getNodes().forEach((node) => {
  794. const id = node.getModel().id;
  795. const freshModel = nodeMap[id];
  796. if (!freshModel) return;
  797. // 确保 meta 中 has_mastery 等字段存在
  798. const masteryInfo =
  799. this.masteryData[id] ||
  800. this.masteryData[freshModel.meta?.code] ||
  801. null;
  802. freshModel.meta = {
  803. ...freshModel.meta,
  804. mastery_level: this.normalizeMasteryLevel(
  805. masteryInfo?.mastery_level ?? freshModel.meta?.mastery_level
  806. ),
  807. has_mastery: Boolean(masteryInfo),
  808. mastery_info: masteryInfo,
  809. total_attempts: this.toNumber(
  810. masteryInfo?.total_attempts ?? freshModel.meta?.total_attempts
  811. ),
  812. };
  813. this.graph.updateItem(node, freshModel);
  814. this.graph.refreshItem?.(node);
  815. this.applyDirectStyles(node, freshModel.meta.mastery_level, freshModel.meta.has_mastery);
  816. // 直接打上选中状态,避免样式被缓存
  817. if (freshModel.meta.has_mastery) {
  818. this.graph.setItemState(node, 'selected', true);
  819. } else {
  820. this.graph.clearItemStates(node, ['selected']);
  821. }
  822. updatedCount += 1;
  823. if (!firstUpdated) {
  824. firstUpdated = {
  825. id,
  826. mastery: freshModel.meta?.mastery_level,
  827. has_mastery: freshModel.meta?.has_mastery,
  828. };
  829. }
  830. });
  831. // 强制重绘,避免样式缓存
  832. this.graph.paint();
  833. }
  834. applyDirectStyles(node, mastery, hasMastery) {
  835. // 直接对关键 shape 赋色,避免 G6 缓存导致颜色不变
  836. const keyShape = node.getKeyShape?.();
  837. const group = node.getContainer?.();
  838. if (!keyShape || !group) return;
  839. const palette = (() => {
  840. if (!hasMastery) {
  841. return { fill: '#f8fafc', stroke: '#cbd5e1', card: '#ffffff' };
  842. }
  843. if (mastery >= 0.8) return { fill: '#fffbeb', stroke: '#d3b55f', card: '#ffffff' };
  844. if (mastery >= 0.6) return { fill: '#ecfdf3', stroke: '#34d399', card: '#ffffff' };
  845. if (mastery >= 0.4) return { fill: '#fffbeb', stroke: '#f59e0b', card: '#fff7ed' };
  846. return { fill: '#fef2f2', stroke: '#f87171', card: '#fff1f2' };
  847. })();
  848. keyShape.attr({
  849. fill: palette.fill,
  850. stroke: palette.stroke,
  851. });
  852. const card = group.find((e) => e.get?.('name') === 'card-shape');
  853. if (card) {
  854. card.attr({ fill: palette.card });
  855. }
  856. // 额外高亮轮廓,确保视觉可见
  857. this.graph.setItemState(node, 'selected', hasMastery);
  858. this.graph.refreshItem?.(node);
  859. }
  860. logMasteryCoverage() {
  861. if (!this.nodeIdSet || !this.nodeIdSet.size) return;
  862. const masteries = Object.keys(this.masteryData || {});
  863. if (!masteries.length) return;
  864. const missing = masteries.filter((id) => !this.nodeIdSet.has(id));
  865. if (missing.length) {
  866. console.warn(
  867. '掌握度返回的知识点未在图谱中找到:',
  868. missing.slice(0, 20),
  869. missing.length > 20 ? `...共${missing.length}条` : ''
  870. );
  871. }
  872. }
  873. buildParentMap(node, parentId = null) {
  874. if (!node) return;
  875. this.parentMap[node.id] = parentId;
  876. (node.children || []).forEach((child) =>
  877. this.buildParentMap(child, node.id)
  878. );
  879. }
  880. }
  881. // 定义KnowledgeMindmapGraph类,确保G6已加载
  882. function defineGraphClass() {
  883. if (typeof window.G6 === 'undefined') {
  884. setTimeout(defineGraphClass, 100);
  885. return;
  886. }
  887. window.KnowledgeMindmapGraph = KnowledgeMindmapGraph;
  888. }
  889. // 启动定义流程
  890. defineGraphClass();