-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
785 lines (658 loc) · 25.1 KB
/
script.js
File metadata and controls
785 lines (658 loc) · 25.1 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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
// Configure marked.js
marked.setOptions({
highlight: function(code, lang) {
// Map common language aliases to Luma
if (lang === 'luma' || lang === 'lx') {
return hljs.highlight(code, { language: 'luma' }).value;
}
// Try to detect language
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(code, { language: lang }).value;
}
// Auto-detect, but prefer Rust-like highlighting for unknown syntax
const result = hljs.highlightAuto(code, ['rust', 'c', 'cpp']);
return result.value;
},
breaks: true,
gfm: true
});
// State management for current view
let currentView = 'docs';
let stdLibFiles = [];
let currentStdLibFile = null;
// Auto-load docs.md on page load
window.addEventListener('DOMContentLoaded', () => {
// Get the base path (works for both local and GitHub Pages)
const basePath = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1);
// Try multiple possible locations
const possiblePaths = [
basePath + 'docs.md',
basePath + 'DOCS.md',
basePath + 'README.md',
'./docs.md',
'docs.md',
'../docs.md'
];
tryLoadMarkdown(possiblePaths, 0);
});
// Show documentation view
function showDocs() {
currentView = 'docs';
// Update nav buttons
document.querySelectorAll('.nav-btn').forEach(btn => btn.classList.remove('active'));
event.target.classList.add('active');
// Reload docs
const basePath = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1);
const possiblePaths = [
basePath + 'docs.md',
basePath + 'DOCS.md',
basePath + 'README.md',
'./docs.md',
'docs.md',
'../docs.md'
];
tryLoadMarkdown(possiblePaths, 0);
}
// Show standard library view
async function showStdLib() {
currentView = 'stdlib';
// Update nav buttons
document.querySelectorAll('.nav-btn').forEach(btn => btn.classList.remove('active'));
event.target.classList.add('active');
const contentDiv = document.getElementById('content');
contentDiv.innerHTML = '<div class="loading">Loading standard library documentation...</div>';
try {
// Fetch the list of markdown files from GitHub API
const response = await fetch('https://api.github.com/repos/Luma-Programming-Language/Luma-std/contents/docs');
if (!response.ok) {
throw new Error(`GitHub API error: ${response.status}`);
}
const files = await response.json();
stdLibFiles = files.filter(file =>
file.name.endsWith('.md') &&
file.name !== 'README.md' &&
file.name !== 'main.md'
);
if (stdLibFiles.length === 0) {
throw new Error('No markdown files found in the docs directory');
}
// Build sidebar for stdlib
buildStdLibSidebar();
// Load the first file by default
await loadStdLibFile(stdLibFiles[0]);
} catch (error) {
contentDiv.innerHTML = `
<div style="padding: 2rem; text-align: center;">
<h2 style="color: #f85149;">❌ Failed to load standard library documentation</h2>
<p style="color: var(--text-secondary); margin: 1rem 0;">
${error.message}
</p>
<p style="color: var(--text-secondary); font-size: 0.9rem;">
Please check your internet connection and try again.
</p>
</div>
`;
}
}
// Build sidebar for standard library files
function buildStdLibSidebar() {
const toc = document.getElementById('toc');
const tocHTML = stdLibFiles.map(file => {
const name = file.name.replace('.md', '');
return `<li><a href="#" onclick="loadStdLibFileByName('${file.name}'); return false;">${name}</a></li>`;
}).join('');
toc.innerHTML = `
<div class="sidebar-section-header">Standard Library</div>
<ul>${tocHTML}</ul>
`;
}
// Load a standard library file by name
async function loadStdLibFileByName(fileName) {
const file = stdLibFiles.find(f => f.name === fileName);
if (file) {
await loadStdLibFile(file);
}
}
// Load a specific standard library file
async function loadStdLibFile(file) {
const contentDiv = document.getElementById('content');
contentDiv.innerHTML = '<div class="loading">Loading...</div>';
try {
// Fetch the raw markdown content
const response = await fetch(file.download_url);
if (!response.ok) {
throw new Error(`Failed to fetch ${file.name}: ${response.status}`);
}
const markdown = await response.text();
currentStdLibFile = file;
// Parse and render the markdown
parseAndRenderMarkdown(markdown);
// Update active state in sidebar
document.querySelectorAll('#toc a').forEach(link => {
link.classList.remove('active');
if (link.textContent === file.name.replace('.md', '')) {
link.classList.add('active');
}
});
} catch (error) {
contentDiv.innerHTML = `
<div style="padding: 2rem; text-align: center;">
<h2 style="color: #f85149;">❌ Failed to load file</h2>
<p style="color: var(--text-secondary); margin: 1rem 0;">
${error.message}
</p>
</div>
`;
}
}
async function tryLoadMarkdown(paths, index) {
if (index >= paths.length) {
document.getElementById('content').innerHTML = `
<div style="padding: 2rem; text-align: center;">
<h2 style="color: #f85149;">❌ Documentation file not found</h2>
<p style="color: var(--text-secondary); margin: 1rem 0;">
Tried looking for markdown file in multiple locations.
</p>
<p style="color: var(--text-secondary); font-size: 0.9rem; margin-top: 1rem;">
Current URL: <code>${window.location.href}</code>
</p>
<p style="color: var(--text-secondary); font-size: 0.9rem;">
Make sure <code>docs.md</code> is in the same directory as <code>index.html</code>
</p>
</div>
`;
return;
}
try {
const response = await fetch(paths[index]);
if (response.ok) {
const markdown = await response.text();
parseAndRenderMarkdown(markdown);
console.log(`Successfully loaded: ${paths[index]}`);
return;
}
} catch (error) {
console.log(`Failed to load: ${paths[index]}`);
}
// Try next path
tryLoadMarkdown(paths, index + 1);
}
async function loadFromUrl(url) {
const contentDiv = document.getElementById('content');
contentDiv.innerHTML = '<div class="loading">Loading markdown from URL...</div>';
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const markdown = await response.text();
parseAndRenderMarkdown(markdown);
} catch (error) {
contentDiv.innerHTML = `
<div style="padding: 2rem; text-align: center;">
<h2 style="color: #f85149;">❌ Failed to load documentation</h2>
<p style="color: var(--text-secondary); margin: 1rem 0;">
Could not find <code>docs.md</code> file.
</p>
<p style="color: var(--text-secondary); font-size: 0.9rem;">
Make sure <code>docs.md</code> is in the same directory as <code>index.html</code>
</p>
</div>
`;
}
}
// Theme toggle
function toggleTheme() {
const body = document.body;
const btn = document.querySelector('.theme-toggle');
const currentTheme = body.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
body.setAttribute('data-theme', newTheme);
btn.textContent = newTheme === 'dark' ? '🌙 Dark' : '☀️ Light';
localStorage.setItem('theme', newTheme);
}
// Load saved theme
const savedTheme = localStorage.getItem('theme') || 'dark';
document.body.setAttribute('data-theme', savedTheme);
document.querySelector('.theme-toggle').textContent = savedTheme === 'dark' ? '🌙 Dark' : '☀️ Light';
// Sidebar toggle for mobile
function toggleSidebar() {
document.getElementById('sidebar').classList.toggle('active');
}
// Scroll to top button
window.addEventListener('scroll', () => {
const scrollTop = document.getElementById('scrollTop');
if (window.pageYOffset > 300) {
scrollTop.classList.add('visible');
} else {
scrollTop.classList.remove('visible');
}
});
function parseAndRenderMarkdown(markdown) {
// Parse markdown to HTML
const html = marked.parse(markdown);
// Render content
const contentDiv = document.getElementById('content');
contentDiv.innerHTML = html;
// Highlight code blocks
contentDiv.querySelectorAll('pre code').forEach((block) => {
hljs.highlightElement(block);
// Add copy button
const pre = block.parentElement;
const wrapper = document.createElement('div');
wrapper.className = 'code-wrapper';
pre.parentNode.insertBefore(wrapper, pre);
wrapper.appendChild(pre);
const copyBtn = document.createElement('button');
copyBtn.className = 'copy-btn';
copyBtn.textContent = 'Copy';
copyBtn.onclick = function() {
navigator.clipboard.writeText(block.textContent);
copyBtn.textContent = 'Copied!';
copyBtn.classList.add('copied');
setTimeout(() => {
copyBtn.textContent = 'Copy';
copyBtn.classList.remove('copied');
}, 2000);
};
wrapper.appendChild(copyBtn);
});
// Generate table of contents
generateTOC();
// Setup intersection observer for active section highlighting
setupScrollSpy();
// Build search index
setTimeout(() => buildSearchIndex(), 100);
}
function generateTOC() {
// Skip TOC generation for stdlib view - it's already built
if (currentView === 'stdlib') {
return;
}
const content = document.getElementById('content');
const headings = content.querySelectorAll('h1, h2, h3, h4');
const toc = document.getElementById('toc');
// Add IDs to ALL headings (not just h1, h2)
headings.forEach((heading, index) => {
if (!heading.id) {
// Create a slug from the heading text
const slug = heading.textContent
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.trim();
heading.id = slug || 'heading-' + index;
}
});
// Build hierarchical TOC structure (only h1 and h2 for TOC)
const tocHeadings = content.querySelectorAll('h1, h2');
let tocHTML = '<ul class="toc-list">';
let currentH1 = null;
let h2List = [];
tocHeadings.forEach((heading, index) => {
const level = heading.tagName.toLowerCase();
const text = heading.textContent;
const id = heading.id;
if (level === 'h1') {
// Close previous h1's h2 list if exists
if (currentH1 && h2List.length > 0) {
tocHTML += '<ul class="toc-sublist">';
h2List.forEach(h2 => {
tocHTML += `<li><a href="#${h2.id}" data-level="h2">${h2.text}</a></li>`;
});
tocHTML += '</ul>';
h2List = [];
}
// Add h1
tocHTML += `<li class="toc-h1"><a href="#${id}" data-level="h1">${text}</a>`;
currentH1 = { id, text };
} else if (level === 'h2') {
// Collect h2s under current h1
h2List.push({ id, text });
}
});
// Close last h1's h2 list if exists
if (currentH1 && h2List.length > 0) {
tocHTML += '<ul class="toc-sublist">';
h2List.forEach(h2 => {
tocHTML += `<li><a href="#${h2.id}" data-level="h2">${h2.text}</a></li>`;
});
tocHTML += '</ul>';
}
if (currentH1) {
tocHTML += '</li>'; // Close last h1
}
tocHTML += '</ul>';
toc.innerHTML = tocHTML;
}
function setupScrollSpy() {
const sections = document.querySelectorAll('.content h1, .content h2, .content h3');
const navLinks = document.querySelectorAll('.sidebar a');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
navLinks.forEach(link => link.classList.remove('active'));
const activeLink = document.querySelector(`.sidebar a[href="#${entry.target.id}"]`);
if (activeLink) {
activeLink.classList.add('active');
}
}
});
}, {
rootMargin: '-20% 0px -80% 0px'
});
sections.forEach(section => observer.observe(section));
}
// Smooth scrolling for anchor links
document.addEventListener('click', (e) => {
if (e.target.tagName === 'A' && e.target.getAttribute('href')?.startsWith('#')) {
e.preventDefault();
const id = e.target.getAttribute('href').slice(1);
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
// Close mobile menu
if (window.innerWidth <= 768) {
document.getElementById('sidebar').classList.remove('active');
}
}
}
});
// ===========================
// SEARCH FUNCTIONALITY
// ===========================
let searchIndex = [];
let currentDocContent = '';
// Build search index from current content
function buildSearchIndex() {
searchIndex = [];
const content = document.getElementById('content');
// Store full content for context
currentDocContent = content.textContent;
// Index all headings - make sure they have IDs first
const headings = content.querySelectorAll('h1, h2, h3, h4');
headings.forEach((heading, idx) => {
// Ensure heading has an ID
if (!heading.id) {
const slug = heading.textContent
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.trim();
heading.id = slug || 'heading-' + idx;
}
const text = heading.textContent;
const id = heading.id;
const level = heading.tagName.toLowerCase();
// Get surrounding context
let context = '';
let nextElement = heading.nextElementSibling;
while (nextElement && !nextElement.matches('h1, h2, h3, h4')) {
context += nextElement.textContent + ' ';
nextElement = nextElement.nextElementSibling;
if (context.length > 300) break;
}
searchIndex.push({
title: text,
id: id,
type: 'heading',
level: level,
content: context.slice(0, 300)
});
});
// Index code blocks
const codeBlocks = content.querySelectorAll('pre code');
codeBlocks.forEach((code, idx) => {
const text = code.textContent;
const prevHeading = findPreviousHeading(code);
searchIndex.push({
title: prevHeading ? `Code in: ${prevHeading.textContent}` : `Code block ${idx + 1}`,
id: prevHeading?.id || '',
type: 'code',
content: text.slice(0, 300)
});
});
// Index paragraphs with keywords
const paragraphs = content.querySelectorAll('p');
paragraphs.forEach(p => {
const text = p.textContent;
// Only index paragraphs with keywords or longer content
if (text.length > 100 || hasKeywords(text)) {
const prevHeading = findPreviousHeading(p);
searchIndex.push({
title: prevHeading ? prevHeading.textContent : 'Documentation',
id: prevHeading?.id || '',
type: 'content',
content: text.slice(0, 300)
});
}
});
}
function findPreviousHeading(element) {
let current = element.previousElementSibling;
while (current) {
if (current.matches('h1, h2, h3, h4')) {
return current;
}
current = current.previousElementSibling;
}
return null;
}
function hasKeywords(text) {
const keywords = ['const', 'let', 'fn', 'struct', 'enum', 'loop', 'if', 'return',
'alloc', 'free', 'defer', 'cast', 'sizeof', 'pub', 'priv'];
const lowerText = text.toLowerCase();
return keywords.some(kw => lowerText.includes(kw));
}
// Perform search
function performSearch(query) {
if (!query || query.length < 2) {
return [];
}
const lowerQuery = query.toLowerCase();
const queryWords = lowerQuery.split(/\s+/).filter(w => w.length > 1);
const results = searchIndex.map(item => {
let score = 0;
const lowerTitle = item.title.toLowerCase();
const lowerContent = item.content.toLowerCase();
// Exact title match - highest score
if (lowerTitle === lowerQuery) {
score += 100;
}
// Title starts with query
if (lowerTitle.startsWith(lowerQuery)) {
score += 50;
}
// Title contains query
if (lowerTitle.includes(lowerQuery)) {
score += 30;
}
// Content contains exact query
if (lowerContent.includes(lowerQuery)) {
score += 20;
}
// Each word match
queryWords.forEach(word => {
if (lowerTitle.includes(word)) score += 10;
if (lowerContent.includes(word)) score += 5;
});
// Bonus for heading type
if (item.type === 'heading') {
score += 10;
if (item.level === 'h1') score += 5;
if (item.level === 'h2') score += 3;
}
return { ...item, score };
}).filter(item => item.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, 10);
return results;
}
// Highlight search terms in text
function highlightSearchTerms(text, query) {
const words = query.toLowerCase().split(/\s+/).filter(w => w.length > 1);
let highlighted = text;
words.forEach(word => {
const regex = new RegExp(`(${word})`, 'gi');
highlighted = highlighted.replace(regex, '<mark>$1</mark>');
});
return highlighted;
}
// Display search results
function displaySearchResults(results, query, resultsContainer) {
if (results.length === 0) {
resultsContainer.innerHTML = '<div class="search-no-results">No results found</div>';
return;
}
// Clear previous results
resultsContainer.innerHTML = '';
results.forEach(result => {
const typeIcon = result.type === 'heading' ? '📄' :
result.type === 'code' ? '💻' : '📝';
const snippet = highlightSearchTerms(result.content.trim(), query);
const resultItem = document.createElement('div');
resultItem.className = 'search-result-item';
resultItem.innerHTML = `
<div class="search-result-title">
<span>${typeIcon}</span>
<span>${highlightSearchTerms(result.title, query)}</span>
<span class="search-result-badge">${result.type}</span>
</div>
<div class="search-result-snippet">${snippet}</div>
`;
// Add click event listener - use event delegation to prevent issues
resultItem.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
navigateToResult(result.id);
});
resultsContainer.appendChild(resultItem);
});
}
function navigateToResult(id) {
console.log('Navigating to ID:', id); // Debug log
const resultsDiv = document.getElementById('searchResults');
const mobileResultsDiv = document.getElementById('mobileSearchResults');
const mobileOverlay = document.getElementById('mobileSearchOverlay');
// Hide search results first
resultsDiv.classList.remove('active');
mobileResultsDiv.innerHTML = '';
mobileOverlay.classList.remove('active');
// Clear search inputs
document.getElementById('searchInput').value = '';
document.getElementById('mobileSearchInput').value = '';
// Close mobile sidebar if open
if (window.innerWidth <= 768) {
document.getElementById('sidebar').classList.remove('active');
}
// Navigate to the element
if (id) {
// Small delay to ensure DOM is ready
setTimeout(() => {
const element = document.getElementById(id);
console.log('Found element:', element); // Debug log
if (element) {
// Scroll to element with offset for fixed header
const headerOffset = 100;
const elementPosition = element.getBoundingClientRect().top;
const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
console.log('Scrolling to position:', offsetPosition); // Debug log
window.scrollTo({
top: offsetPosition,
behavior: 'smooth'
});
// Highlight the element briefly
element.style.transition = 'background 0.3s';
element.style.background = 'var(--bg-tertiary)';
setTimeout(() => {
element.style.background = '';
}, 1500);
} else {
console.warn('Element not found with ID:', id);
// If no element with ID found, just scroll to top of content
window.scrollTo({
top: 60,
behavior: 'smooth'
});
}
}, 150);
} else {
console.warn('No ID provided');
// No ID provided, scroll to top
window.scrollTo({
top: 60,
behavior: 'smooth'
});
}
}
// Desktop search setup
const searchInput = document.getElementById('searchInput');
const searchResults = document.getElementById('searchResults');
searchInput.addEventListener('input', (e) => {
const query = e.target.value;
if (query.length < 2) {
searchResults.classList.remove('active');
return;
}
const results = performSearch(query);
displaySearchResults(results, query, searchResults);
searchResults.classList.add('active');
});
searchInput.addEventListener('focus', (e) => {
if (e.target.value.length >= 2) {
searchResults.classList.add('active');
}
});
// Close search results when clicking outside
document.addEventListener('click', (e) => {
if (!e.target.closest('.search-container')) {
searchResults.classList.remove('active');
}
if (!e.target.closest('.mobile-search-overlay')) {
document.getElementById('mobileSearchOverlay').classList.remove('active');
}
});
// Mobile search setup
const mobileSearchInput = document.getElementById('mobileSearchInput');
const mobileSearchResults = document.getElementById('mobileSearchResults');
mobileSearchInput.addEventListener('input', (e) => {
const query = e.target.value;
if (query.length < 2) {
mobileSearchResults.innerHTML = '';
return;
}
const results = performSearch(query);
displaySearchResults(results, query, mobileSearchResults);
});
function toggleMobileSearch() {
const overlay = document.getElementById('mobileSearchOverlay');
const input = document.getElementById('mobileSearchInput');
overlay.classList.toggle('active');
if (overlay.classList.contains('active')) {
setTimeout(() => input.focus(), 100);
} else {
input.value = '';
mobileSearchResults.innerHTML = '';
}
}
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
// Cmd/Ctrl + K to focus search
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
if (window.innerWidth <= 768) {
toggleMobileSearch();
} else {
searchInput.focus();
}
}
// Escape to close search
if (e.key === 'Escape') {
searchResults.classList.remove('active');
document.getElementById('mobileSearchOverlay').classList.remove('active');
searchInput.blur();
mobileSearchInput.blur();
}
});