UNPKG

@diplodoc/transform

Version:

A simple transformer of text in YFM (Yandex Flavored Markdown) to HTML

73 lines 3.2 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const markdown_it_1 = __importDefault(require("markdown-it")); const path_1 = require("path"); const url_1 = __importDefault(require("url")); const utils_1 = require("../../utils"); const utilsFS_1 = require("../../utilsFS"); const index_1 = __importDefault(require("./index")); const replaceLinkHref = (input, href, newHref) => { /* Try not replace include syntax */ return input.replace(`](${href})`, `](${newHref})`); }; /* Replace the links to the markdown and yaml files if the singlePage option is passed in the options * Example: replace [Text](../../path/to/file.md#anchor) with [Text](#_path_to_file_anchor) * */ const collect = (input, options) => { const { root, path: startPath, singlePage } = options; if (!singlePage) { return; } let result = input; /* Syntax "{% include [Text](_includes/file.md) %}" is parsed as link. Need to ignore errors */ const needSkipLinkFn = (href) => href.includes(`_includes${path_1.sep}`); const transformLink = (href) => href; const md = new markdown_it_1.default().use(index_1.default, Object.assign(Object.assign({}, options), { transformLink, needSkipLinkFn })); const tokens = md.parse(result, {}); let i = 0; while (i < tokens.length) { if (tokens[i].type === 'inline') { const childrenTokens = tokens[i].children || []; let j = 0; while (j < childrenTokens.length) { const isLinkOpenToken = childrenTokens[j].type === 'link_open'; if (!isLinkOpenToken) { j++; continue; } const linkToken = childrenTokens[j]; const href = (0, utils_1.getHrefTokenAttr)(linkToken); const isIncludeLink = (0, utilsFS_1.resolveRelativePath)(startPath, href).includes(`_includes${path_1.sep}`); if (!href || !(0, utils_1.isLocalUrl)(href) || isIncludeLink) { j++; continue; } const { pathname, hash } = url_1.default.parse(href); if (pathname) { const isPageFile = utils_1.PAGE_LINK_REGEXP.test(pathname); if (isPageFile) { const newHref = (0, utilsFS_1.getSinglePageAnchorId)({ root, currentPath: startPath, pathname, hash, }); result = replaceLinkHref(result, href, newHref); } } else if (hash) { const newHref = (0, utilsFS_1.getSinglePageAnchorId)({ root, currentPath: startPath, hash }); result = replaceLinkHref(result, href, newHref); } j++; } } i++; } // eslint-disable-next-line consistent-return return result; }; module.exports = collect; //# sourceMappingURL=collect.js.map