Skip to content

Commit fd2a5ef

Browse files
committed
nav.js: restore CM highlighting, fix double render with insertBefore+hide
1 parent 661f843 commit fd2a5ef

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

assets/nav.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,55 @@
9797
}
9898

9999

100+
// CodeMirror syntax highlighting on reference/example pages
101+
if (document.querySelector('.syntax-block, .impl-block')) {
102+
const CDNJS = 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16';
103+
function loadScript(src, cb) {
104+
const s = document.createElement('script'); s.src = src;
105+
s.onload = cb; document.head.appendChild(s);
106+
}
107+
function loadLink(href) {
108+
const l = document.createElement('link');
109+
l.rel = 'stylesheet'; l.href = href;
110+
document.head.appendChild(l);
111+
}
112+
loadLink(CDNJS + '/codemirror.min.css');
113+
loadLink(SITE + '/assets/cppmode-theme.css');
114+
loadScript(CDNJS + '/codemirror.min.js', function() {
115+
loadScript(CDNJS + '/mode/clike/clike.min.js', function() {
116+
loadScript(SITE + '/assets/cppmode-keywords.js', function() {
117+
loadScript(SITE + '/assets/cppmode.js', function() {
118+
const dark = document.body.classList.contains('dark-mode');
119+
document.querySelectorAll('.syntax-block, .impl-block').forEach(el => {
120+
if (!el.parentNode) return;
121+
const code = el.textContent.trim();
122+
if (!code) return;
123+
// Hide original first
124+
el.style.display = 'none';
125+
const wrap = document.createElement('div');
126+
el.parentNode.insertBefore(wrap, el);
127+
const cm = CodeMirror(wrap, {
128+
value: code,
129+
mode: 'cppmode',
130+
theme: dark ? 'cppmode-dark' : 'cppmode',
131+
readOnly: true,
132+
lineNumbers: false,
133+
lineWrapping: false,
134+
});
135+
cm.setSize('100%', 'auto');
136+
cm.getWrapperElement().style.height = 'auto';
137+
cm.getScrollerElement().style.overflowY = 'visible';
138+
});
139+
// Switch theme on dark toggle
140+
document.querySelectorAll('.CodeMirror').forEach(el => {
141+
if (el.CodeMirror) el.CodeMirror.setOption('theme', dark ? 'cppmode-dark' : 'cppmode');
142+
});
143+
});
144+
});
145+
});
146+
});
147+
}
148+
100149
// Dark mode via CSS class
101150
(function() {
102151
if (!document.getElementById('dark-mode-style')) {

0 commit comments

Comments
 (0)