-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
268 lines (243 loc) · 8.35 KB
/
Copy pathmain.js
File metadata and controls
268 lines (243 loc) · 8.35 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
const state = {
posts: [],
filtered: [],
active: null,
search: ''
};
const CONTENT_DIR = 'sessions';
const elements = {
postList: document.getElementById('post-list'),
postTitle: document.getElementById('post-title'),
postSummary: document.getElementById('post-summary'),
postContent: document.getElementById('post-content'),
tagList: document.getElementById('tag-list'),
search: document.getElementById('search'),
prev: document.getElementById('prev-post'),
next: document.getElementById('next-post'),
blockCount: document.getElementById('block-count'),
reader: document.querySelector('.reader')
};
let mathReady;
function ensureMathReady() {
if (mathReady) return mathReady;
mathReady = new Promise(resolve => {
const ensureScript = () => {
if (!document.getElementById('mathjax-script')) {
const s = document.createElement('script');
s.id = 'mathjax-script';
s.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js';
document.head.appendChild(s);
}
};
ensureScript();
const check = () => {
if (window.MathJax && typeof MathJax.typesetPromise === 'function') {
if (MathJax.startup && MathJax.startup.promise) {
MathJax.startup.promise.then(() => resolve(MathJax));
} else {
resolve(MathJax);
}
} else {
setTimeout(check, 50);
}
};
check();
});
return mathReady;
}
async function typesetContent() {
try {
await ensureMathReady();
await MathJax.typesetPromise([elements.postContent]);
} catch (err) {
console.error('MathJax typeset error', err);
}
}
async function init() {
try {
const manifest = await fetch('sessions/index.json').then(res => res.json());
const metas = await Promise.all(manifest.sessions.map(loadFrontmatter));
state.posts = metas
.filter(Boolean)
.sort((a, b) => {
const aNum = Number.isFinite(a.idNumber) ? a.idNumber : Number.MAX_SAFE_INTEGER;
const bNum = Number.isFinite(b.idNumber) ? b.idNumber : Number.MAX_SAFE_INTEGER;
if (aNum !== bNum) return aNum - bNum;
return String(a.id).localeCompare(String(b.id));
});
applyFilters();
const initial = state.filtered[0];
if (initial) {
selectPost(initial.id);
} else {
elements.postContent.textContent = 'No sessions found.';
}
elements.search.addEventListener('input', onSearch);
elements.prev.addEventListener('click', () => selectAdjacent(-1));
elements.next.addEventListener('click', () => selectAdjacent(1));
} catch (err) {
console.error(err);
elements.postContent.textContent = `Failed to load sessions: ${err.message}. If opened via file://, please run a local server or deploy to a static host.`;
}
}
async function fetchJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`${url} returned ${response.status}`);
}
return response.json();
}
async function fetchText(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`${url} returned ${response.status}`);
}
return response.text();
}
async function loadFrontmatter(entry) {
try {
const raw = await fetch(`sessions/${entry.file}`).then(res => res.text());
const parsed = parseFrontmatter(raw);
const idRaw = parsed.meta && parsed.meta.id !== undefined ? parsed.meta.id : null;
const idNumber = Number.isFinite(Number(idRaw)) ? Number(idRaw) : null;
const id = idRaw !== null && idRaw !== undefined ? String(idRaw) : '';
return {
...parsed.meta,
id,
idNumber,
file: entry.file,
content: parsed.content
};
} catch (err) {
console.error('Error loading', entry.file, err);
return null;
}
}
// Protect LaTeX math from marked.js by replacing with placeholders,
// parsing markdown, then restoring the original math strings.
function renderBlock(md) {
const stash = [];
// Display math $$...$$ (possibly multiline)
md = md.replace(/\$\$([\s\S]*?)\$\$/g, (match) => {
const key = `\x02MATH${stash.length}\x03`;
stash.push(match);
return key;
});
// Inline math $...$ (single line, non-greedy)
md = md.replace(/\$([^\$\n]+?)\$/g, (match) => {
const key = `\x02MATH${stash.length}\x03`;
stash.push(match);
return key;
});
let html = marked.parse(md, { mangle: false, headerIds: false });
// Restore math — also unwrap any <em> tags marked injected around _ inside placeholders
html = html.replace(/\x02MATH(\d+)\x03/g, (_, i) => stash[Number(i)]);
return html;
}
// A block = one self-contained unit that will later become one slide.
// Blocks are delimited in the markdown by a line containing only "---".
function splitBlocks(md) {
return md
.split(/\r?\n[ \t]*---[ \t]*\r?\n/)
.map(s => s.trim())
.filter(Boolean);
}
function parseFrontmatter(raw) {
if (raw.startsWith('---')) {
const end = raw.indexOf('---', 3);
if (end === -1) {
return { meta: {}, content: raw };
}
const yamlText = raw.slice(3, end).trim();
const meta = jsyaml.load(yamlText) || {};
const content = raw.slice(end + 3).trim();
return { meta, content };
}
return { meta: {}, content: raw };
}
function onSearch(e) {
state.search = e.target.value.toLowerCase();
applyFilters();
}
function applyFilters() {
state.filtered = state.posts.filter(p => {
const haystack = [p.title, p.summary, (p.tags || []).join(' '), (p.learning_goals || []).join(' ')].join(' ').toLowerCase();
const matchesSearch = haystack.includes(state.search);
return matchesSearch;
});
renderPostList();
}
function renderPostList() {
elements.postList.innerHTML = '';
state.filtered.forEach(p => {
const item = document.createElement('div');
item.className = 'post-item' + (state.active === p.id ? ' active' : '');
item.innerHTML = `
<div class="title">${p.title || p.file}</div>
<div class="meta"><span>Section ${p.id ?? ''}</span></div>
`;
item.addEventListener('click', () => selectPost(p.id));
elements.postList.appendChild(item);
});
}
async function selectPost(id) {
const post = state.posts.find(p => p.id === id);
if (!post) return;
state.active = id;
renderPostList();
await renderPost(post);
}
function selectAdjacent(direction) {
if (!state.active) return;
const idx = state.filtered.findIndex(p => p.id === state.active);
const nextIdx = idx + direction;
if (nextIdx >= 0 && nextIdx < state.filtered.length) {
selectPost(state.filtered[nextIdx].id);
}
}
async function renderPost(post) {
elements.postTitle.textContent = post.title || post.file;
elements.postSummary.textContent = post.summary || '';
elements.tagList.innerHTML = '';
(post.tags || []).forEach(tag => {
const pill = document.createElement('span');
pill.className = 'tag';
pill.textContent = tag;
elements.tagList.appendChild(pill);
});
const currentIdx = state.filtered.findIndex(p => p.id === post.id);
elements.prev.disabled = currentIdx <= 0;
elements.next.disabled = currentIdx === -1 || currentIdx >= state.filtered.length - 1;
const raw = await fetch(`sessions/${post.file}`).then(res => res.text());
const parsed = parseFrontmatter(raw);
const blocks = splitBlocks(parsed.content);
elements.postContent.innerHTML = blocks.map((block, i) => {
const html = renderBlock(block);
const no = String(i + 1).padStart(2, '0');
return `<section class="block" data-block="${i + 1}">` +
`<span class="block-no" title="Block ${i + 1} — future slide ${no}">${no}</span>` +
html +
`</section>`;
}).join('');
if (elements.blockCount) {
const n = blocks.length;
elements.blockCount.textContent = n ? `${n} blocks · ${n} slides` : '';
}
// Syntax-highlight code blocks. Guard each call: if highlight.js throws on an
// unusual block (e.g. ASCII diagrams), it must NOT abort the render and skip
// the MathJax typeset below — otherwise equations in code-bearing sessions
// silently fail to render.
elements.postContent.querySelectorAll('pre code').forEach(block => {
try {
hljs.highlightElement(block);
} catch (err) {
console.warn('highlight.js skipped a block', err);
}
});
if (elements.reader) {
elements.reader.scrollTo({ top: 0, behavior: 'smooth' });
}
window.scrollTo({ top: 0, behavior: 'smooth' });
typesetContent();
}
document.addEventListener('DOMContentLoaded', init);