前言
写点代码让网页直接展示代码文件的内容!
正文
显示代码文件:codeFile.js
这需要引入:
html
<link rel="stylesheet" href="/css/codeFileTree.css"/>
<script src="/js/highlightjs.js"></script>
<script src="/js/highlightjs-line-numbers.min.js"></script>
<script src="/js/codeFile.js"></script>设计一个 codeFile 类表示文本文件的代码块,用于控制文本文件的相关逻辑:
class CodeFile {
// 静态变量,用来检查初始化函数是否已经调用
static isInitialized = false;
// 静态变量,用来记录所有的实例
static Instances = [];
constructor(link, lang = "", fileName = "", needRender = true) {
this.link = link;
this.fileName = CodeFile.getFileName(link, fileName)
this.lang = CodeFile.getLang(this.fileName, lang);
this.text = "";
this.$codeElement = null;
this.$preElement = null;
this.$root = null;
this.needRender = needRender;
this.rendered = false;
if (!CodeFile.isInitialized) {
CodeFile.isInitialized = true;
try {
hljs.configure({
languages: [] // 禁用所有语言自动检测
});
} catch (error) {
console.log('初始化代码高亮时出错:', error);
}
}
CodeFile.Instances.push(this); // 记录实例
}
static getFileName(link,fileName = "") {
return fileName || link.split('/').pop();
}
static getLang(fileName, lang = "") {
return lang || CodeFile.getLanguageFromExtension(fileName.split('.').pop());
}
async loadFile() {
const url = window.SiteAssets ? window.SiteAssets.resolve(this.link) : this.link;
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('网络响应失败');
}
return response.text();
}).then(data => {
this.text = data;
})
.catch(error => {
console.log('读取文件失败: ' + error.message);
});
}
render(anchor) {
if (this.rendered) {
throw new Error('代码块已渲染');
}
if (!this.needRender) {
throw new Error('代码块不需要渲染');
}
if (!anchor) {
anchor = $(document.currentScript);
}
this.loadFile().then(() => {
let $preElement = $('<pre></pre>');
let $codeElement = $('<code></code>').text(this.text.trim()); // 创建 <code> 元素并设置文本内容
$preElement.addClass('hljs');
$preElement.addClass(this.lang);
$preElement.append($codeElement);
this.$preElement = $preElement;
this.$codeElement = $codeElement;
this.$root = this.$preElement;
anchor.before($preElement);
hljs.highlightBlock(this.$codeElement[0]);
this.rendered = true;
CodeFile.initLineNumbers();
$(document).trigger('CodeFileRendered', [this]);
});
}
destroy() {
this.needRender = false;
this.rendered = false;
this.$root.remove();
}
static initLineNumbers() {
// 判定是否所有代码块都已经渲染完成
CodeFile.Instances.forEach((el) => {
if (!el.rendered && el.needRender) {
return;
}
});
// 启用行号
try {
hljs.initLineNumbersOnLoad();
}
catch (error) {
console.log('初始化行号时出错:', error);
}
}
static getLanguageFromExtension(extension) {
const languageMap = {
'c': 'C',
'cpp': 'C++',
'cc': 'C++',
'cxx': 'C++',
'cs': 'C#',
'java': 'Java',
'py': 'Python',
'js': 'JavaScript',
'ts': 'TypeScript',
'html': 'HTML',
'htm': 'HTML',
'css': 'CSS',
'less': 'LESS',
'sass': 'Sass',
'scss': 'SCSS',
'php': 'PHP',
'rb': 'Ruby',
'swift': 'Swift',
'go': 'Go',
'rs': 'Rust',
'kt': 'Kotlin',
'kts': 'Kotlin',
'm': 'Objective-C',
'h': 'Objective-C',
'r': 'R',
'sql': 'SQL',
'sh': 'Shell',
'bat': 'Batch',
'ps1': 'PowerShell',
'md': 'Markdown',
'json': 'JSON',
'xml': 'XML',
'yaml': 'YAML',
'yml': 'YAML',
'toml': 'TOML',
'lua': 'Lua',
'hs': 'Haskell',
'pl': 'Perl',
'vhd': 'VHDL',
'vhdl': 'VHDL',
'v': 'Verilog',
'sv': 'Verilog',
'asm': 'Assembly',
'tex': 'LaTeX',
'sty': 'LaTeX',
'styl': 'Stylus',
'vue': 'Vue',
'hlsl': 'HLSL',
'glsl': 'GLSL',
'ini': 'INI',
'conf': 'INI',
'cfg': 'INI',
};
// 获取后缀并转换为小写,避免大小写不一致
extension = extension.toLowerCase();
// 返回对应的语言,若没有找到则返回未知
return languageMap[extension] || 'plaintext';
}
}
具有如下功能:
-
自动根据文件地址返回代码语言,渲染代码块
提示
fetch()是一个用于发送网络请求的 JavaScript 原生 API,基于Promise,用于替代传统的XMLHttpRequest。它可以发起各种 HTTP 请求(如 GET、POST 等),并处理响应数据。基本用法:
javascriptfetch(url, options) .then(response => response.json()) // 解析响应数据 .then(data => console.log(data)) // 使用响应数据 .catch(error => console.error(error)); // 错误处理 -
使用
highlight.js进行代码高亮:提示
text`highlight.js` 会将识别下列结构:html<pre class="hljs lang"><code></code></pre> -
使用
highlightjs-line-numbers.min.js给代码块添加行号。提示
这段代码将扫描网页中的所有高亮后的代码块并添加行号。
javascripthljs.initLineNumbersOnLoad(); -
所有代码块实例渲染完后,派发消息
allCodeFilesRendered供其它代码使用。 -
销毁代码块
使用如下代码将文本文件内容渲染成代码块:
html
<script>new CodeFile("XXX.c").render();</script>代码文件工具栏:codeFileTools.js
这需要引入:
html
<link rel="stylesheet" href="/css/codeFileTree.css"/>
<link rel="stylesheet" type="text/css" href="/css/codeFileTools.css">
<script src="/js/highlightjs.js"></script>
<script src="/js/highlightjs-line-numbers.min.js"></script>
<script src="/js/codeFile.js"></script>
<script src="/js/codeFileTools.js"></script>正在加载图表…
给创建的代码块添加一个工具栏,具有如下功能:
- 收缩代码块
- 显示文件名
- 复制文件内容
- 下载文件
const DOWNLOAD_ICON = '/images/icon/download.webp';
$(document).on('CodeFileRendered', function (_, data) {
createCodeFileTools(data);
});
function createCodeFileTools(codeFile) {
codeFile.$preElement.wrap(`<figure class="code-file"></figure>`);
codeFile.$root = codeFile.$preElement.parent();
var $codeFileTools = $('<div class="code-file-tools"></div>');
codeFile.$preElement.before($codeFileTools);
codeFile.$preElement.css('maxHeight', HIGHLIGHT_SHRINK);
// 关闭代码块按钮
var $closeCodeBlockButton = $('<button class="close-code-block-button" type="button" title="close-code-block-button"></button>').css('backgroundImage', 'url("' + CLOSE_CODE_BLOCK_ICON + '")');
$codeFileTools.append($closeCodeBlockButton);
if (HIGHLIGHT_SHRINK == 'true') {
var $hljs = codeFile.$codeElement.find('.hljs');
$closeCodeBlockButton.css('transform', "rotate(-90deg)");
$hljs.addClass("closed");
}
$closeCodeBlockButton.click(function () {
if (!codeFile.$codeElement.hasClass('closed')) {
$closeCodeBlockButton.css('transform', "rotate(-90deg)");
codeFile.$codeElement.addClass("closed");
} else {
$closeCodeBlockButton.css('transform', "rotate(0deg)");
codeFile.$codeElement.removeClass("closed");
}
});
// 显示文件名
$codeFileTools.append($('<span class="code-file-name">' + codeFile.fileName + '</span>'));
// 复制按钮
var $copyButton = $('<button class="copy-button" type="button" title="复制代码"></button>').css('backgroundImage', 'url("' + COPY_ICON + '")');
$codeFileTools.append($copyButton);
$copyButton.click(function () {
// 创建已复制提示文字
var $span = $('<span class="copy-notice">已复制</span>');
$codeFileTools.append($span);
// 执行复制操作
navigator.clipboard.writeText(codeFile.text).then(function () {
// 显示已复制提示,并在 1 秒后隐藏
$span.css('opacity', 1);
setTimeout(function () {
$span.css('opacity', 0);
setTimeout(function () {
$span.remove();
}, 500);
}, 1000);
}).catch(function (err) {
// 如果复制失败,显示错误信息
console.error('Failed to copy text:', err);
$span.remove();
});
});
// 下载按钮
var $downloadButton = $('<button class="download-button" type="button" title="下载代码文件"></button>').css('backgroundImage', 'url("' + DOWNLOAD_ICON + '")');
$codeFileTools.append($downloadButton);
function downloadFileFromUrl(url, filename) {
url = window.SiteAssets ? window.SiteAssets.resolve(url) : url;
fetch(url)
.then(response => response.blob())
.then(blob => {
const a = document.createElement('a');
const fileURL = URL.createObjectURL(blob);
a.href = fileURL;
a.download = filename;
a.click();
URL.revokeObjectURL(fileURL); // 释放 URL 对象
})
.catch(error => console.error('Error fetching the file:', error));
}
$downloadButton.click(function () {
downloadFileFromUrl(codeFile.link, codeFile.fileName);
});
}
其余的交给 CSS(为了适应主题随便写写)。
.code-file {
margin: 5px 0;
border: 2px solid var(--border);
tab-size: 4;
}
table.hljs-ln {
display: contents;
font-size: 15px;
}
.hljs-ln-n {
border-right: 1px solid var(--border);
padding: 0 10px;
color: var(--th-text);
font-size: 15px;
border: none;
}
td.hljs-ln-code {
padding: 0 10px !important;
border: none;
}
.hljs-ln-line {
border: none;
line-height: 1.5em;
}
pre.hljs {
overflow: auto;
background-color: var(--tabs-bg);
}
table.hljs-ln tr:first-child>.hljs-ln-line {
padding-top: 10px !important;
}
table.hljs-ln tr:last-child>.hljs-ln-line {
padding-bottom: 10px !important;
}
.hljs-ln-numbers {
border-right: 1px solid var(--border) !important;
}
.code-file-tools {
background: var(--highlight-tools-bg);
position: relative;
height: 32px;
}
.code-file-tools>.code-file-name {
margin-left: 10px;
line-height: 32px;
font-weight: bold;
position: absolute;
left: 30px;
font-size: 18px;
color: var(--th-text);
font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace;
}
.code-file-tools>.download-button,
.code-file-tools>.copy-button {
position: absolute;
width: 18px;
height: 18px;
border: none;
background-color: rgba(0, 0, 0, 0);
background-size: cover;
top: 50%;
transform: translateY(-50%);
}
.code-file-tools>.download-button {
right: 6px;
}
.code-file-tools>.copy-button {
right: 30px;
}
.code-file-tools>.download-button:hover,
.code-file-tools>.copy-button:hover {
cursor: pointer;
filter: brightness(120%);
}
.code-file-tools>.close-code-block-button {
position: absolute;
width: 16px;
height: 16px;
bottom: 8px;
left: 6px;
border: none;
background-color: rgba(0, 0, 0, 0);
background-size: cover;
transition: transform 0.5s;
}
.code-file-tools>.close-code-block-button:hover {
cursor: pointer;
}
.code-file code.closed {
display: none;
}
.code-file-tools>.copy-notice {
line-height: 32px;
font-weight: 500;
position: absolute;
right: 56px;
font-size: 14px;
opacity: 0;
transition: opacity 0.5s;
color: var(--th-text);
-webkit-user-select: none;
/* Safari */
-moz-user-select: none;
/* Firefox */
-ms-user-select: none;
/* IE 10+ */
user-select: none;
}显示代码文件树状结构:codeFileTree.js
在 codeFile 类的基础上,借助 jstree,实现树状文件结构的展示!设计 CodeFileTreeNode 类和 CodeFileTree 类:
正在加载图表…
这需要引入:
html
<link href="/css/fontawesome/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="/css/jsTreeList.css"/>
<link rel="stylesheet" href="/js/jsTree/dist/themes/default/style.min.css"/>
<link rel="stylesheet" href="/css/codeFileTree.css"/>
<script src="/js/jsTree/dist/jstree.min.js"></script>
<script src="/js/highlightjs.js"></script>
<script src="/js/highlightjs-line-numbers.min.js"></script>
<script src="/js/codeFile.js"></script>
<script src="/js/codeFileTree.js"></script>再写个 CSS,大功告成!
使用方法:
html
<script>
// new CodeFileTreeNode(ID, 是否为文件夹, 文件路径);
const codeFileTreeCSS = new CodeFileTreeNode('node1', false, '/css/codeFileTree.css');
const codeFileTreeJS = new CodeFileTreeNode('node2', false, '/js/codeFileTree.js');
const jsNode = new CodeFileTreeNode('node3', true, 'js', [codeFileTreeJS]);
const cssNode = new CodeFileTreeNode('node4', true, 'css', [codeFileTreeCSS]);
const sourceNode = new CodeFileTreeNode('node5', true, 'source', [jsNode, cssNode]);
// new CodeFileTree(ID, 根节点, 默认节点)
new CodeFileTree('tree1', sourceNode, codeFileTreeJS).render();
</script>效果(点击文件图标展示文件内容):
class CodeFileTreeNode {
constructor(id, isFolder, linkOrFolderName, children, lang, fileName, icon, opened = true) {
this.id = id;
this.isFolder = isFolder;
this.opened = opened;
if (isFolder) {
this.folderName = linkOrFolderName;
this.children = children;
this.icon = icon || "far fa-folder";
} else {
this.link = linkOrFolderName;
this.fileName = CodeFile.getFileName(linkOrFolderName, fileName);
this.lang = CodeFile.getLang(linkOrFolderName, lang);
this.icon = icon || "far fa-file-code";
if (children) {
throw new Error("CodeFileTreeNode should not have children if it is a file.");
}
}
}
// 添加转换到 jsTree 数据的方法
convertToJsTreeData() {
let node;
if (this.isFolder) {
node = {
id: this.id,
text: this.folderName,
children: [],
state: {
opened: this.opened
},
icon: this.icon,
data: {
isFolder: true,
},
};
} else {
node = {
id: this.id,
text: this.fileName,
children: [],
state: {
opened: this.opened
},
icon: this.icon,
data: {
isFolder: false,
link: this.link,
lang: this.lang,
fileName: this.fileName,
}
};
}
if (this.children && Array.isArray(this.children)) {
node.children = this.children.map(childNode => childNode.convertToJsTreeData());
}
return node;
}
}
class CodeFileTree {
constructor(id, root, defaultNode) {
this.id = id;
this.root = root;
this.defaultNode = defaultNode;
this.jsTreeData = "";
this.codeFile = null;
this.jsTree = null;
this.container = null;
}
render() {
this.jsTreeData = this.root.convertToJsTreeData();
this.jsTree = $(`<div id="${this.id}"></div>`).insertBefore(document.currentScript);
this.container = this.jsTree.wrap(`<div class="code-file-tree-container"></div>`);
const $this = this;
$(document).ready(function () {
$("#" + $this.id).jstree({
'core': {
'data': $this.jsTreeData, // 将解析后的数据传递给 jsTree
}
}).on('select_node.jstree', function (e, data) {
const node = data.node;
if (!node.data.isFolder) {
// console.log('你点击了文件:' + node.text, node); // 弹出点击的节点文本
try {
if (!$this.codeFile ||
$this.codeFile.link !== node.data.link ||
$this.codeFile.lang !== node.data.lang ||
$this.codeFile.fileName !== node.data.fileName) {
if ($this.codeFile) {
$this.codeFile.destroy();
}
$this.codeFile = new CodeFile(node.data.link, node.data.lang, node.data.fileName, true);
$this.codeFile.render($this.jsTree);
}
} catch (error) {
console.error("代码文件加载失败:", error);
}
} else {
// console.log('你点击了文件夹:' + node.text, node); // 弹出点击的节点文本
}
}).on('ready.jstree', function() {
if($this.defaultNode) {
$("#" + $this.id).jstree('select_node', $this.defaultNode.id);
}
});
});
}
}