| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568 |
- <x-filament::page>
- <div
- class="space-y-4"
- x-data="knowledgeMindmap()"
- x-init="initMindmap()"
- >
- <div class="rounded-lg border border-gray-200 bg-white p-4 shadow-sm">
- <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
- <div>
- <h2 class="text-lg font-semibold text-gray-900">初中数学知识图谱 · 思维导图</h2>
- <p class="text-sm text-gray-500">
- tree.json 提供完整层级(模块 → 知识点),edges.json 描述跨节点关系;基于 AntV G6 MindMap 布局,节点可逐层展开/折叠并叠加前置/后继/兄弟/联合连线。
- </p>
- <div class="mt-2 flex gap-4 text-xs text-gray-500">
- <div>节点总数:<span x-text="stats.nodes"></span></div>
- <div>跨边数量:<span x-text="stats.extraEdges"></span></div>
- </div>
- </div>
- <div class="flex flex-wrap gap-3 text-xs text-gray-600">
- <span class="inline-flex items-center gap-1">
- <span class="h-2 w-4 rounded-full bg-blue-500"></span> 前置
- </span>
- <span class="inline-flex items-center gap-1">
- <span class="h-2 w-4 rounded-full bg-red-500"></span> 后继
- </span>
- <span class="inline-flex items-center gap-1">
- <span class="h-2 w-4 rounded-full border border-dashed border-gray-500"></span> 兄弟
- </span>
- <span class="inline-flex items-center gap-1">
- <span class="h-2 w-4 rounded-full bg-yellow-400"></span> 联合考查
- </span>
- </div>
- </div>
- </div>
- <div
- id="knowledge-mindmap"
- class="h-[80vh] min-h-[720px] w-full rounded-lg border border-gray-200 bg-white"
- ></div>
- </div>
- </x-filament::page>
- @push('scripts')
- <script src="https://gw.alipayobjects.com/os/lib/antv/g6/5.0.18/dist/g6.min.js"></script>
- <script>
- document.addEventListener('alpine:init', () => {
- window.knowledgeMindmap = () => ({
- graph: null,
- treeData: null,
- relationEdges: [],
- stats: { nodes: 0, extraEdges: 0 },
- arrow(w = 12, h = 14, r = 5) {
- if (window.G6?.Arrow?.triangle) {
- return G6.Arrow.triangle(w, h, r);
- }
- return [
- ['M', 0, 0],
- ['L', w, h / 2],
- ['L', 0, h],
- ['Z'],
- ];
- },
- levelStyles: [
- {
- fill: '#0ea5e9',
- stroke: '#0369a1',
- labelColor: '#0f172a',
- fontSize: 17,
- fontWeight: 700,
- size: 34,
- },
- {
- fill: '#e0f2fe',
- stroke: '#38bdf8',
- labelColor: '#0f172a',
- fontSize: 16,
- fontWeight: 700,
- size: 30,
- },
- {
- fill: '#f1f5f9',
- stroke: '#cbd5e1',
- labelColor: '#0f172a',
- fontSize: 14,
- fontWeight: 600,
- size: 26,
- },
- ],
- relationStyles: {
- prerequisite: {
- type: 'quadratic',
- curveOffset: 60,
- style: {
- stroke: '#2563eb',
- lineWidth: 3.4,
- lineDash: [8, 6],
- endArrow: {
- path: null,
- fill: '#2563eb',
- d: 12,
- },
- startArrow: false,
- },
- label: '前置',
- },
- successor: {
- type: 'quadratic',
- curveOffset: 60,
- style: {
- stroke: '#dc2626',
- lineWidth: 3.4,
- lineDash: [8, 6],
- endArrow: {
- path: null,
- fill: '#dc2626',
- d: 12,
- },
- startArrow: false,
- },
- label: '后继',
- },
- sibling: {
- type: 'quadratic',
- curveOffset: 50,
- style: {
- stroke: '#64748b',
- lineDash: [6, 6],
- lineWidth: 3,
- endArrow: {
- path: null,
- fill: '#64748b',
- d: 10,
- },
- },
- label: '兄弟',
- },
- joint: {
- type: 'quadratic',
- curveOffset: 50,
- style: {
- stroke: '#fcd34d',
- lineWidth: 3,
- lineDash: [10, 8],
- endArrow: {
- path: null,
- fill: '#fbbf24',
- d: 10,
- },
- },
- label: '联合',
- },
- default: {
- type: 'quadratic',
- curveOffset: 50,
- style: {
- stroke: '#94a3b8',
- lineWidth: 3,
- lineDash: [10, 8],
- endArrow: {
- path: null,
- fill: '#94a3b8',
- d: 10,
- },
- },
- label: '',
- },
- },
- async initMindmap() {
- try {
- if (this.$nextTick) {
- await this.$nextTick();
- }
- if (!window.G6) {
- console.error('G6 未加载');
- return;
- }
- Object.keys(this.relationStyles).forEach((key) => {
- const rel = this.relationStyles[key];
- if (rel?.style && rel.style.endArrow && !rel.style.endArrow.path) {
- rel.style.endArrow.path = this.arrow(rel.style.endArrow.d || 10, (rel.style.endArrow.d || 10) + 2, 4);
- }
- });
- await this.loadData();
- this.applyInitialCollapse(this.treeData);
- this.renderGraph();
- window.addEventListener('resize', () => this.resizeGraph());
- } catch (err) {
- console.error('初始化思维导图失败', err);
- }
- },
- async loadData() {
- const [treeResp, edgesResp] = await Promise.all([
- fetch('/data/tree.json'),
- fetch('/data/edges.json'),
- ]);
- const rawTree = await treeResp.json();
- const edges = await edgesResp.json();
- const rawEdges = Array.isArray(edges) ? edges : edges?.edges || [];
- this.treeData = this.transformNode(rawTree);
- this.relationEdges = this.normalizeEdges(rawEdges);
- this.stats = {
- nodes: this.countNodes(this.treeData),
- extraEdges: this.relationEdges.length,
- };
- },
- transformNode(node, depth = 0) {
- if (!node) {
- return null;
- }
- const id = node.code || node.id || node.label || `node-${Math.random().toString(36).slice(2, 8)}`;
- const label = node.name || node.label || node.code || node.id || '未命名节点';
- const meta = {
- code: node.code || node.id || '',
- name: label,
- direct_score: node.direct_score || [],
- related_score: node.related_score || [],
- skills: node.skills || [],
- };
- return {
- id,
- label,
- meta,
- depth,
- children: (node.children || []).map((child) => this.transformNode(child, depth + 1)).filter(Boolean),
- };
- },
- applyInitialCollapse(node, depth = 0) {
- if (!node) {
- return;
- }
- if (depth >= 2 && node.children.length > 0) {
- node.collapsed = true;
- }
- node.children.forEach((child) => this.applyInitialCollapse(child, depth + 1));
- },
- countNodes(node) {
- if (!node) {
- return 0;
- }
- return 1 + node.children.reduce((sum, child) => sum + this.countNodes(child), 0);
- },
- normalizeEdges(rawEdges) {
- const seen = new Set();
- const normalized = [];
- (rawEdges || []).forEach((edge, index) => {
- if (!edge?.source || !edge?.target) {
- return;
- }
- const key = `${edge.source}-${edge.target}-${edge.type}`;
- if (seen.has(key)) {
- return;
- }
- seen.add(key);
- const relationStyle = this.relationStyles[edge.type] || this.relationStyles.default;
- normalized.push({
- id: `rel-${index}-${edge.source}-${edge.target}`,
- source: edge.source,
- target: edge.target,
- type: relationStyle.type || 'quadratic',
- curveOffset: relationStyle.curveOffset || 50,
- style: relationStyle.style,
- label: relationStyle.label,
- comment: edge.comment || edge.note || '',
- });
- });
- return normalized;
- },
- renderGraph(containerEl = null) {
- if (!this.treeData) {
- return;
- }
- const container = containerEl || document.getElementById('knowledge-mindmap');
- if (!container) {
- console.error('容器未找到');
- return;
- }
- const ensuredId = container.id || 'knowledge-mindmap';
- if (!container.id) {
- container.id = ensuredId;
- }
- const bounds = container.getBoundingClientRect();
- const width = Math.max(bounds.width, 600);
- const height = Math.max(bounds.height, 600);
- const tooltipEl = document.createElement('div');
- tooltipEl.className = 'fixed z-50 pointer-events-none hidden';
- document.body.appendChild(tooltipEl);
- const showTooltip = (html, x, y) => {
- tooltipEl.innerHTML = html;
- tooltipEl.style.left = `${x + 12}px`;
- tooltipEl.style.top = `${y + 12}px`;
- tooltipEl.classList.remove('hidden');
- };
- const hideTooltip = () => {
- tooltipEl.classList.add('hidden');
- tooltipEl.innerHTML = '';
- };
- const G6Lib = window.G6?.default || window.G6;
- const TreeGraphClass = G6Lib?.TreeGraph || null;
- if (!TreeGraphClass) {
- console.error('G6 TreeGraph 不可用');
- return;
- }
- const graphData = this.decorateTree(this.treeData);
- const graphConfig = {
- container: ensuredId,
- width,
- height,
- data: graphData,
- linkCenter: true,
- modes: {
- default: [
- 'drag-canvas',
- 'zoom-canvas',
- {
- type: 'collapse-expand',
- trigger: 'click',
- onChange: function onChange(item, collapsed) {
- if (!item) return;
- item.getModel().collapsed = collapsed;
- return true;
- },
- },
- ],
- },
- layout: {
- type: 'mindmap',
- direction: 'H',
- getHeight: () => 32,
- getWidth: () => 140,
- getVGap: () => 32,
- getHGap: () => 110,
- },
- defaultNode: {
- size: 22,
- style: {
- stroke: '#94a3b8',
- fill: '#fff',
- radius: 4,
- shadowColor: undefined,
- shadowBlur: 0,
- lineWidth: 3,
- },
- labelCfg: {
- style: {
- fontSize: 13,
- fill: '#0f172a',
- fontWeight: 500,
- },
- position: 'right',
- offset: 12,
- },
- },
- defaultEdge: {
- type: 'cubic-horizontal',
- style: {
- stroke: '#cbd5f5',
- lineWidth: 3,
- shadowBlur: 0,
- shadowColor: undefined,
- },
- },
- nodeStateStyles: {
- selected: {
- lineWidth: 3.2,
- stroke: '#2563eb',
- fill: '#e0f2fe',
- },
- },
- edgeStateStyles: {
- highlight: {
- lineWidth: 3.4,
- stroke: '#fb923c',
- },
- },
- plugins: [],
- };
- this.graph = new TreeGraphClass(graphConfig);
- if (typeof this.graph.data === 'function') {
- this.graph.data(graphData);
- } else if (typeof this.graph.changeData === 'function') {
- this.graph.changeData(graphData);
- }
- if (typeof this.graph.render === 'function') {
- this.graph.render();
- }
- this.graph.data(this.decorateTree(this.treeData));
- this.graph.render();
- this.graph.fitView(24);
- this.drawRelationEdges();
- this.bindEvents();
- this.graph.on('node:mouseenter', (evt) => {
- const { clientX, clientY } = evt;
- showTooltip(this.buildTooltip(evt?.item?.getModel()), clientX, clientY);
- });
- this.graph.on('node:mouseleave', hideTooltip);
- this.graph.on('edge:mouseenter', (evt) => {
- const model = evt?.item?.getModel() || {};
- const relation = model.label || '关联关系';
- const text = `${model.source || ''} → ${model.target || ''}`;
- const comment = model.comment ? `<div class="text-[11px] text-gray-600 mt-1 whitespace-pre-line">${model.comment}</div>` : '';
- const html = `
- <div class="rounded-md border border-gray-200 bg-white px-3 py-2 text-xs text-gray-700 shadow-md">
- <div class="font-semibold text-gray-900 mb-1">${relation}</div>
- <div>${text}</div>
- ${comment}
- </div>
- `;
- const { clientX, clientY } = evt;
- showTooltip(html, clientX, clientY);
- });
- this.graph.on('edge:mouseleave', hideTooltip);
- const canvas = this.graph && typeof this.graph.get === 'function' ? this.graph.get('canvas') : null;
- if (canvas && typeof canvas.set === 'function') {
- canvas.set('localRefresh', false);
- const ctx = typeof canvas.get === 'function' ? canvas.get('context') : null;
- if (ctx) {
- ctx.shadowColor = 'transparent';
- ctx.shadowBlur = 0;
- }
- }
- },
- decorateTree(node) {
- if (!node) {
- return null;
- }
- const { nodeStyle, labelCfg, size } = this.getNodeLevelStyle(node.depth);
- return {
- id: node.id,
- label: `${node.meta.code ? `${node.meta.code} · ` : ''}${node.label}`,
- meta: node.meta,
- collapsed: node.collapsed,
- depth: node.depth,
- size,
- style: nodeStyle,
- labelCfg,
- children: node.children.map((child) => this.decorateTree(child)).filter(Boolean),
- };
- },
- getNodeLevelStyle(depth = 0) {
- const style = this.levelStyles[depth] || this.levelStyles[this.levelStyles.length - 1];
- return {
- size: style.size || 22,
- nodeStyle: {
- fill: style.fill || '#fff',
- stroke: style.stroke || '#cbd5f5',
- lineWidth: 3,
- radius: 6,
- shadowColor: undefined,
- shadowBlur: 0,
- },
- labelCfg: {
- position: 'right',
- offset: 12,
- style: {
- fontSize: style.fontSize || 13,
- fontWeight: style.fontWeight || 600,
- fill: style.labelColor || '#0f172a',
- },
- },
- };
- },
- drawRelationEdges() {
- if (!this.graph || !this.relationEdges.length) {
- return;
- }
- this.relationEdges.forEach((edge, index) => {
- const style = { ...(edge.style || {}), lineAppendWidth: 14 };
- if (style.endArrow && !style.endArrow.path) {
- style.endArrow = {
- ...style.endArrow,
- path: this.arrow(style.endArrow.d || 10, (style.endArrow.d || 10) + 2, 4),
- };
- }
- this.graph.addItem('edge', {
- id: `extra-${index}`,
- source: edge.source,
- target: edge.target,
- type: edge.type || 'quadratic',
- curveOffset: edge.curveOffset || 50,
- style,
- label: edge.label,
- comment: edge.comment || '',
- labelCfg: {
- autoRotate: true,
- style: {
- fill: '#475569',
- fontSize: 11,
- background: {
- fill: 'rgba(255,255,255,0.85)',
- padding: [2, 4],
- radius: 4,
- },
- },
- },
- });
- });
- },
- buildTooltip(model) {
- const meta = model?.meta;
- if (!meta) {
- return '<div class="text-xs text-gray-600">无数据</div>';
- }
- const range = (value) => (value?.length ? `${value[0]}-${value[1]}` : '未配置');
- const skills = (meta.skills || [])
- .slice(0, 6)
- .map((skill) => `<li class="leading-snug">${skill.trim()}</li>`)
- .join('') || '<li>暂无技能</li>';
- return `
- <div class="min-w-[230px] max-w-sm rounded-md border border-gray-200 bg-white p-3 text-xs text-gray-700 shadow-lg">
- <div class="text-sm font-semibold text-gray-900 mb-1">${meta.code || model.id} · ${meta.name}</div>
- <div class="flex gap-3 text-xs">
- <span>直接:${range(meta.direct_score)}</span>
- <span>关联:${range(meta.related_score)}</span>
- </div>
- <div class="mt-2">
- <div class="font-medium">技能要点</div>
- <ul class="list-disc pl-5 space-y-0.5">
- ${skills}
- </ul>
- </div>
- </div>
- `;
- },
- bindEvents() {
- if (!this.graph) {
- return;
- }
- this.graph.on('node:click', (evt) => {
- const nodeId = evt?.item?.getID();
- if (nodeId) {
- this.highlightEdges(nodeId);
- }
- });
- this.graph.on('canvas:click', () => this.resetHighlight());
- },
- highlightEdges(nodeId) {
- this.graph.getNodes().forEach((node) => {
- this.graph.clearItemStates(node);
- if (node.getID() === nodeId) {
- this.graph.setItemState(node, 'selected', true);
- }
- });
- this.graph.getEdges().forEach((edge) => {
- const { source, target } = edge.getModel();
- const linked = source === nodeId || target === nodeId;
- if (linked) {
- this.graph.setItemState(edge, 'highlight', true);
- } else {
- this.graph.clearItemStates(edge);
- }
- });
- },
- resetHighlight() {
- if (!this.graph) return;
- this.graph.getNodes().forEach((node) => this.graph.clearItemStates(node));
- this.graph.getEdges().forEach((edge) => this.graph.clearItemStates(edge));
- },
- resizeGraph() {
- if (!this.graph) return;
- const container = document.getElementById('knowledge-mindmap');
- if (!container) return;
- this.graph.changeSize(container.clientWidth, container.clientHeight);
- this.graph.fitView(24);
- },
- });
- });
- </script>
- @endpush
|