knowledge-mindmap-graph.js 29 KB

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