knowledge-mindmap-graph.js 35 KB

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