diff --git a/blog.config.js b/blog.config.js index dfd1498c..2a2ce299 100644 --- a/blog.config.js +++ b/blog.config.js @@ -98,6 +98,7 @@ const BLOG = { 'https://npm.elemecdn.com/prism-themes/themes/prism-a11y-dark.min.css', // 代码样式主题 更多参考 https://github.com/PrismJS/prism-themes CODE_MAC_BAR: process.env.NEXT_PUBLIC_CODE_MAC_BAR || true, // 代码左上角显示mac的红黄绿图标 CODE_LINE_NUMBERS: process.env.NEXT_PUBLIC_CODE_LINE_NUMBERS || 'false', // 是否显示行号 + CODE_COLLAPSE: process.env.NEXT_PUBLIC_CODE_COLLAPSE || 'false', // 是否折叠代码框 // Mermaid 图表CDN MERMAID_CDN: process.env.NEXT_PUBLIC_MERMAID_CDN || 'https://cdn.jsdelivr.net/npm/mermaid@10.2.2/dist/mermaid.min.js', // CDN diff --git a/components/PrismMac.js b/components/PrismMac.js index 01f4e65b..9e684d6a 100644 --- a/components/PrismMac.js +++ b/components/PrismMac.js @@ -15,6 +15,7 @@ import { loadExternalResource } from '@/lib/utils' import { useRouter } from 'next/navigation' /** + * 代码美化相关 * @author https://github.com/txs/ * @returns */ @@ -31,11 +32,59 @@ const PrismMac = () => { } renderPrismMac() renderMermaid() + renderCollapseCode() }) }, [router]) return <>> } +/** + * 将代码块转为可折叠对象 + */ +const renderCollapseCode = () => { + if (!JSON.parse(BLOG.CODE_COLLAPSE)) { + return + } + const codeBlocks = document.querySelectorAll('.code-toolbar') + for (const codeBlock of codeBlocks) { + // 判断当前元素是否被包裹 + if (codeBlock.closest('.collapse-wrapper')) { + continue // 如果被包裹了,跳过当前循环 + } + + const code = codeBlock.querySelector('code') + const language = code.getAttribute('class').match(/language-(\w+)/)[1] + + const collapseWrapper = document.createElement('div') + collapseWrapper.className = 'collapse-wrapper w-full py-2' + const panelWrapper = document.createElement('div') + panelWrapper.className = 'border rounded-md border-indigo-500' + + const header = document.createElement('div') + header.className = 'flex justify-between items-center px-4 py-2 cursor-pointer select-none' + header.innerHTML = `