chore: render code style clean and update (#2477)

This commit is contained in:
Koy Zhuang 2024-09-12 10:46:39 +08:00 committed by GitHub
parent beb86a3e17
commit 5f80683369
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 108 additions and 126 deletions

View File

@ -5,63 +5,18 @@ import { tree as treeTpl } from './tpl.js';
import { genTree } from './gen-tree.js';
import { slugify } from './slugify.js';
import { emojify } from './emojify.js';
import {
getAndRemoveConfig,
removeAtag,
getAndRemoveDocsifyIgnoreConfig,
} from './utils.js';
import { getAndRemoveConfig } from './utils.js';
import { imageCompiler } from './compiler/image.js';
import { headingCompiler } from './compiler/heading.js';
import { highlightCodeCompiler } from './compiler/code.js';
import { paragraphCompiler } from './compiler/paragraph.js';
import { taskListCompiler } from './compiler/taskList.js';
import { taskListItemCompiler } from './compiler/taskListItem.js';
import { linkCompiler } from './compiler/link.js';
import { compileMedia } from './compiler/media.js';
const cachedLinks = {};
const compileMedia = {
markdown(url) {
return {
url,
};
},
mermaid(url) {
return {
url,
};
},
iframe(url, title) {
return {
html: `<iframe src="${url}" ${
title || 'width=100% height=400'
}></iframe>`,
};
},
video(url, title) {
return {
html: `<video src="${url}" ${title || 'controls'}>Not Support</video>`,
};
},
audio(url, title) {
return {
html: `<audio src="${url}" ${title || 'controls'}>Not Support</audio>`,
};
},
code(url, title) {
let lang = url.match(/\.(\w+)$/);
lang = title || (lang && lang[1]);
if (lang === 'md') {
lang = 'markdown';
}
return {
url,
lang,
};
},
};
export class Compiler {
constructor(config, router) {
this.config = config;
@ -173,7 +128,7 @@ export class Compiler {
type = 'audio';
}
embed = compileMedia[type].call(this, href, title);
embed = compileMedia[type](href, title);
embed.type = type;
}
@ -198,47 +153,22 @@ export class Compiler {
_initRenderer() {
const renderer = new marked.Renderer();
const { linkTarget, linkRel, router, contentBase } = this;
const _self = this;
// Supports mermaid
const origin = {};
/**
* Render anchor tag
* @link https://github.com/markedjs/marked#overriding-renderer-methods
* @param {String} tokens the content tokens
* @param {Number} depth Type of heading (h<level> tag)
* @returns {String} Heading element
*/
origin.heading = renderer.heading = function ({ tokens, depth }) {
const text = this.parser.parseInline(tokens);
let { str, config } = getAndRemoveConfig(text);
const nextToc = { depth, title: str };
const { content, ignoreAllSubs, ignoreSubHeading } =
getAndRemoveDocsifyIgnoreConfig(str);
str = content.trim();
nextToc.title = removeAtag(str);
nextToc.ignoreAllSubs = ignoreAllSubs;
nextToc.ignoreSubHeading = ignoreSubHeading;
const slug = slugify(config.id || str);
const url = router.toURL(router.getCurrentPath(), { id: slug });
nextToc.slug = url;
_self.toc.push(nextToc);
// Note: tabindex="-1" allows programmatically focusing on heading
// elements after navigation. This is preferred over focusing on the link
// within the heading because it matches the focus behavior of screen
// readers when navigating page content.
return `<h${depth} id="${slug}" tabindex="-1"><a href="${url}" data-id="${slug}" class="anchor"><span>${str}</span></a></h${depth}>`;
};
// renderer customizers
origin.heading = headingCompiler({
renderer,
router,
compiler: this,
});
origin.code = highlightCodeCompiler({ renderer });
origin.link = linkCompiler({
renderer,
router,
linkTarget,
linkRel,
compilerClass: _self,
compiler: this,
});
origin.paragraph = paragraphCompiler({ renderer });
origin.image = imageCompiler({ renderer, contentBase, router });

View File

@ -0,0 +1,31 @@
import {
getAndRemoveConfig,
removeAtag,
getAndRemoveDocsifyIgnoreConfig,
} from '../utils.js';
import { slugify } from '../slugify.js';
export const headingCompiler = ({ renderer, router, compiler }) =>
(renderer.heading = function ({ tokens, depth }) {
const text = this.parser.parseInline(tokens);
let { str, config } = getAndRemoveConfig(text);
const nextToc = { depth, title: str };
const { content, ignoreAllSubs, ignoreSubHeading } =
getAndRemoveDocsifyIgnoreConfig(str);
str = content.trim();
nextToc.title = removeAtag(str);
nextToc.ignoreAllSubs = ignoreAllSubs;
nextToc.ignoreSubHeading = ignoreSubHeading;
const slug = slugify(config.id || str);
const url = router.toURL(router.getCurrentPath(), { id: slug });
nextToc.slug = url;
compiler.toc.push(nextToc);
// Note: tabindex="-1" allows programmatically focusing on heading
// elements after navigation. This is preferred over focusing on the link
// within the heading because it matches the focus behavior of screen
// readers when navigating page content.
return `<h${depth} id="${slug}" tabindex="-1"><a href="${url}" data-id="${slug}" class="anchor"><span>${str}</span></a></h${depth}>`;
});

View File

@ -1,27 +0,0 @@
import {
getAndRemoveConfig,
removeAtag,
getAndRemoveDocsifyIgnoreConfig,
} from '../utils.js';
import { slugify } from './slugify.js';
export const headingCompiler = ({ renderer, router, _self }) =>
(renderer.code = (text, level) => {
let { str, config } = getAndRemoveConfig(text);
const nextToc = { level, title: str };
const { content, ignoreAllSubs, ignoreSubHeading } =
getAndRemoveDocsifyIgnoreConfig(str);
str = content.trim();
nextToc.title = removeAtag(str);
nextToc.ignoreAllSubs = ignoreAllSubs;
nextToc.ignoreSubHeading = ignoreSubHeading;
const slug = slugify(config.id || str);
const url = router.toURL(router.getCurrentPath(), { id: slug });
nextToc.slug = url;
_self.toc.push(nextToc);
return /* html */ `<h${level} id="${slug}"><a href="${url}" data-id="${slug}" class="anchor"><span>${str}</span></a></h${level}>`;
});

View File

@ -6,7 +6,7 @@ export const linkCompiler = ({
router,
linkTarget,
linkRel,
compilerClass,
compiler,
}) =>
(renderer.link = function ({ href, title = '', tokens }) {
const attrs = [];
@ -15,16 +15,16 @@ export const linkCompiler = ({
linkTarget = config.target || linkTarget;
linkRel =
linkTarget === '_blank'
? compilerClass.config.externalLinkRel || 'noopener'
? compiler.config.externalLinkRel || 'noopener'
: '';
title = str;
if (
!isAbsolutePath(href) &&
!compilerClass._matchNotCompileLink(href) &&
!compiler._matchNotCompileLink(href) &&
!config.ignore
) {
if (href === compilerClass.config.homepage) {
if (href === compiler.config.homepage) {
href = 'README';
}

View File

@ -0,0 +1,42 @@
export const compileMedia = {
markdown(url) {
return {
url,
};
},
mermaid(url) {
return {
url,
};
},
iframe(url, title) {
return {
html: `<iframe src="${url}" ${
title || 'width=100% height=400'
}></iframe>`,
};
},
video(url, title) {
return {
html: `<video src="${url}" ${title || 'controls'}>Not Support</video>`,
};
},
audio(url, title) {
return {
html: `<audio src="${url}" ${title || 'controls'}>Not Support</audio>`,
};
},
code(url, title) {
let lang = url.match(/\.(\w+)$/);
lang = title || (lang && lang[1]);
if (lang === 'md') {
lang = 'markdown';
}
return {
url,
lang,
};
},
};

View File

@ -82,7 +82,7 @@ export function Render(Base) {
}
}
this._renderTo(markdownElm, html);
dom.setHTML(markdownElm, html);
// Execute markdown <script>
if (
@ -274,13 +274,6 @@ export function Render(Base) {
}
}
_renderTo(el, content, replace) {
const node = dom.getNode(el);
if (node) {
node[replace ? 'outerHTML' : 'innerHTML'] = content;
}
}
_renderSidebar(text) {
const { maxLevel, subMaxLevel, loadSidebar, hideSidebar } = this.config;
const sidebarEl = dom.getNode('aside.sidebar');
@ -294,7 +287,7 @@ export function Render(Base) {
return null;
}
this._renderTo('.sidebar-nav', this.compiler.sidebar(text, maxLevel));
dom.setHTML('.sidebar-nav', this.compiler.sidebar(text, maxLevel));
sidebarToggleEl.setAttribute('aria-expanded', !isMobile());
@ -366,7 +359,7 @@ export function Render(Base) {
const html = this.compiler.compile(text);
['.app-nav', '.app-nav-merged'].forEach(selector => {
this._renderTo(selector, html);
dom.setHTML(selector, html);
this.#addTextAsTitleAttribute(`${selector} a`);
});
}
@ -507,7 +500,7 @@ export function Render(Base) {
rootElm.style.setProperty('--cover-bg', mdCoverBg);
}
this._renderTo('.cover-main', html);
dom.setHTML('.cover-main', html);
// Button styles
dom
@ -563,7 +556,7 @@ export function Render(Base) {
html += tpl.main(config);
// Render main app
this._renderTo(el, html, true);
dom.setHTML(el, html, true);
} else {
this.rendered = true;
}

View File

@ -71,7 +71,7 @@ export class HashHistory extends History {
/**
* Parse the url
* @param {string} [path=location.herf] URL to be parsed
* @param {string} [path=location.href] URL to be parsed
* @return {object} { path, query }
*/
parse(path = location.href) {

View File

@ -20,6 +20,19 @@ export function getNode(el, noCache = false) {
return el;
}
/**
*
* @param {*} el the targt element or the selector
* @param {*} content the content to be rendered as HTML
* @param {*} replace To replace the content (true) or insert instead (false) , default is false
*/
export function setHTML(el, content, replace) {
const node = getNode(el);
if (node) {
node[replace ? 'outerHTML' : 'innerHTML'] = content;
}
}
export const $ = document;
export const body = $.body;