-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
521 lines (459 loc) · 16.8 KB
/
Copy pathscript.js
File metadata and controls
521 lines (459 loc) · 16.8 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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/* -------------------------
CONFIG: set your repo here
------------------------- */
const CONFIG = {
owner: "OpenNotesProject",
repo: "Notes",
branch: "main",
rootPath: "",
token: ''
};
/* -------------------------
THEME MANAGEMENT
------------------------- */
const THEME_KEY = 'opennotes_theme';
function getCurrentTheme(){
const saved = localStorage.getItem(THEME_KEY);
if(saved) return saved;
if(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) return 'dark';
return 'light';
}
function setTheme(theme){
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem(THEME_KEY, theme);
updateThemeButtons(theme);
}
function updateThemeButtons(theme){
const lightBtn = document.getElementById('themeLight');
const darkBtn = document.getElementById('themeDark');
const kindleBtn = document.getElementById('themeKindle');
if(lightBtn) lightBtn.style.opacity = theme === 'light' ? '1' : '0.5';
if(darkBtn) darkBtn.style.opacity = theme === 'dark' ? '1' : '0.5';
if(kindleBtn) kindleBtn.style.opacity = theme === 'kindle' ? '1' : '0.5';
}
/* -------------------------
STATE & ELEMENTS
------------------------- */
const state = { tree: null, notesIndex: [], currentNote: null };
const subjectsDropdown = document.getElementById('subjectsDropdown');
const noteTitleEl = document.getElementById('noteTitle');
const noteContentEl = document.getElementById('noteContent');
const noteTopicEl = document.getElementById('noteTopic');
const noteInfoEl = document.getElementById('noteInfo');
const currentPathEl = document.getElementById('currentPath');
const statusEl = document.getElementById('status');
const searchInput = document.getElementById('globalSearch');
const searchResultsEl = document.getElementById('searchResults');
const shareBtn = document.getElementById('shareBtn');
const breadcrumbsEl = document.getElementById('breadcrumbs');
const recentListEl = document.getElementById('recentList');
/* -------------------------
Initialize mermaid
------------------------- */
if(window.mermaid){
try{
mermaid.initialize({
startOnLoad: false,
theme: 'default',
securityLevel: 'loose',
flowchart: { curve: 'basis' }
});
}catch(e){
console.warn('Mermaid init failed', e);
}
}
/* -------------------------
URL helpers
------------------------- */
function setURL(path){
const url = new URL(window.location);
url.searchParams.set('note', path);
window.history.replaceState({}, '', url);
}
function getURLNote(){
const url = new URL(window.location);
return url.searchParams.get('note');
}
/* -------------------------
GitHub helpers
------------------------- */
function ghContentsUrl(path=''){
const base = `https://api.github.com/repos/${CONFIG.owner}/${CONFIG.repo}/contents`;
const full = CONFIG.rootPath ? `${CONFIG.rootPath}/${path}` : path;
const encoded = full ? '/' + encodeURIComponent(full).replace(/%2F/g,'/') : '';
return `${base}${encoded}?ref=${CONFIG.branch}`;
}
function ghRawUrl(path){
const full = CONFIG.rootPath ? `${CONFIG.rootPath}/${path}` : path;
return `https://raw.githubusercontent.com/${CONFIG.owner}/${CONFIG.repo}/${CONFIG.branch}/${full}`;
}
async function ghFetch(url, opts = {}){
const headers = Object.assign({}, opts.headers || {});
if(CONFIG.token) headers['Authorization'] = `token ${CONFIG.token}`;
const res = await fetch(url, Object.assign({}, opts, { headers }));
if(!res.ok){
let msg = `${res.status} ${res.statusText} - ${url}`;
try{
const body = await res.json();
if(body && body.message) msg += `: ${body.message}`;
}catch(e){}
throw new Error(`GitHub fetch failed: ${msg}`);
}
return res;
}
async function fetchTree(path=''){
const url = ghContentsUrl(path);
const res = await ghFetch(url);
const items = await res.json();
const folders = {};
const files = [];
for(const item of items){
if(item.type === 'dir'){
folders[item.name] = await fetchTree(path ? `${path}/${item.name}` : item.name);
} else if(item.type === 'file' && item.name.toLowerCase().endsWith('.md')){
files.push({ name: item.name, path: path ? `${path}/${item.name}` : item.name });
}
}
return { folders, files };
}
function renderBranch(node, container, depth = 0, basePath = ''){
const folderNames = Object.keys(node.folders).sort();
folderNames.forEach(folder => {
const folderWrap = document.createElement('div');
folderWrap.className = 'branch';
folderWrap.dataset.path = basePath ? `${basePath}/${folder}` : folder;
const title = document.createElement('div');
title.className = 'branch-title';
title.style.paddingLeft = `${depth * 6}px`;
title.innerHTML = `📁 ${folder}`;
folderWrap.appendChild(title);
const children = document.createElement('div');
children.className = 'branch-children';
folderWrap.appendChild(children);
title.addEventListener('click', () => {
children.classList.toggle('open');
collapseSiblings(children, folderWrap.parentElement);
});
container.appendChild(folderWrap);
renderBranch(node.folders[folder], children, depth + 1, folderWrap.dataset.path);
});
node.files.sort((a,b)=>a.name.localeCompare(b.name)).forEach(file => {
const fileEl = document.createElement('div');
fileEl.className = 'note-link';
fileEl.style.paddingLeft = `${depth * 6}px`;
fileEl.textContent = file.name.replace(/\.md$/,'');
fileEl.dataset.path = file.path;
fileEl.addEventListener('click', () => loadNote(file.path));
container.appendChild(fileEl);
});
}
function collapseSiblings(currentChildren, parent){
if(!parent) return;
parent.querySelectorAll('.branch-children').forEach(ch => {
if(ch !== currentChildren) ch.classList.remove('open');
});
}
function renderSubjects(tree){
subjectsDropdown.innerHTML = `<div class="subject-header">Subjects</div>`;
const topFolders = Object.keys(tree.folders).sort();
topFolders.forEach((subject, idx) => {
const branch = document.createElement('div');
branch.className = 'branch';
const title = document.createElement('div');
title.className = 'branch-title';
title.innerHTML = `📁 ${subject}`;
branch.appendChild(title);
const children = document.createElement('div');
children.className = 'branch-children';
branch.appendChild(children);
title.addEventListener('click', () => {
children.classList.toggle('open');
collapseSiblings(children, subjectsDropdown);
});
subjectsDropdown.appendChild(branch);
renderBranch(state.tree.folders[subject], children, 0, subject);
if(idx === 0) children.classList.add('open');
});
}
function processCallouts(container){
const icons = {
note: '📝', warning: '⚠️', danger: '🚨', error: '❌', tip: '💡', hint: '💡',
example: '📋', quote: '💬', info: 'ℹ️', abstract: '📋', summary: '📋',
bug: '🐛', failure: '❌', success: '✅'
};
function sanitizeType(raw){
return raw.toLowerCase().trim().replace(/[^a-z0-9_-]+/g,'-');
}
function displayTitle(raw){
raw = raw.trim();
return raw.charAt(0).toUpperCase() + raw.slice(1).toLowerCase();
}
function removeMarkerFromNode(node){
if(!node) return false;
if(node.nodeType === Node.TEXT_NODE){
const txt = node.nodeValue || '';
if(/^\s*\[!.+?\]\s*/i.test(txt)){
node.nodeValue = txt.replace(/^\s*\[!.+?\]\s*/i, '');
return true;
}
return false;
}
if(node.nodeType === Node.ELEMENT_NODE){
const children = Array.from(node.childNodes);
for(const child of children){
if(removeMarkerFromNode(child)){
if(child.nodeType === Node.ELEMENT_NODE && !child.textContent.trim()) child.remove();
return true;
}
}
}
return false;
}
function makeCalloutFor(el, typeRaw){
const type = sanitizeType(typeRaw);
const calloutDiv = document.createElement('div');
calloutDiv.className = `callout ${type}`;
const titleDiv = document.createElement('div');
titleDiv.className = 'callout-title';
titleDiv.innerHTML = `<span class="callout-icon">${icons[type] || '📌'}</span><span>${displayTitle(typeRaw)}</span>`;
removeMarkerFromNode(el);
const contentDiv = document.createElement('div');
contentDiv.className = 'callout-content';
contentDiv.innerHTML = el.innerHTML;
calloutDiv.appendChild(titleDiv);
calloutDiv.appendChild(contentDiv);
el.parentNode.replaceChild(calloutDiv, el);
}
const blockquotes = Array.from(container.querySelectorAll('blockquote'));
blockquotes.forEach(bq => {
const bqText = bq.textContent || '';
const match = bqText.match(/^\s*\[!(.+?)\]/i);
if(!match) return;
makeCalloutFor(bq, match[1]);
});
const blockTags = ['p','div','li','pre','section','article','figure','aside','header','footer'];
const candidates = Array.from(container.querySelectorAll(blockTags.join(',')));
candidates.forEach(el => {
if(el.closest('blockquote')) return;
const txt = el.textContent || '';
const match = txt.match(/^\s*\[!(.+?)\]/i);
if(!match) return;
makeCalloutFor(el, match[1]);
});
}
async function loadNote(path){
try{
statusEl.textContent = 'Loading…';
const res = await ghFetch(ghRawUrl(path));
const text = await res.text();
const title = path.split('/').pop().replace(/\.md$/,'');
const topic = path.split('/')[0] || 'Notes';
noteTitleEl.textContent = title;
noteTopicEl.textContent = topic;
noteInfoEl.textContent = path;
currentPathEl.textContent = path;
noteContentEl.innerHTML = marked.parse(text);
processCallouts(noteContentEl);
try{
if(window.renderMathInElement){
renderMathInElement(noteContentEl, {
delimiters: [
{left: '$$', right: '$$', display: true},
{left: '$', right: '$', display: false}
],
throwOnError: false
});
}
}catch(e){ console.warn('KaTeX render failed', e); }
state.currentNote = { path, title, content: text };
setURL(path);
updateBreadcrumbs(path);
addRecent(path);
await renderAllMermaid();
statusEl.textContent = 'Loaded';
}catch(err){
console.error(err);
statusEl.textContent = 'Error loading note';
}
}
let mermaidIdCounter = 0;
async function renderAllMermaid() {
if (!window.mermaid) return;
const blocks = noteContentEl.querySelectorAll(
'pre code.language-mermaid, code.language-mermaid'
);
for (const block of blocks) {
const code = block.textContent.trim();
const id = "mmd-" + Math.random().toString(36).slice(2);
try {
const { svg } = await mermaid.render(id, code);
const wrapper = document.createElement("div");
wrapper.className = "mermaid-svg";
wrapper.innerHTML = svg;
const pre = block.closest("pre");
if (pre) pre.replaceWith(wrapper);
else block.replaceWith(wrapper);
} catch (err) {
console.error("Mermaid render error:", err);
const errorBox = document.createElement("div");
errorBox.style.color = "crimson";
errorBox.style.margin = "0.5rem 0";
errorBox.textContent = "Mermaid diagram failed to render.";
block.closest("pre")?.after(errorBox);
}
}
}
function updateBreadcrumbs(path){
if(!path){
breadcrumbsEl.style.display = 'none';
return;
}
breadcrumbsEl.style.display = 'flex';
breadcrumbsEl.innerHTML = '';
const parts = path.split('/');
let accum = [];
parts.forEach((p, i) => {
accum.push(p);
const seg = accum.join('/');
const label = p.replace(/\.md$/,'');
const a = document.createElement('a');
a.textContent = label;
a.href = 'javascript:void(0)';
a.addEventListener('click', () => {
expandPath(seg);
if(seg.toLowerCase().endsWith('.md')) loadNote(seg);
});
breadcrumbsEl.appendChild(a);
if(i < parts.length - 1){
const sep = document.createElement('span');
sep.className = 'sep';
sep.textContent = '›';
breadcrumbsEl.appendChild(sep);
}
});
}
function expandPath(path){
const segments = path.split('/');
let current = '';
segments.forEach((seg) => {
current = current ? `${current}/${seg}` : seg;
const branch = document.querySelector(`.branch[data-path="${current}"]`);
if(branch){
const children = branch.querySelector('.branch-children');
if(children) children.classList.add('open');
}
});
document.querySelectorAll('.branch-children').forEach(ch => {
const parentBranch = ch.parentElement;
if(parentBranch && parentBranch.dataset.path){
const p = parentBranch.dataset.path;
if(!path.startsWith(p)) ch.classList.remove('open');
}
});
}
const RECENT_KEY = 'opennotes_recent';
function getRecent(){
try{ const raw = localStorage.getItem(RECENT_KEY); return raw ? JSON.parse(raw) : []; }catch{ return []; }
}
function saveRecent(list){ try{ localStorage.setItem(RECENT_KEY, JSON.stringify(list)); }catch{} }
function addRecent(path){
if(!path) return;
const list = getRecent().filter(p => p !== path);
list.unshift(path);
if(list.length > 12) list.length = 12;
saveRecent(list);
renderRecent();
}
function renderRecent(){
const list = getRecent();
recentListEl.innerHTML = '';
if(!list.length){
recentListEl.innerHTML = '<div style="color:var(--muted)">No recent notes yet — open a note to add it here.</div>';
return;
}
list.forEach(p => {
const el = document.createElement('div');
el.className = 'recent-item';
el.textContent = p;
el.addEventListener('click', () => loadNote(p));
recentListEl.appendChild(el);
});
}
async function buildIndex(node){
for(const file of node.files){
try{
const res = await fetch(ghRawUrl(file.path));
if(!res.ok) continue;
const text = await res.text();
state.notesIndex.push({ path: file.path, title: file.name.replace(/\.md$/,''), content: text.toLowerCase() });
}catch(e){
console.warn('Index fetch failed for', file.path);
}
}
for(const folder in node.folders){
await buildIndex(node.folders[folder]);
}
}
function runSearch(q){
q = q.toLowerCase().trim();
if(!q){ searchResultsEl.style.display = 'none'; searchResultsEl.innerHTML = ''; return; }
const results = state.notesIndex.filter(n => n.title.toLowerCase().includes(q) || n.content.includes(q)).slice(0,50);
searchResultsEl.innerHTML = '';
if(!results.length){
const none = document.createElement('div'); none.className = 'search-result-item'; none.textContent = `No results for "${q}"`; searchResultsEl.appendChild(none);
searchResultsEl.style.display = 'block'; return;
}
results.forEach(r => {
const item = document.createElement('div');
item.className = 'search-result-item';
item.textContent = r.path;
item.addEventListener('click', () => { searchResultsEl.style.display = 'none'; loadNote(r.path); });
searchResultsEl.appendChild(item);
});
searchResultsEl.style.display = 'block';
}
document.addEventListener('keydown', e => {
if((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k'){ e.preventDefault(); searchInput.focus(); }
if(e.key.toLowerCase() === 'n' && document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA'){ e.preventDefault(); createNotePlaceholder(); }
});
searchInput.addEventListener('input', e => runSearch(e.target.value));
searchInput.addEventListener('blur', () => setTimeout(()=>{ searchResultsEl.style.display='none'; }, 150));
shareBtn.addEventListener('click', () => {
if(!state.currentNote) return;
const url = window.location.href;
navigator.clipboard.writeText(url).then(() => {
const prev = statusEl.textContent;
statusEl.textContent = 'Link copied!';
setTimeout(()=> statusEl.textContent = prev, 1400);
});
});
document.getElementById('themeLight').addEventListener('click', () => setTheme('light'));
document.getElementById('themeDark').addEventListener('click', () => setTheme('dark'));
document.getElementById('themeKindle').addEventListener('click', () => setTheme('kindle'));
function createNotePlaceholder(){
alert('Create note flow — integrate your editor here.');
}
(async function init(){
try{
setTheme(getCurrentTheme());
statusEl.textContent = 'Fetching vault…';
const tree = await fetchTree('');
state.tree = tree;
renderSubjects(tree);
statusEl.textContent = 'Indexing notes…';
await buildIndex(tree);
statusEl.textContent = `Ready · ${state.notesIndex.length} notes indexed`;
renderRecent();
const urlNote = getURLNote();
if(urlNote){
expandPath(urlNote);
await loadNote(urlNote);
} else {
currentPathEl.textContent = 'Recent';
}
}catch(err){
console.error(err);
statusEl.textContent = 'Error loading vault';
noteContentEl.innerHTML = `<p style="color:var(--muted)">Could not load repository. Check <code>CONFIG</code>, that the repo is public, and that the branch exists. Error: ${err.message}</p>`;
}
})();