knowledge-mindmap-graph.js 37 KB

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