Skip to content

Commit

Permalink
chore: render code style clean and update (#2477)
Browse files Browse the repository at this point in the history
  • Loading branch information
Koooooo-7 committed Sep 12, 2024
1 parent beb86a3 commit 5f80683
Show file tree
Hide file tree
Showing 8 changed files with 108 additions and 126 deletions.
94 changes: 12 additions & 82 deletions src/core/render/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -173,7 +128,7 @@ export class Compiler {
type = 'audio';
}

embed = compileMedia[type].call(this, href, title);
embed = compileMedia[type](href, title);
embed.type = type;
}

Expand All @@ -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 });
Expand Down
31 changes: 31 additions & 0 deletions src/core/render/compiler/heading.js
Original file line number Diff line number Diff line change
@@ -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}>`;
});
27 changes: 0 additions & 27 deletions src/core/render/compiler/headline.js

This file was deleted.

8 changes: 4 additions & 4 deletions src/core/render/compiler/link.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const linkCompiler = ({
router,
linkTarget,
linkRel,
compilerClass,
compiler,
}) =>
(renderer.link = function ({ href, title = '', tokens }) {
const attrs = [];
Expand All @@ -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';
}

Expand Down
42 changes: 42 additions & 0 deletions src/core/render/compiler/media.js
Original file line number Diff line number Diff line change
@@ -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,
};
},
};
17 changes: 5 additions & 12 deletions src/core/render/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export function Render(Base) {
}
}

this._renderTo(markdownElm, html);
dom.setHTML(markdownElm, html);

// Execute markdown <script>
if (
Expand Down Expand Up @@ -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');
Expand All @@ -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());

Expand Down Expand Up @@ -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`);
});
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/router/history/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
13 changes: 13 additions & 0 deletions src/core/util/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 5f80683

Please sign in to comment.