knowledge-mindmap-graph.js 37 KB

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