knowledge-mindmap-graph.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  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: '#8C8986FF', lineDash: [8, 6], lineWidth: 1, label: '前置' },
  167. successor: { stroke: '#8C8986FF', lineDash: [8, 6], lineWidth: 1, label: '后继' },
  168. crosslink: { stroke: '#8c8a89', lineDash: [8, 6], lineWidth: 1, label: '跨联' },
  169. sibling: { stroke: '#8C8986FF', lineDash: [8, 6], lineWidth: 1, 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:mouseover', (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:mouseout', (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.zoom(2);
  618. this.graph.focusItem(item, true, {
  619. easing: 'easeCubic',
  620. duration: 500,
  621. });
  622. this.graph.setItemState(item, 'selected', true);
  623. }
  624. }
  625. refreshGraph() {
  626. if (!this.graph || !this.rawTree) return;
  627. this.masteryCache = {};
  628. this.treeData = this.transformNode(this.rawTree);
  629. this.buildParentMap(this.treeData);
  630. const flatIds = [];
  631. this.collectIds(this.treeData, flatIds);
  632. this.nodeIdSet = new Set(flatIds);
  633. this.logMasteryCoverage();
  634. this.applyUnlockRules(this.treeData);
  635. this.applyInitialCollapse(this.treeData);
  636. this.expandForMastery();
  637. // 强制全量重绘,确保 meta/颜色更新
  638. this.graph.clear();
  639. this.graph.data(this.treeData);
  640. this.graph.render();
  641. this.repaintNodes();
  642. this.graph.fitView(12);
  643. // 暴露实例便于调试(刷新后仍可用)
  644. window.KnowledgeMindmapGraphInstance = this;
  645. window.KnowledgeMindmapG6Graph = this.graph;
  646. this.clearRelationEdges();
  647. this.drawRelationEdges();
  648. this.applyNodeStates();
  649. this.startEdgeFlows();
  650. this.focusOnLowestMastery();
  651. this.graph.paint();
  652. this.setupFocusListener();
  653. }
  654. bindEdgeTooltip() {
  655. if (!this.graph) return;
  656. const tooltipEl = document.createElement('div');
  657. tooltipEl.style.position = 'fixed';
  658. tooltipEl.style.pointerEvents = 'none';
  659. tooltipEl.style.zIndex = '9999';
  660. tooltipEl.style.display = 'none';
  661. tooltipEl.style.background = 'rgba(15,23,42,0.95)';
  662. tooltipEl.style.color = '#e2e8f0';
  663. tooltipEl.style.padding = '8px 10px';
  664. tooltipEl.style.borderRadius = '8px';
  665. tooltipEl.style.boxShadow = '0 10px 30px rgba(0,0,0,0.18)';
  666. tooltipEl.style.fontSize = '12px';
  667. tooltipEl.style.lineHeight = '1.4';
  668. document.body.appendChild(tooltipEl);
  669. const show = (html, x, y) => {
  670. tooltipEl.innerHTML = html;
  671. tooltipEl.style.left = `${x + 12}px`;
  672. tooltipEl.style.top = `${y + 12}px`;
  673. tooltipEl.style.display = 'block';
  674. };
  675. const hide = () => {
  676. tooltipEl.style.display = 'none';
  677. };
  678. const buildHtml = (model) => {
  679. return `
  680. <div style="font-weight:700;font-size:13px;margin-bottom:4px;">${model.label || '关联'}</div>
  681. <div style="font-size:12px;">${model.source || ''} → ${model.target || ''}</div>
  682. ${model.comment ? `<div style="font-size:11px;color:#cbd5e1;margin-top:4px;white-space:pre-line;">${model.comment}</div>` : ''}
  683. `;
  684. };
  685. this.graph.on('edge:mouseenter', (evt) => {
  686. const model = evt?.item?.getModel?.() || {};
  687. const { clientX, clientY } = evt;
  688. show(buildHtml(model), clientX, clientY);
  689. });
  690. this.graph.on('edge:mouseleave', () => hide());
  691. }
  692. redrawRelationEdges() {
  693. this.clearRelationEdges();
  694. this.drawRelationEdges();
  695. }
  696. forceCollapseNodes() {
  697. if (!this.graph) return;
  698. }
  699. handleNodeClick(evt) {
  700. if (this.clickTimer) {
  701. clearTimeout(this.clickTimer);
  702. this.clickTimer = null;
  703. }
  704. this.clickTimer = setTimeout(() => {
  705. const model = evt.item?.getModel();
  706. if (!model) return;
  707. // if (model.locked) return;
  708. this.graph.getNodes().forEach((node) => {
  709. this.graph.clearItemStates(node);
  710. });
  711. this.graph.setItemState(evt.item, 'selected', true);
  712. this.flashNode(evt.item);
  713. if (this.emitSelection) {
  714. this.notifySelection(model);
  715. }
  716. this.showTooltip(evt, model);
  717. }, this.clickDelay);
  718. }
  719. focusNodeById(nodeId) {
  720. if (!this.graph || !nodeId) return;
  721. // 展开到目标节点
  722. this.expandAncestors(nodeId);
  723. this.graph.layout?.();
  724. this.redrawRelationEdges();
  725. const target = this.graph.findById(nodeId);
  726. if (!target) return;
  727. this.graph.getNodes().forEach((node) => {
  728. this.graph.clearItemStates(node);
  729. });
  730. this.graph.setItemState(target, 'selected', true);
  731. this.flashNode(target);
  732. this.graph.focusItem(target, true, { duration: 400, easing: 'easeCubic' });
  733. this.graph.paint();
  734. }
  735. expandAncestors(nodeId) {
  736. let cur = nodeId;
  737. while (cur) {
  738. const parentId = this.parentMap[cur];
  739. if (parentId && this.graph.findById(parentId)) {
  740. this.graph.updateItem(this.graph.findById(parentId), { collapsed: false });
  741. }
  742. cur = parentId;
  743. }
  744. }
  745. setupFocusListener() {
  746. if (this.focusListener) {
  747. window.removeEventListener('mindmap-focus-node', this.focusListener);
  748. }
  749. this.focusListener = (evt) => {
  750. const targetId = evt.detail?.id || evt.detail || null;
  751. if (!targetId) return;
  752. this.focusNodeById(targetId);
  753. };
  754. window.addEventListener('mindmap-focus-node', this.focusListener);
  755. }
  756. forceCollapse() {
  757. if (!this.graph) {
  758. setTimeout(() => this.forceCollapse(), 200);
  759. return;
  760. }
  761. const nodes = this.graph.getNodes();
  762. let collapsedCount = 0;
  763. nodes.forEach(node => {
  764. const model = node.getModel();
  765. // 折叠除根节点外的所有有子节点的节点
  766. if (
  767. this.masteryData[model.id] ||
  768. (model.meta && this.masteryData[model.meta.code])
  769. ) {
  770. model.collapsed = false;
  771. return;
  772. }
  773. if (model.depth > 0 && model.children && model.children.length > 0) {
  774. try {
  775. this.graph.collapseItem(node);
  776. collapsedCount++;
  777. } catch (error) {
  778. console.error('折叠节点失败:', model.id, error);
  779. }
  780. }
  781. });
  782. // 重新渲染和适配视图
  783. this.graph.refresh();
  784. this.graph.fitView(12);
  785. }
  786. resizeGraph() {
  787. if (!this.graph) return;
  788. const container = document.getElementById(this.containerId);
  789. if (!container) return;
  790. this.graph.changeSize(container.clientWidth, container.clientHeight);
  791. this.graph.fitView(12);
  792. }
  793. setMasteryData(payload = {}) {
  794. this.masteryData = this.normalizeMasteryPayload(payload);
  795. this.masteryCache = {};
  796. this.logMasteryCoverage();
  797. }
  798. normalizeMasteryPayload(payload = {}) {
  799. // 支持 {masteries: []} / {data: []} / {Target: {KP: {...}}} / 直接的键值对
  800. const map = {};
  801. const addEntry = (entry, fallbackKey = null) => {
  802. if (!entry || typeof entry !== 'object') return;
  803. const code =
  804. entry.kp_code ||
  805. entry.code ||
  806. entry.id ||
  807. fallbackKey;
  808. if (!code) return;
  809. const masteryLevel = this.normalizeMasteryLevel(
  810. entry.mastery_level
  811. );
  812. map[code] = {
  813. ...entry,
  814. kp_code: code,
  815. mastery_level: masteryLevel,
  816. };
  817. };
  818. const normalizeCandidate = (candidate) => {
  819. if (!candidate) return;
  820. if (Array.isArray(candidate)) {
  821. candidate.forEach((item) => addEntry(item));
  822. return;
  823. }
  824. if (typeof candidate === 'object') {
  825. Object.entries(candidate).forEach(([key, value]) =>
  826. addEntry(value, key)
  827. );
  828. }
  829. };
  830. normalizeCandidate(payload.masteries);
  831. normalizeCandidate(payload.data);
  832. normalizeCandidate(payload.Target);
  833. // 允许直接传入键值对
  834. normalizeCandidate(payload);
  835. return map;
  836. }
  837. normalizeMasteryLevel(value) {
  838. const num = this.toNumber(value);
  839. if (!Number.isFinite(num)) return 0;
  840. return Math.max(0, Math.min(1, num));
  841. }
  842. toNumber(value) {
  843. const num = Number(value);
  844. return Number.isFinite(num) ? num : 0;
  845. }
  846. repaintNodes() {
  847. if (!this.graph || !this.treeData) return;
  848. const nodeMap = {};
  849. const walk = (node) => {
  850. if (!node) return;
  851. nodeMap[node.id] = node;
  852. (node.children || []).forEach((child) => walk(child));
  853. };
  854. walk(this.treeData);
  855. let updatedCount = 0;
  856. let firstUpdated = null;
  857. this.graph.getNodes().forEach((node) => {
  858. const id = node.getModel().id;
  859. const freshModel = nodeMap[id];
  860. if (!freshModel) return;
  861. // 确保 meta 中 has_mastery 等字段存在
  862. const masteryInfo =
  863. this.masteryData[id] ||
  864. this.masteryData[freshModel.meta?.code] ||
  865. null;
  866. freshModel.meta = {
  867. ...freshModel.meta,
  868. mastery_level: this.normalizeMasteryLevel(
  869. masteryInfo?.mastery_level ?? freshModel.meta?.mastery_level
  870. ),
  871. has_mastery: Boolean(masteryInfo),
  872. mastery_info: masteryInfo,
  873. total_attempts: this.toNumber(
  874. masteryInfo?.total_attempts ?? freshModel.meta?.total_attempts
  875. ),
  876. };
  877. this.graph.updateItem(node, freshModel);
  878. this.graph.refreshItem?.(node);
  879. this.applyDirectStyles(node, freshModel.meta.mastery_level, freshModel.meta.has_mastery);
  880. // 直接打上选中状态,避免样式被缓存
  881. if (freshModel.meta.has_mastery) {
  882. this.graph.setItemState(node, 'selected', true);
  883. } else {
  884. this.graph.clearItemStates(node, ['selected']);
  885. }
  886. updatedCount += 1;
  887. if (!firstUpdated) {
  888. firstUpdated = {
  889. id,
  890. mastery: freshModel.meta?.mastery_level,
  891. has_mastery: freshModel.meta?.has_mastery,
  892. };
  893. }
  894. });
  895. // 强制重绘,避免样式缓存
  896. this.graph.paint();
  897. }
  898. applyDirectStyles(node, mastery, hasMastery) {
  899. // 直接对关键 shape 赋色,避免 G6 缓存导致颜色不变
  900. const keyShape = node.getKeyShape?.();
  901. const group = node.getContainer?.();
  902. if (!keyShape || !group) return;
  903. const palette = (() => {
  904. if (!hasMastery) {
  905. return { fill: '#f8fafc', stroke: '#cbd5e1', card: '#ffffff' };
  906. }
  907. if (mastery >= 0.8) return { fill: '#fffbeb', stroke: '#d3b55f', card: '#ffffff' };
  908. if (mastery >= 0.6) return { fill: '#ecfdf3', stroke: '#34d399', card: '#ffffff' };
  909. if (mastery >= 0.4) return { fill: '#fffbeb', stroke: '#f59e0b', card: '#fff7ed' };
  910. return { fill: '#fef2f2', stroke: '#f87171', card: '#fff1f2' };
  911. })();
  912. keyShape.attr({
  913. fill: palette.fill,
  914. stroke: palette.stroke,
  915. });
  916. const card = group.find((e) => e.get?.('name') === 'card-shape');
  917. if (card) {
  918. card.attr({ fill: palette.card });
  919. }
  920. // 额外高亮轮廓,确保视觉可见
  921. this.graph.setItemState(node, 'selected', hasMastery);
  922. this.graph.refreshItem?.(node);
  923. }
  924. logMasteryCoverage() {
  925. if (!this.nodeIdSet || !this.nodeIdSet.size) return;
  926. const masteries = Object.keys(this.masteryData || {});
  927. if (!masteries.length) return;
  928. const missing = masteries.filter((id) => !this.nodeIdSet.has(id));
  929. if (missing.length) {
  930. console.warn(
  931. '掌握度返回的知识点未在图谱中找到:',
  932. missing.slice(0, 20),
  933. missing.length > 20 ? `...共${missing.length}条` : ''
  934. );
  935. }
  936. }
  937. buildParentMap(node, parentId = null) {
  938. if (!node) return;
  939. this.parentMap[node.id] = parentId;
  940. (node.children || []).forEach((child) =>
  941. this.buildParentMap(child, node.id)
  942. );
  943. }
  944. }
  945. // 定义KnowledgeMindmapGraph类,确保G6已加载
  946. function defineGraphClass() {
  947. if (typeof window.G6 === 'undefined') {
  948. setTimeout(defineGraphClass, 100);
  949. return;
  950. }
  951. window.KnowledgeMindmapGraph = KnowledgeMindmapGraph;
  952. }
  953. // 启动定义流程
  954. defineGraphClass();