knowledge-mindmap-graph.js 34 KB

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