fix(@vant/cli): added markdown link open plugin (#9597)

This commit is contained in:
neverland
2021-09-30 10:45:55 +08:00
committed by GitHub
parent 6a054ca0e3
commit 1457a27fb4
4 changed files with 61 additions and 12 deletions
+1
View File
@@ -34,6 +34,7 @@
"@types/fs-extra": "^9.0.12",
"@types/less": "^3.0.3",
"@types/lodash": "^4.14.173",
"@types/markdown-it": "^12.2.1",
"@types/postcss-load-config": "^3.0.1",
"@vue/compiler-sfc": "3.2.12",
"vue": "3.2.12"
@@ -1,5 +1,8 @@
<template>
<div :class="['van-doc-content', `van-doc-content--${currentPage}`]">
<div
:class="['van-doc-content', `van-doc-content--${currentPage}`]"
@click="onClick"
>
<slot />
</div>
</template>
@@ -18,19 +21,18 @@ export default {
},
},
mounted() {
const anchors = [].slice.call(this.$el.querySelectorAll('h2, h3, h4, h5'));
anchors.forEach((anchor) => {
anchor.addEventListener('click', this.scrollToAnchor);
});
},
methods: {
scrollToAnchor(event) {
if (event.target.id) {
onClick({ target }) {
if (['H2', 'H3', 'H4', 'H5'].includes(target.tagName)) {
this.scrollToAnchor(target);
}
},
scrollToAnchor(target) {
if (target.id) {
this.$router.push({
name: this.$route.name,
hash: '#' + event.target.id,
hash: '#' + target.id,
});
}
},
+23 -1
View File
@@ -13,6 +13,7 @@ import {
} from '../common/constant';
import { injectHtml } from 'vite-plugin-html';
import type { InlineConfig } from 'vite';
import type MarkdownIt from 'markdown-it';
function markdownHighlight(str: string, lang: string) {
if (lang && hljs.getLanguage(lang)) {
@@ -40,6 +41,24 @@ function markdownCardWrapper(htmlCode: string) {
.join('');
}
// add target="_blank" to all links
function markdownLinkOpen(md: MarkdownIt) {
const defaultRender =
md.renderer.rules.link_open ||
((tokens, idx, options, env, self) =>
self.renderToken(tokens, idx, options));
md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
const aIndex = tokens[idx].attrIndex('target');
if (aIndex < 0) {
tokens[idx].attrPush(['target', '_blank']); // add new attribute
}
return defaultRender(tokens, idx, options, env, self);
};
}
function getSiteConfig(vantConfig: any) {
const siteConfig = vantConfig.site;
@@ -96,9 +115,12 @@ export function getViteConfigForSiteDev(): InlineConfig {
markdownItOptions: {
highlight: markdownHighlight,
},
markdownItSetup(md: any) {
markdownItSetup(md: MarkdownIt) {
const { slugify } = require('transliteration');
const markdownItAnchor = require('markdown-it-anchor');
markdownLinkOpen(md);
md.use(markdownItAnchor, {
level: 2,
slugify,