-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
254 lines (210 loc) · 9.45 KB
/
app.js
File metadata and controls
254 lines (210 loc) · 9.45 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
const md = window.markdownit({ html: true, linkify: true, typographer: true });
const toggleBtn = document.getElementById('theme-toggle');
const hlTheme = document.getElementById('hl-theme');
const currentTheme = localStorage.getItem('theme') || 'dark';
const iconSun = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>`;
const iconMoon = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`;
function applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
toggleBtn.innerHTML = theme === 'dark' ? iconSun : iconMoon;
toggleBtn.title = theme === 'dark' ? 'switch to light' : 'switch to dark';
hlTheme.href = theme === 'dark'
? 'https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/styles/github-dark.min.css'
: 'https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/styles/github.min.css';
}
applyTheme(currentTheme);
toggleBtn.addEventListener('click', () => {
const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
localStorage.setItem('theme', theme);
applyTheme(theme);
});
function parseGithubPath(pathname) {
const clean = pathname.replace(/^\//, '');
const parts = clean.split('/');
if (parts.length < 2) return null;
const owner = parts[0];
const repo = parts[1];
const rest = parts.slice(2);
if (rest.length === 0) {
return { owner, repo, branch: null, fileParts: ['README.md'], isRepoRoot: true };
}
if (rest[0] === 'blob' && rest.length >= 3) {
return { owner, repo, branch: rest[1], fileParts: rest.slice(2), isRepoRoot: false };
}
if (rest[0] === 'refs' && rest[1] === 'heads' && rest.length >= 3) {
return { owner, repo, branch: rest[2], fileParts: rest.slice(3), isRepoRoot: false };
}
if (rest[0] === 'tree' && rest.length >= 2) {
return { owner, repo, branch: rest[1], fileParts: rest.slice(2), isRepoRoot: false };
}
return { owner, repo, branch: null, fileParts: rest, isRepoRoot: false };
}
async function resolveDefaultBranch(owner, repo) {
try {
const res = await fetch(`https://api.github.com/repos/${owner}/${repo}`);
if (!res.ok) return 'main';
const data = await res.json();
return data.default_branch || 'main';
} catch {
return 'main';
}
}
async function buildRawUrl(pathname) {
const parsed = parseGithubPath(pathname);
if (!parsed) return null;
const { owner, repo, fileParts, isRepoRoot } = parsed;
let { branch } = parsed;
if (!branch) {
branch = await resolveDefaultBranch(owner, repo);
}
let fileStr = fileParts.join('/');
if (!fileStr) fileStr = 'README.md';
const hasExt = /\.[a-zA-Z0-9]+$/.test(fileStr);
if (!hasExt) {
fileStr += '.md';
} else {
const ext = fileStr.split('.').pop().toLowerCase();
if (!['md', 'markdown', 'mdx', 'mdwn', 'mkd'].includes(ext)) {
return { error: `"${fileStr}" is not a Markdown file. viewmd only renders .md files.` };
}
}
const filePartsResolved = fileStr.split('/');
const dirParts = filePartsResolved.slice(0, -1);
const baseRawDir = `https://raw.githubusercontent.com/${owner}/${repo}/refs/heads/${branch}/${dirParts.length ? dirParts.join('/') + '/' : ''}`;
const raw = `https://raw.githubusercontent.com/${owner}/${repo}/refs/heads/${branch}/${fileStr}`;
const display = isRepoRoot ? `${owner}/${repo}` : `${owner}/${repo}/${fileStr}`;
return { raw, display, baseRawDir, owner, repo, branch, fileParts: filePartsResolved };
}
function fixRelativePaths(el, baseUrl, owner, repo, branch, fileParts) {
el.querySelectorAll('img').forEach(img => {
const src = img.getAttribute('src');
if (src && !src.startsWith('http') && !src.startsWith('data:')) {
img.src = baseUrl + src.replace(/^\.\//, '');
}
});
el.querySelectorAll('a').forEach(a => {
const href = a.getAttribute('href');
if (!href || href.startsWith('http') || href.startsWith('#') || href.startsWith('mailto:')) return;
const cleaned = href.replace(/^\.\//, '');
const dir = fileParts.slice(0, -1);
const newPath = '/' + [owner, repo, 'blob', branch, ...dir, cleaned].join('/');
a.href = window.location.origin + newPath;
});
}
function buildTOC(el) {
const allHeadings = el.querySelectorAll('h1, h2, h3, h4');
const headings = Array.from(allHeadings).filter((h, i) => !(h.tagName === 'H1' && i === 0));
if (headings.length < 3) return;
const tocList = document.getElementById('toc-list');
const tocPanel = document.getElementById('toc-panel');
tocList.innerHTML = '';
headings.forEach(h => {
const level = parseInt(h.tagName[1]);
const li = document.createElement('li');
li.className = `toc-h${level}`;
const a = document.createElement('a');
a.href = '#' + h.id;
a.textContent = h.textContent.replace(/ #$/, '');
a.addEventListener('click', e => {
e.preventDefault();
document.getElementById(h.id)?.scrollIntoView({ behavior: 'smooth' });
window.history.pushState(null, '', '#' + h.id);
});
li.appendChild(a);
tocList.appendChild(li);
});
tocPanel.classList.add('visible');
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const id = entry.target.id;
tocList.querySelectorAll('a').forEach(a => {
a.classList.toggle('active', a.getAttribute('href') === '#' + id);
});
}
});
}, { rootMargin: '-10% 0px -80% 0px' });
headings.forEach(h => observer.observe(h));
}
async function main() {
const urlParams = new URLSearchParams(window.location.search);
const redirect = urlParams.get('p');
if (redirect) {
window.history.replaceState(null, '', decodeURIComponent(redirect));
return main();
}
let pathname = window.location.pathname;
if (pathname === '/' || pathname === '') {
window.history.replaceState(null, '', '/viewmd/viewmd.github.io/blob/main/README.md');
pathname = '/viewmd/viewmd.github.io/blob/main/README.md';
}
const info = await buildRawUrl(pathname);
if (!info) {
showError('Invalid URL. Usage: viewmd.github.io/owner/repo/path/to/FILE.md');
return;
}
if (info.error) {
showError(info.error);
return;
}
document.getElementById('filepath').textContent = info.display;
document.title = info.display.split('/').pop() + ' — viewmd';
try {
const res = await fetch(info.raw);
if (!res.ok) {
if (res.status === 404) throw new Error('file not found — check the path or branch name');
throw new Error(`${res.status} ${res.statusText}`);
}
const text = await res.text();
document.getElementById('loading').style.display = 'none';
const el = document.getElementById('content');
let htmlContent = md.render(text);
htmlContent = htmlContent
.replace(/\[ \]/g, '<input type="checkbox" disabled>')
.replace(/\[x\]/gi, '<input type="checkbox" checked disabled>');
el.innerHTML = htmlContent;
fixRelativePaths(el, info.baseRawDir, info.owner, info.repo, info.branch, info.fileParts);
if (typeof hljs !== 'undefined') {
el.querySelectorAll('pre code').forEach(block => hljs.highlightElement(block));
}
el.querySelectorAll('pre').forEach(pre => {
const btn = document.createElement('button');
btn.className = 'pre-copy-btn';
btn.textContent = 'copy';
pre.appendChild(btn);
btn.addEventListener('click', () => {
const codeEl = pre.querySelector('code');
if (!codeEl) return;
navigator.clipboard.writeText(codeEl.textContent).then(() => {
btn.textContent = 'copied!';
setTimeout(() => { btn.textContent = 'copy'; }, 2000);
});
});
});
el.querySelectorAll('h1, h2, h3, h4, h5, h6').forEach(heading => {
const slug = heading.textContent.trim().toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-');
heading.id = slug;
heading.addEventListener('click', () => {
window.location.hash = slug;
navigator.clipboard.writeText(window.location.href);
});
});
buildTOC(el);
el.style.display = 'block';
if (window.location.hash) {
const target = document.getElementById(decodeURIComponent(window.location.hash.substring(1)));
if (target) setTimeout(() => target.scrollIntoView(), 150);
}
} catch (e) {
showError(`Failed to load file: ${e.message}`);
}
}
function showError(msg) {
document.getElementById('loading').style.display = 'none';
const el = document.getElementById('error');
el.textContent = msg;
el.style.display = 'block';
}
main();