-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate-script.js
More file actions
245 lines (226 loc) · 9.76 KB
/
Copy pathtemplate-script.js
File metadata and controls
245 lines (226 loc) · 9.76 KB
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
// ═════════════════════════════════════════════════════════
// 模板:HTML_Template-v3.15.0
// ═════════════════════════════════════════════════════════
// Ctrl+S 保存下载
document.addEventListener('keydown', function(e) {
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault();
var clone = document.documentElement.cloneNode(true);
clone.querySelectorAll('[contenteditable]').forEach(function(el) {
el.removeAttribute('contenteditable');
});
clone.querySelectorAll('#fmt-bar').forEach(function(el) {
el.remove();
});
var html = '<!DOCTYPE html>\n' + clone.outerHTML;
var blob = new Blob([html], { type: 'text/html;charset=utf-8' });
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
var title = document.getElementById('doc-title');
var version = document.getElementById('doc-version');
var filename = (title ? title.textContent.trim() : 'document');
if (version) filename += '-' + version.textContent.trim();
filename += '.html';
a.download = filename.replace(/[^a-zA-Z0-9\u4e00-\u9fff._-]/g, '_');
a.click();
URL.revokeObjectURL(a.href);
}
});
// ═══════════════════════════════════════════════════════════
// 【目录滚动高亮】scroll 驱动 + IntersectionObserver 加速
// ═══════════════════════════════════════════════════════════
// 策略:scroll 事件为主驱动(用 getBoundingClientRect 实时计算),
// observer 只作为 scroll 之前的快速预响应,不参与高亮决策。
// 根因:observer 的 intersectingIds 在长文档底部/快速滚动时会过时,
// 依赖它做决策导致高亮乱跳或卡住。
(function() {
window.addEventListener('DOMContentLoaded', function() {
var tocLinks = document.querySelectorAll('#toc-nav a[data-section]');
if (tocLinks.length === 0) return;
var sections = [];
tocLinks.forEach(function(link) {
var secId = link.getAttribute('data-section');
var el = document.getElementById(secId);
if (el) sections.push({ id: secId, el: el, link: link });
});
if (sections.length === 0) return;
// 当前高亮的章节 id
var activeId = null;
// 点击滚动锁定
var clickScrollLock = false;
var clickScrollTimer = null;
// 核心:根据当前滚动位置,计算应该高亮哪个章节
// 规则:取已滚过视口顶部(top<=40)的最后一个(DOM顺序最下);
// 没有则取视口内top最小的;都没有则取第一个。
function computeActive() {
// 策略:找"当前阅读位置对应的章节"
// 1. 已滚过视口顶部的章节(top<=0)中,取 DOM 顺序最后一个
// 2. 如果没有滚过顶部的,取视口内 top 最小(最靠近顶部)的
// 3. 都没有(页面顶部以上),取第一个
var aboveTop = [];
var inView = [];
var viewportHeight = window.innerHeight;
sections.forEach(function(s) {
var rect = s.el.getBoundingClientRect();
if (rect.top <= 0) {
aboveTop.push(s);
}
if (rect.top < viewportHeight && rect.bottom > 0) {
inView.push(s);
}
});
if (aboveTop.length > 0) {
return aboveTop[aboveTop.length - 1].id;
}
if (inView.length > 0) {
return inView[0].id;
}
// 页面顶部:所有section都在视口下方
return sections[0].id;
}
function setActive(id) {
if (id === activeId) return; // 无变化,跳过
activeId = id;
tocLinks.forEach(function(l) { l.classList.remove('active'); });
var link = document.querySelector('#toc-nav a[data-section="' + id + '"]');
if (link) {
link.classList.add('active');
// 确保高亮项在目录栏可见
link.scrollIntoView({ block: 'nearest', behavior: 'instant' });
}
}
function updateHighlight() {
if (clickScrollLock) return;
var id = computeActive();
if (id) setActive(id);
}
// IntersectionObserver:只在 scroll 事件之前预响应,加速感知
var observer = new IntersectionObserver(function() {
// observer 回调时直接用 getBoundingClientRect 计算,
// 不依赖 intersectingIds
updateHighlight();
}, { rootMargin: '-20px 0px -80% 0px', threshold: 0 });
sections.forEach(function(s) { observer.observe(s.el); });
// 点击目录跳转
tocLinks.forEach(function(link) {
link.addEventListener('click', function(e) {
e.preventDefault();
var secId = link.getAttribute('data-section');
var target = document.getElementById(secId);
if (target) {
// 立即高亮目标章节,不经过 computeActive
activeId = secId;
tocLinks.forEach(function(l) { l.classList.remove('active'); });
link.classList.add('active');
link.scrollIntoView({ block: 'nearest', behavior: 'instant' });
// 跳转
target.scrollIntoView({ behavior: 'instant', block: 'start' });
// 锁定:防止跳转后的 scroll/observer 回调覆盖高亮
clickScrollLock = true;
clearTimeout(clickScrollTimer);
clickScrollTimer = setTimeout(function() {
clickScrollLock = false;
}, 300);
}
});
});
// 初始高亮
updateHighlight();
// scroll 事件:主驱动(监听 #main-content 容器,非 window)
var scrollRaf = null;
var scrollContainer = document.getElementById('main-content') || window;
scrollContainer.addEventListener('scroll', function() {
if (clickScrollLock) return;
if (scrollRaf) return;
scrollRaf = requestAnimationFrame(function() {
scrollRaf = null;
updateHighlight();
});
}, { passive: true });
// Bug fix C: 目录区滚动穿透阻止
// 当 nav 滚到顶部/底部边界时,阻止 wheel 事件穿透到正文
var tocNav = document.querySelector('#toc-sidebar nav');
if (tocNav) {
tocNav.addEventListener('wheel', function(e) {
var scrollTop = tocNav.scrollTop;
var scrollHeight = tocNav.scrollHeight;
var clientHeight = tocNav.clientHeight;
var atTop = scrollTop <= 0;
var atBottom = scrollTop + clientHeight >= scrollHeight - 1;
// 向下滚且到底,或向上滚且到顶 → 阻止穿透
if ((e.deltaY > 0 && atBottom) || (e.deltaY < 0 && atTop)) {
e.preventDefault();
}
}, { passive: false });
}
});
})();
if (typeof mermaid !== 'undefined') mermaid.initialize({
startOnLoad: true,
theme: 'base',
themeVariables: {
primaryColor: '#e8f0fe',
primaryTextColor: '#1a1a1a',
primaryBorderColor: '#90b4e0',
lineColor: '#5b8abf',
fontFamily: '-apple-system, "Microsoft YaHei", sans-serif',
fontSize: '13px',
nodeBorder: '#90b4e0'
},
flowchart: { curve: 'basis', padding: 8, nodeSpacing: 30, rankSpacing: 35 }
});
// 初始化 WaveDrom
function initWaveDrom() {
if (typeof WaveDrom === 'undefined') return;
try {
WaveDrom.ProcessAll();
} catch(e) {
console.warn('WaveDrom 渲染失败:', e);
}
}
// WaveDrom 需要等 SVG 渲染容器就绪
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function() { setTimeout(initWaveDrom, 100); });
} else {
setTimeout(initWaveDrom, 100);
}
// 【格式栏】高亮 / 取消
(function() {
var style = document.createElement('style');
style.textContent = '.hl{background:#fff3a8;color:#c0392b;font-size:110%;font-weight:700}#fmt-bar button{border:none;background:none;font-size:14px;padding:3px 8px;cursor:default;border-radius:3px}#fmt-bar button:hover{background:#eee}';
document.head.appendChild(style);
var bar = document.createElement('div');
bar.id = 'fmt-bar';
bar.innerHTML = '<button id="hl-btn">高亮</button><button id="hl-cancel">取消</button>';
bar.style.cssText = 'position:fixed;display:none;background:#fff;border:1px solid #ccc;border-radius:6px;padding:4px 6px;box-shadow:0 2px 8px rgba(0,0,0,.15);z-index:9999;gap:4px;';
document.body.appendChild(bar);
document.addEventListener('mousedown', function(e) { if (!bar.contains(e.target)) bar.style.display = 'none'; });
bar.addEventListener('mousedown', function(e) { e.preventDefault(); });
var savedRange = null;
document.addEventListener('selectionchange', function() {
var s = window.getSelection();
if (!s || s.isCollapsed) { bar.style.display = 'none'; savedRange = null; return; }
savedRange = s.getRangeAt(0).cloneRange();
var r = s.getRangeAt(0).getBoundingClientRect();
bar.style.display = 'flex';
bar.style.left = (r.left + r.width / 2 - 40) + 'px';
bar.style.top = (r.top - 36) + 'px';
});
document.getElementById('hl-btn').addEventListener('click', function() {
if (!savedRange) return;
var span = document.createElement('span');
span.className = 'hl';
span.appendChild(savedRange.extractContents());
savedRange.insertNode(span);
window.getSelection().removeAllRanges();
bar.style.display = 'none';
});
document.getElementById('hl-cancel').addEventListener('click', function() {
if (!savedRange) return;
var node = savedRange.commonAncestorContainer;
var el = node.nodeType === 1 ? node : node.parentElement;
var hl = el.closest('.hl');
if (hl) { hl.replaceWith(...hl.childNodes); }
bar.style.display = 'none';
});
})();