<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ECUST课程分享仓库目录</title>
    <script src="https://mirrors.sustech.edu.cn/cdnjs/ajax/libs/showdown/2.1.0/showdown.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }
        #tree {
            font-family: monospace;
            line-height: 1.5;
            margin-top: 20px;
        }
        .dir {
            color: #0366d6;
            font-weight: bold;
            cursor: pointer;
            position: relative;
            padding-left: 15px;
        }
        .dir::before {
            content: '📁 ';
        }
        .dir.collapsed::before {
            content: '📂 ';
        }
        .file {
            color: #24292e;
            padding-left: 15px;
        }
        .file::before {
            content: '📄 ';
        }
        .loading {
            color: #6a737d;
            font-style: italic;
            padding-left: 30px;
            display: flex;
            align-items: center;
        }
        .error {
            color: red;
        }
        .readme-container {
            margin: 20px 0;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 5px;
            border-left: 4px solid #0366d6;
        }
        .readme-title {
            font-weight: bold;
            margin-bottom: 10px;
            color: #0366d6;
            display: flex;
            align-items: center;
        }
        .readme-content {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
            line-height: 1.5;
            color: #24292e;
            word-wrap: break-word;
            overflow-wrap: break-word;
        }
        .file-link {
            cursor: pointer;
            text-decoration: underline;
            color: #0366d6;
        }
        .download-sources {
            margin-left: 10px;
            font-size: 0.8em;
            color: #586069;
        }
        .download-source {
            margin-left: 8px;
            color: #586069;
            text-decoration: none;
        }
        .download-source:hover {
            text-decoration: underline;
            color: #0366d6;
        }
        
        /* Markdown 渲染样式 */
        .readme-content h1, .readme-content h2, .readme-content h3 {
            margin: 1em 0 0.5em 0;
            color: #0366d6;
        }
        .readme-content h1 {
            font-size: 1.5em;
            border-bottom: 1px solid #eaecef;
            padding-bottom: 0.3em;
        }
        .readme-content h2 {
            font-size: 1.3em;
            border-bottom: 1px solid #eaecef;
            padding-bottom: 0.3em;
        }
        .readme-content h3 {
            font-size: 1.1em;
        }
        .readme-content pre {
            background-color: #f6f8fa;
            border-radius: 3px;
            padding: 16px;
            overflow-x: auto;
            line-height: 1.45;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        .readme-content code {
            background-color: rgba(27,31,35,0.05);
            border-radius: 3px;
            padding: 0.2em 0.4em;
            font-family: monospace;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        .readme-content a {
            word-break: break-all;
            overflow-wrap: break-word;
        }
        .readme-content ul, .readme-content ol {
            padding-left: 2em;
        }
        .readme-content img {
            max-width: 100%;
            box-sizing: content-box;
            background-color: #fff;
        }
        .readme-content a {
            color: #0366d6;
            text-decoration: none;
        }
        .readme-content a:hover {
            text-decoration: underline;
        }
        .readme-content blockquote {
            padding: 0 1em;
            color: #6a737d;
            border-left: 0.25em solid #dfe2e5;
            margin: 0 0 1em 0;
        }
        .readme-content .center {
            text-align: center;
        }
        .readme-content .note {
            background-color: #e7f5ff;
            border-left: 4px solid #0366d6;
            padding: 1em;
            margin: 1em 0;
        }
        .readme-content .important {
            background-color: #fff3bf;
            border-left: 4px solid #f08c00;
            padding: 1em;
            margin: 1em 0;
        }
        .readme-content .todo-list {
            list-style-type: none;
            padding-left: 0;
        }
        .readme-content .todo-list li {
            margin: 0.5em 0;
            padding-left: 1.5em;
            position: relative;
        }
        .readme-content .todo-list li:before {
            content: "☐";
            position: absolute;
            left: 0;
        }
        .readme-content .todo-list li.checked:before {
            content: "☑";
        }
        .readme-content .badge {
            display: inline-block;
            padding: 0.25em 0.4em;
            font-size: 75%;
            font-weight: 700;
            line-height: 1;
            text-align: center;
            white-space: nowrap;
            vertical-align: baseline;
            border-radius: 0.25rem;
            margin: 0 0.2em;
        }
        
        /* 加载动画 */
        .spinner {
            display: inline-block;
            width: 1em;
            height: 1em;
            border: 2px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top-color: #0366d6;
            animation: spin 1s ease-in-out infinite;
            margin-right: 8px;
            vertical-align: middle;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* 错误样式增强 */
        .readme-container.error {
            border-left-color: #d73a49;
        }
        .error-message {
            color: #d73a49;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .error-icon {
            font-size: 1.2em;
        }
        .retry-btn {
            margin-left: auto;
            padding: 4px 8px;
            background-color: #f3f4f6;
            border: 1px solid #d1d5da;
            border-radius: 3px;
            cursor: pointer;
        }
        .retry-btn:hover {
            background-color: #eaecef;
        }
        
        /* 目录样式 */
        .toc {
            background: #f8f9fa;
            padding: 10px 15px;
            border-radius: 3px;
            margin-bottom: 15px;
            border: 1px solid #e1e4e8;
        }
        .toc ul {
            list-style: none;
            padding-left: 0;
            margin: 5px 0 0 0;
        }
        .toc li {
            margin: 5px 0;
        }
        .toc-link {
            color: #0366d6;
            text-decoration: none;
        }
        .toc-link:hover {
            text-decoration: underline;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            .readme-container {
                padding: 10px;
            }
            .readme-content pre {
                padding: 10px;
                font-size: 0.9em;
            }
            .download-sources {
                display: block;
                margin-left: 0;
                margin-top: 4px;
            }
        }
        
        .api-switch {
            margin-top: 10px;
            color: #586069;
        }
        .api-link {
            color: #0366d6;
            text-decoration: none;
        }
        .api-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <h1>ECUST课程分享仓库目录</h1>
    <p>点击目录可以展开查看内容,README文件会自动显示</p>
    <p class="api-switch">
        当前使用GitHub API | 
        <a href="index.html" class="api-link">
            切换到 CNB API版本 🔄
        </a>
    </p>
    
    <div id="tree"></div>
    <div id="readme"></div>
    <p>
        项目Github地址:<a href="https://github.com/ecust-CourseShare/ecust-courseshare.github.io">https://github.com/ecust-CourseShare/ecust-courseshare.github.io</a>
        <br>
        项目CNB地址:<a href="https://cnb.cool/ecustcic/ecust-courseshare.github.io">https://cnb.cool/ecustcic/ecust-courseshare.github.io</a>
        <br>
        课程资源仓库地址:<a href="https://github.com/tianyilt/ecust-CourseShare">https://github.com/tianyilt/ecust-CourseShare</a>
        <br>
        网站Github Pages: <a href="https://ecust-courseshare.github.io/">https://ecust-courseshare.github.io/</a>
        <br>
        网站Edgeone Pages(国内站): <a href="https://ecust-courseshare.bestzyq.cn/">https://ecust-courseshare.bestzyq.cn/</a> 或 <a href="https://ecust-courseshare.ecustvr.top/">https://ecust-courseshare.ecustvr.top/</a>
    </p>

    <script>
        const apiBaseUrl = 'https://api.github.com/repos/tianyilt/ecust-CourseShare/contents/';
        // 下载源配置,可以在这里添加更多下载源
        const downloadSources = [
            {
                name: "Github源",
                url: "https://github.com/tianyilt/ecust-CourseShare/blob/master/{path}"
            },
            {
                name: "Gitcode源",
                url: "https://gitcode.com/ecust/ecust-CourseShare/blob/master/{path}"
            },
            {
                name: "CNB源",
                url: "https://cnb.cool/ecustcic/ecust-CourseShare/-/blob/master/{path}"
            },
            {
                name: "Openlist源",
                url: "https://ss.bestzyq.cn/ecust-CourseShare/{path}"
            }
        ];

        document.addEventListener('DOMContentLoaded', () => {
            loadDirectory('.', 'tree');
        });

        async function loadDirectory(path, targetElementId, parentElement = null) {
            const targetElement = parentElement || document.getElementById(targetElementId);
            const loadingElement = document.createElement('div');
            loadingElement.className = 'loading';
            loadingElement.innerHTML = '<div class="spinner"></div>加载中...';
            
            if (parentElement) {
                targetElement.appendChild(loadingElement);
            } else {
                targetElement.innerHTML = '';
                targetElement.appendChild(loadingElement);
                document.getElementById('readme').innerHTML = '';
            }

            try {
                const contents = await fetchDirectoryContents(path);
                const sortedContents = sortContents(contents);
                displayDirectoryContents(sortedContents, targetElement, loadingElement, path);
                
                if (path === '.') {
                    const readme = findReadme(contents);
                    if (readme) {
                        displayReadme(readme);
                    }
                }
            } catch (error) {
                const errorElement = document.createElement('div');
                errorElement.className = 'error';
                errorElement.textContent = `加载失败: ${error.message}`;
                targetElement.replaceChild(errorElement, loadingElement);
                console.error(error);
            }
        }

        function sortContents(contents) {
            return contents.sort((a, b) => {
                if (a.type === 'dir' && b.type !== 'dir') return -1;
                if (a.type !== 'dir' && b.type === 'dir') return 1;
                
                // 检查是否包含英文字母
                const aHasEnglish = /[a-zA-Z]/.test(a.name);
                const bHasEnglish = /[a-zA-Z]/.test(b.name);
                
                // 如果一个是英文,一个不是英文,英文优先
                if (aHasEnglish && !bHasEnglish) return -1;
                if (!aHasEnglish && bHasEnglish) return 1;
                
                // 如果都是英文或都不是英文,使用原来的排序方式
                return a.name.localeCompare(b.name, 'zh-Hans-CN', {numeric: true});
            });
        }

        function findReadme(contents) {
            return contents.find(item => 
                item.type === 'file' && /readme\.md$/i.test(item.name)
            );
        }

        async function fetchDirectoryContents(path) {
            const url = `${apiBaseUrl}${path}`;
            const response = await fetch(url, {
                headers: {
                    'Accept': 'application/vnd.github.v3+json'
                }
            });
            
            if (!response.ok) {
                if (response.status === 403) {
                    throw new Error('GitHub API 访问频率限制,请稍后再试');
                }
                throw new Error(`GitHub API请求失败: ${response.status} ${response.statusText}`);
            }
            
            const data = await response.json();
            
            // GitHub API 直接返回数组格式的目录内容
            return data.map(entry => ({
                name: entry.name,
                type: entry.type === 'dir' ? 'dir' : 'file',
                path: entry.path,
                sha: entry.sha,
                html_url: `https://raw.githubusercontent.com/tianyilt/ecust-CourseShare/master/${entry.path}`
            }));
        }

        function renderMarkdown(content) {
            const converter = new showdown.Converter({
                tables: true,
                tasklists: true,
                strikethrough: true,
                emoji: true,
                underline: true,
                metadata: true,
                openLinksInNewWindow: true,
                ghCompatibleHeaderId: true,
                ghMentions: true,
                ghMentionsLink: 'https://github.com/{u}',
                encodeEmails: true,
                backslashEscapesHTMLTags: true,
                completeHTMLDocument: false,
                splitAdjacentBlockquotes: true,
                simpleLineBreaks: true,
                requireSpaceBeforeHeadingText: true,
                ghCodeBlocks: true,
                tablesHeaderId: true,
                parseImgDimensions: true,
                excludeTrailingPunctuationFromURLs: true,
                literalMidWordUnderscores: true,
                literalMidWordAsterisks: true,
                smoothLivePreview: true,
                smartIndentationFix: true,
                disableForced4SpacesIndentedSublists: true
            });

            // 添加自定义扩展
            converter.addExtension({
                type: 'lang',
                regex: /> \[!NOTE\]\n>([\s\S]*?)(?=\n\n|$)/g,
                replace: (match, content) => {
                    // 移除所有 > 符号和后面的空格
                    content = content.replace(/^>\s*/gm, '');
                    // 移除开头的空行
                    content = content.replace(/^\n+/, '');
                    // 让 Showdown 处理内容
                    content = converter.makeHtml(content);
                    return `<div class="note">
                        <div class="note-header">
                            <span class="note-icon">📝</span>
                            <span class="note-title">注意</span>
                        </div>
                        <div class="note-content">${content}</div>
                    </div>`;
                }
            }, 'note-block');

            converter.addExtension({
                type: 'lang',
                regex: /> \[!IMPORTANT\]\n>([\s\S]*?)(?=\n\n|$)/g,
                replace: (match, content) => {
                    // 移除所有 > 符号和后面的空格
                    content = content.replace(/^>\s*/gm, '');
                    // 移除开头的空行
                    content = content.replace(/^\n+/, '');
                    // 让 Showdown 处理内容
                    content = converter.makeHtml(content);
                    return `<div class="important">
                        <div class="important-header">
                            <span class="important-icon">⚠️</span>
                            <span class="important-title">重要</span>
                        </div>
                        <div class="important-content">${content}</div>
                    </div>`;
                }
            }, 'important-block');

            // 添加样式
            const style = document.createElement('style');
            style.textContent = `
                .note, .important {
                    margin: 1em 0;
                    padding: 1em;
                    border-radius: 4px;
                }
                .note {
                    background-color: #e7f5ff;
                    border-left: 4px solid #0366d6;
                }
                .important {
                    background-color: #fff3bf;
                    border-left: 4px solid #f08c00;
                }
                .note-header, .important-header {
                    display: flex;
                    align-items: center;
                    margin-bottom: 0.5em;
                    font-weight: bold;
                }
                .note-icon, .important-icon {
                    margin-right: 0.5em;
                    font-size: 1.2em;
                }
                .note-title {
                    color: #0366d6;
                }
                .important-title {
                    color: #f08c00;
                }
                .note-content, .important-content {
                    margin: 0;
                }
                .note-content p, .important-content p {
                    margin: 0.5em 0;
                }
                .note-content p:first-child, .important-content p:first-child {
                    margin-top: 0;
                }
                .note-content p:last-child, .important-content p:last-child {
                    margin-bottom: 0;
                }
            `;
            document.head.appendChild(style);

            // 转换 Markdown
            let html = converter.makeHtml(content);

            // 处理图片
            html = html.replace(/<img src="([^"]+)" alt="([^"]+)"(?: title="([^"]+)")?>/g, (match, src, alt, title) => {
                if (src.startsWith('readme.assets/')) {
                    // 处理相对路径的图片
                    return `<img src="/${src}" alt="${alt}"${title ? ` title="${title}"` : ''}>`;
                }
                return match;
            });

            // 生成目录
            const headings = html.match(/<h[1-3][^>]*>([^<]+)<\/h[1-3]>/g);
            let toc = '';
            if (headings && headings.length > 2) {
                toc = '<div class="toc"><strong>目录</strong><ul>';
                headings.forEach(heading => {
                    const level = heading.match(/<h([1-3])/)[1];
                    const title = heading.match(/>([^<]+)</)[1];
                    const id = title.toLowerCase().replace(/[^\w\u4e00-\u9fa5]+/g, '-');
                    toc += `<li style="margin-left: ${(level - 1) * 15}px">
                              <a href="#${id}" class="toc-link">${title}</a>
                           </li>`;
                });
                toc += '</ul></div>';
            }
            
            return toc + '<div class="markdown-body">' + html + '</div>';
        }

        async function displayReadme(readme) {
            const readmeContainer = document.getElementById('readme');
            readmeContainer.innerHTML = `
                <div class="readme-container">
                    <div class="readme-title">📝 ${readme.name}</div>
                    <div class="loading">
                        <div class="spinner"></div>
                        加载README内容中...
                    </div>
                </div>
            `;
            
            try {
                const response = await fetch(`https://raw.githubusercontent.com/tianyilt/ecust-CourseShare/master/${readme.path}`);
                
                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }
                
                const content = await response.text();
                
                readmeContainer.innerHTML = `
                    <div class="readme-container">
                        <div class="readme-title">📝 ${readme.name} 
                            <a href="${readme.html_url}" target="_blank" style="font-size: 0.8em; margin-left: 10px;">(查看原文)</a>
                        </div>
                        <div class="readme-content">${renderMarkdown(content)}</div>
                    </div>
                `;
            } catch (error) {
                readmeContainer.innerHTML = `
                    <div class="readme-container error">
                        <div class="readme-title">📝 ${readme.name}</div>
                        <div class="error-message">
                            <span class="error-icon">❌</span>
                            无法加载README内容: ${error.message}
                            <button class="retry-btn" onclick="displayReadme(${JSON.stringify(readme).replace(/"/g, '&quot;')})">重试</button>
                        </div>
                    </div>
                `;
            }
        }

        function displayDirectoryContents(contents, targetElement, loadingElement, currentPath) {
            const container = document.createElement('div');
            targetElement.replaceChild(container, loadingElement);

            contents.forEach(item => {
                const itemElement = document.createElement('div');
                
                if (item.type === 'dir') {
                    itemElement.className = 'dir collapsed';
                    itemElement.textContent = item.name;
                    
                    itemElement.addEventListener('click', function(e) {
                        e.stopPropagation();
                        
                        if (this.classList.contains('expanded')) {
                            this.classList.remove('expanded');
                            this.classList.add('collapsed');
                            const childContainer = this.nextElementSibling;
                            if (childContainer) {
                                childContainer.remove();
                            }
                        } else {
                            this.classList.remove('collapsed');
                            this.classList.add('expanded');
                            
                            const childContainer = document.createElement('div');
                            childContainer.style.marginLeft = '20px';
                            this.parentNode.insertBefore(childContainer, this.nextSibling);
                            
                            loadDirectory(item.path, '', childContainer);
                            
                            const readme = findReadme(contents);
                            if (readme && readme.path.startsWith(item.path)) {
                                displayReadme(readme);
                            }
                        }
                    });
                } else {
                    itemElement.className = 'file';
                    const link = document.createElement('a');
                    link.className = 'file-link';
                    link.textContent = item.name;
                    link.href = item.html_url;
                    link.target = '_blank';
                    itemElement.appendChild(link);
                    
                    // 添加下载源链接
                    if (downloadSources.length > 0) {
                        const sourcesContainer = document.createElement('span');
                        sourcesContainer.className = 'download-sources';
                        sourcesContainer.textContent = '下载源: ';
                        
                        downloadSources.forEach((source, index) => {
                            const sourceLink = document.createElement('a');
                            sourceLink.className = 'download-source';
                            sourceLink.textContent = source.name;
                            sourceLink.href = source.url.replace('{path}', item.path);
                            sourceLink.target = '_blank';
                            sourceLink.title = source.url.replace('{path}', item.path);
                            
                            if (index > 0) {
                                sourcesContainer.appendChild(document.createTextNode(' | '));
                            }
                            sourcesContainer.appendChild(sourceLink);
                        });
                        
                        itemElement.appendChild(sourcesContainer);
                    }
                    
                    // 只有在非根目录时才显示README
                    if (/readme\.md$/i.test(item.name) && currentPath !== '.') {
                        displayReadme(item);
                    }
                }
                
                container.appendChild(itemElement);
            });
        }
    </script>
</body>
</html>