fix: code style lost in downloaded html file (#73)

* fix: color of the html export button in dark mode

* fix: code style lost in downloaded html file

* fix: adjust for which span includes code

* fix #71
This commit is contained in:
小树 2021-10-30 22:54:41 +08:00 committed by GitHub
parent 544483c43c
commit 150435efa2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 71 additions and 4 deletions

View File

@ -121,7 +121,8 @@
::v-deep .el-icon-upload,
.el-icon-download,
.el-icon-refresh,
.el-icon-s-grid {
.el-icon-s-grid,
.el-icon-document {
color: @nightWhiteColor;
}

View File

@ -242,9 +242,12 @@ export function downloadMD(doc) {
/**
* 导出 HTML 生成内容
* @param {HTML生成内容} htmlStr
*/
export function exportHTML(htmlStr) {
export function exportHTML() {
const element = document.querySelector("#output");
setStyles(element);
const htmlStr = element.innerHTML;
const downLink = document.createElement("a");
downLink.download = "content.html";
@ -257,6 +260,50 @@ export function exportHTML(htmlStr) {
document.body.appendChild(downLink);
downLink.click();
document.body.removeChild(downLink);
function setStyles(element) {
switch (true) {
case isSection(element):
case isPre(element):
case isCode(element):
case isSpan(element):
element.setAttribute("style", getElementStyles(element));
default:
}
if (element.children.length) {
Array.from(element.children).forEach((child) => setStyles(child));
}
// 判断是否是包裹代码块的 section 元素
function isSection(element) {
return (
element.tagName === "SECTION" &&
Array.from(element.classList).includes("code-snippet__github")
);
}
// 判断是否是包裹代码块的 pre 元素
function isPre(element) {
return (
element.tagName === "PRE" &&
Array.from(element.classList).includes("code__pre")
);
}
// 判断是否是包裹代码块的 code 元素
function isCode(element) {
return (
element.tagName === "CODE" &&
Array.from(element.classList).includes("prettyprint")
);
}
// 判断是否是包裹代码字符的 span 元素
function isSpan(element) {
return (
element.tagName === "SPAN" &&
(isCode(element.parentElement) ||
isCode(element.parentElement.parentElement))
);
}
}
}
/**
@ -313,3 +360,17 @@ export function checkImage(file) {
}
return { ok: true };
}
/**
* 获取一个 DOM 元素的所有样式
* @param {DOM 元素} element DOM 元素
* @param {排除的属性} excludes 如果某些属性对结果有不良影响可以使用这个参数来排除
* @returns 行内样式拼接结果
*/
function getElementStyles(element, excludes = ["width", "height"]) {
const styles = getComputedStyle(element, null);
return Object.entries(styles)
.filter(([key]) => styles.getPropertyValue(key) && !excludes.includes(key))
.map(([key, value]) => `${key}:${value};`)
.join("");
}

View File

@ -334,7 +334,12 @@ export default {
},
// HTML
exportEditorContent() {
exportHTML(this.output);
this.$nextTick(() => {
exportHTML();
})
},
//
formatContent() {