UNPKG

@diplodoc/transform

Version:

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

91 lines 3.35 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultTransformLink = exports.PAGE_LINK_REGEXP = exports.getHrefTokenAttr = exports.transformLinkToOriginalArticle = exports.isExternalHref = exports.headingInfo = exports.findBlockTokens = exports.isLocalUrl = void 0; const url_1 = __importDefault(require("url")); function isLocalUrl(url) { return !/^(?:[a-z]+:)?\/\//i.test(url); } exports.isLocalUrl = isLocalUrl; function findBlockTokens(tokens, id) { let blockTokens = []; let i = 0, startToken, start, end; while (i < tokens.length) { const token = tokens[i]; if (typeof start === 'number' && startToken) { if (startToken.type === 'paragraph_open' && token.type === 'paragraph_close') { end = i + 1; break; } else if (startToken.type === 'heading_open') { if (token.type === 'heading_open' && token.tag === startToken.tag) { end = i; break; } else if (i === tokens.length - 1) { end = tokens.length; } } } if ((token.type === 'paragraph_open' || token.type === 'heading_open') && token.attrGet('id') === id && typeof start === 'undefined') { startToken = token; start = i; } i++; } if (typeof start === 'number' && typeof end === 'number') { blockTokens = tokens.slice(start, end); } return blockTokens; } exports.findBlockTokens = findBlockTokens; function headingInfo(tokens, idx) { const openToken = tokens[idx]; const inlineToken = tokens[idx + 1]; let title = '', i = 0; while (inlineToken.children && i < inlineToken.children.length) { const token = inlineToken.children[i]; if (token.type === 'text') { title += token.content; } i++; } const level = Number.parseInt(openToken.tag.slice(1), 10); title || (title = inlineToken.content); return { level, title, }; } exports.headingInfo = headingInfo; function isExternalHref(href) { return href.startsWith('http') || href.startsWith('//'); } exports.isExternalHref = isExternalHref; function transformLinkToOriginalArticle(opts) { const { root, currentPath } = opts; return currentPath.replace(root, '').replace(/\.(md|ya?ml|html)$/i, ''); } exports.transformLinkToOriginalArticle = transformLinkToOriginalArticle; function getHrefTokenAttr(token) { let href = token.attrGet('href') || ''; try { href = decodeURI(href); } catch (e) { } return href; } exports.getHrefTokenAttr = getHrefTokenAttr; exports.PAGE_LINK_REGEXP = /\.(md|ya?ml)$/i; function defaultTransformLink(href) { var _a; const parsed = url_1.default.parse(href); href = url_1.default.format(Object.assign(Object.assign({}, parsed), { pathname: (_a = parsed.pathname) === null || _a === void 0 ? void 0 : _a.replace(exports.PAGE_LINK_REGEXP, '.html') })); return href; } exports.defaultTransformLink = defaultTransformLink; //# sourceMappingURL=utils.js.map