1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
| //- 思维导图功能:配置注入 + 核心引擎 if theme.mindmap && theme.mindmap.enable script(data-pjax). // 思维导图配置 window.MINDMAP_CONFIG = { enable: true, d3Cdn: '!{theme.mindmap.d3_cdn}', libCdn: '!{theme.mindmap.lib_cdn}', viewCdn: '!{theme.mindmap.view_cdn}', icon: '!{theme.mindmap.icon || "fa-sitemap"}', options: !{JSON.stringify(theme.mindmap.options || {})}, fullscreen: !{JSON.stringify(theme.mindmap.fullscreen || {})}, export: !{JSON.stringify(theme.mindmap.export || {})} };
// MindmapEngine 核心类(防止 PJAX 重复声明) if (typeof window.MindmapEngine === 'undefined') { window.MindmapEngine = class MindmapEngine { constructor() { this.state = { rendered: false, visible: false, fullscreen: false, markmapLoaded: false }; this.cache = { treeData: null, svgElement: null, markmap: null }; this.modal = document.getElementById('mindmap-modal'); this.container = document.getElementById('mindmap-svg-container'); this.bindEvents(); }
// 提取文章标题并转换为 Markdown 格式(修复层级) extractHeadingsAsMarkdown() { const articleContainer = document.getElementById('article-container'); if (!articleContainer) return ''; const headings = Array.from(articleContainer.querySelectorAll('h1, h2, h3, h4, h5, h6')); if (headings.length === 0) return ''; // 初始化 idMap if (!this.idMap) this.idMap = new Map(); // 找到最小的标题层级作为根节点层级 const minLevel = Math.min(...headings.map(h => parseInt(h.tagName[1]))); // 构建 Markdown - 从根节点开始 let markdown = `# ${window.postData.title || '文章目录'}\n\n`; headings.forEach(h => { const level = parseInt(h.tagName[1]); const text = h.textContent.trim(); const id = h.id || ''; // 调整层级:最小层级变为 ## (二级),依此类推 const adjustedLevel = level - minLevel + 2; markdown += '#'.repeat(adjustedLevel) + ' ' + text + '\n'; // 保存 ID 映射关系 this.idMap.set(text, id); }); console.log('[Mindmap] Generated markdown:', markdown); return markdown; }
// 加载脚本辅助函数 loadScript(src) { return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = src; script.onload = resolve; script.onerror = () => reject(new Error(`Failed to load ${src}`)); document.head.appendChild(script); }); }
// 加载 Markmap 所有依赖 async loadMarkmap() { if (this.state.markmapLoaded && window.markmap) { return; }
try { // 1. 加载 D3 if (!window.d3) { await this.loadScript(window.MINDMAP_CONFIG.d3Cdn); }
// 2. 加载 markmap-lib (包含 Transformer) if (!window.markmap || !window.markmap.Transformer) { await this.loadScript(window.MINDMAP_CONFIG.libCdn); }
// 3. 加载 markmap-view (包含 Markmap) if (!window.markmap || !window.markmap.Markmap) { await this.loadScript(window.MINDMAP_CONFIG.viewCdn); }
this.state.markmapLoaded = true; } catch (error) { console.error('[Mindmap] Failed to load libraries:', error); throw error; } }
// 显示思维导图 async show() { if (this.state.rendered && this.cache.markmap) { // 显示缓存 this.showCached(); return; }
// 首次渲染 await this.firstRender(); }
// 首次渲染 async firstRender() { try { // 显示加载状态 this.showLoading();
// 提取标题为 Markdown 格式 const markdown = this.extractHeadingsAsMarkdown(); if (!markdown || markdown.trim().length === 0) { this.showEmptyState(); return; }
// 加载 Markmap 库 await this.loadMarkmap();
// 使用 Transformer 转换 Markdown const { Transformer, Markmap } = window.markmap; const transformer = new Transformer(); const { root, features } = transformer.transform(markdown);
// 缓存转换后的数据 this.cache.treeData = root;
// 渲染思维导图 const options = { duration: window.MINDMAP_CONFIG.options?.duration || 500, maxWidth: window.MINDMAP_CONFIG.options?.maxWidth || 300, embedGlobalCSS: false };
this.cache.markmap = Markmap.create(this.container, options, root);
// 缓存 SVG (容器本身就是 svg) setTimeout(() => { this.cache.svgElement = this.container.cloneNode(true); }, 600);
this.state.rendered = true; this.hideLoading();
} catch (error) { console.error('[Mindmap] Render failed:', error); anzhiyu.snackbarShow('思维导图加载失败: ' + error.message, false, 3000); this.hideModal(); } }
// 显示缓存 showCached() { this.showModal(); if (this.cache.markmap) { this.cache.markmap.fit(); } }
// 节点点击功能已移除(保持简洁)
// 显示/隐藏 Modal showModal() { this.modal.style.display = 'flex'; setTimeout(() => this.modal.classList.add('show'), 10); this.state.visible = true; document.body.style.overflow = 'hidden'; }
hideModal() { this.modal.classList.remove('show'); setTimeout(() => { this.modal.style.display = 'none'; document.body.style.overflow = ''; }, 300); this.state.visible = false; this.state.fullscreen = false; this.modal.classList.remove('fullscreen'); }
// 加载/空状态 showLoading() { const loading = document.createElement('div'); loading.className = 'mindmap-loading'; loading.innerHTML = '<i class="fas fa-spinner fa-spin"></i><p>正在生成思维导图...</p>'; this.container.appendChild(loading); }
hideLoading() { const loading = this.container.querySelector('.mindmap-loading'); if (loading) loading.remove(); }
showEmptyState() { document.querySelector('.mindmap-empty-state').style.display = 'block'; this.hideLoading(); }
// 全屏切换 toggleFullscreen() { if (!this.state.fullscreen) { this.modal.classList.add('fullscreen'); this.state.fullscreen = true; const btn = document.getElementById('mindmap-btn-fullscreen'); if (btn) btn.querySelector('i').className = 'fas fa-compress'; } else { this.modal.classList.remove('fullscreen'); this.state.fullscreen = false; const btn = document.getElementById('mindmap-btn-fullscreen'); if (btn) btn.querySelector('i').className = 'fas fa-expand'; } if (this.cache.markmap) { setTimeout(() => this.cache.markmap.fit(), 100); } }
// 导出 SVG exportAsSVG() { if (!this.cache.svgElement) { anzhiyu.snackbarShow('请先打开思维导图', false, 2000); return; }
const svgData = new XMLSerializer().serializeToString(this.cache.svgElement); const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' }); this.downloadBlob(svgBlob, this.getExportFilename('svg')); }
// PNG 导出已移除(跨域限制)
// 下载文件 downloadBlob(blob, filename) { const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = filename; link.click(); URL.revokeObjectURL(link.href); anzhiyu.snackbarShow('导出成功', false, 2000); }
// 生成导出文件名 getExportFilename(format) { const template = window.MINDMAP_CONFIG.export.filename_format || '{title}-mindmap'; const filename = template.replace('{title}', window.postData.title || 'mindmap'); return `${filename}.${format}`; }
// 缩放控制已移除(Markmap 支持鼠标滚轮缩放和拖拽)
// 绑定事件 bindEvents() { // 检查 modal 是否存在 if (!this.modal || !this.container) { console.warn('[Mindmap] Modal elements not found, skipping initialization'); return; }
// 按钮点击 const mindmapBtn = document.getElementById('mindmap-btn'); if (mindmapBtn) { mindmapBtn.addEventListener('click', () => { this.showModal(); this.show(); }); }
// 关闭按钮 const closeBtn = document.getElementById('mindmap-btn-close'); if (closeBtn) { closeBtn.addEventListener('click', () => this.hideModal()); }
// 遮罩层点击 const overlay = this.modal.querySelector('.mindmap-overlay'); if (overlay) { overlay.addEventListener('click', () => this.hideModal()); }
// 全屏按钮 const fullscreenBtn = document.getElementById('mindmap-btn-fullscreen'); if (fullscreenBtn) { fullscreenBtn.addEventListener('click', () => this.toggleFullscreen()); }
// 导出按钮(仅SVG) const exportBtn = document.getElementById('mindmap-btn-export'); if (exportBtn) { exportBtn.addEventListener('click', () => this.exportAsSVG()); }
// 缩放按钮已移除
// ESC 键关闭 document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && this.state.visible) { this.hideModal(); } }); }
// PJAX 清理 destroy() { if (this.cache.markmap) { this.cache.markmap.destroy && this.cache.markmap.destroy(); } this.state = { rendered: false, visible: false, fullscreen: false, markmapLoaded: false }; this.cache = { treeData: null, svgElement: null, markmap: null }; } }; }
// 初始化函数(PJAX 模式B:立即执行) function initMindmapFeature() { // 检查是否启用了思维导图功能 if (!window.postData || !window.postData.mindmap) { const mindmapBtn = document.getElementById('mindmap-btn'); if (mindmapBtn) { mindmapBtn.style.display = 'none'; mindmapBtn.dataset.mindmapEnabled = 'false'; } return; }
// 立即尝试初始化,如果元素不存在则重试 const modal = document.getElementById('mindmap-modal'); const container = document.getElementById('mindmap-svg-container'); if (!modal || !container) { console.log('[Mindmap] Modal not ready, retrying...'); setTimeout(initMindmapFeature, 50); return; }
// 显示按钮 const mindmapBtn = document.getElementById('mindmap-btn'); if (mindmapBtn) { mindmapBtn.style.display = 'block'; mindmapBtn.dataset.mindmapEnabled = 'true'; }
// 初始化引擎(防止重复初始化) if (!window.__mindmapEngine) { window.__mindmapEngine = new window.MindmapEngine(); console.log('[Mindmap] Engine initialized'); } }
// 立即执行初始化(关键!模仿 about 页面) initMindmapFeature();
// PJAX 清理钩子 if (typeof pjax !== 'undefined') { document.addEventListener('pjax:send', () => { if (window.__mindmapEngine) { window.__mindmapEngine.destroy(); window.__mindmapEngine = null; } }); }
|