You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.3 KiB
82 lines
2.3 KiB
'use strict'
|
|
|
|
import Plugin from "markdown-it-regexp";
|
|
import extend from "extend";
|
|
import sanitize from "sanitize-filename";
|
|
|
|
export default (options) => {
|
|
const defaults = {
|
|
baseURL: '/',
|
|
relativeBaseURL: './',
|
|
makeAllLinksAbsolute: false,
|
|
uriSuffix: '.html',
|
|
htmlAttributes: {
|
|
},
|
|
generatePageNameFromLabel: (label) => {
|
|
return label
|
|
},
|
|
postProcessPageName: (pageName) => {
|
|
pageName = pageName.trim()
|
|
pageName = pageName.split('/').map(sanitize).join('/')
|
|
pageName = pageName.replace(/\s+/g, '_')
|
|
return pageName
|
|
},
|
|
postProcessLabel: (label) => {
|
|
label = label.trim()
|
|
return label
|
|
}
|
|
}
|
|
|
|
options = extend(true, defaults, options)
|
|
|
|
function isAbsolute(pageName) {
|
|
return options.makeAllLinksAbsolute || pageName.charCodeAt(0) === 0x2F/* / */
|
|
}
|
|
|
|
function removeInitialSlashes(str) {
|
|
return str.replace(/^\/+/g, '')
|
|
}
|
|
|
|
return Plugin(
|
|
/(#?)\[\[([^\]]+)\]\]/,
|
|
(match, utils) => {
|
|
let label = ''
|
|
let pageName = ''
|
|
let href = ''
|
|
let htmlAttrs = []
|
|
let htmlAttrsString = ''
|
|
|
|
let tag = match[1]
|
|
|
|
label = match[2]
|
|
pageName = options.generatePageNameFromLabel(label)
|
|
|
|
label = options.postProcessLabel(label)
|
|
pageName = options.postProcessPageName(pageName)
|
|
|
|
// make sure none of the values are empty
|
|
if (!label || !pageName) {
|
|
return match.input
|
|
}
|
|
|
|
if (isAbsolute(pageName)) {
|
|
pageName = removeInitialSlashes(pageName)
|
|
href = options.baseURL + pageName + options.uriSuffix
|
|
}
|
|
else {
|
|
href = options.relativeBaseURL + pageName + options.uriSuffix
|
|
}
|
|
href = utils.escape(href)
|
|
|
|
htmlAttrs.push(`href="${href}"`)
|
|
for (let attrName in options.htmlAttributes) {
|
|
const attrValue = options.htmlAttributes[attrName]
|
|
htmlAttrs.push(`${attrName}="${attrValue}"`)
|
|
}
|
|
htmlAttrsString = htmlAttrs.join(' ')
|
|
|
|
return `<a ${htmlAttrsString}>${tag}${label}</a>`
|
|
}
|
|
)
|
|
}
|