UNPKG

@botonic/plugin-contentful

Version:

## What Does This Plugin Do?

90 lines 3.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.recursiveTokenFind = exports.visitTokens = exports.MarkUp = exports.TokenType = exports.MarkupType = void 0; const tslib_1 = require("tslib"); const escape_string_regexp_1 = tslib_1.__importDefault(require("escape-string-regexp")); var MarkupType; (function (MarkupType) { /** * CommonMark markdown * https://spec.commonmark.org/ * Italics is *text* or _text_ * Bold is **text** or __text__ * */ MarkupType["MARKDOWN"] = "markdown"; /** * Bold is *text* and italics is _text_ * https://faq.whatsapp.com/en/android/26000002/ **/ MarkupType["WHATSAPP"] = "whatsapp"; /** * https://guides.github.com/pdfs/markdown-cheatsheet-online.pdf * https://guides.github.com/features/mastering-markdown/ */ MarkupType["GITHUB"] = "github"; /** * Contentful supports github flavoured markdown. Its editor by default generates: * Italics with *text* * Bold with __text__ */ MarkupType["CONTENTFUL"] = "contentful"; })(MarkupType = exports.MarkupType || (exports.MarkupType = {})); var TokenType; (function (TokenType) { TokenType["STRONG"] = "strong"; TokenType["EMPHASIS"] = "em"; TokenType["ESCAPE"] = "escape"; TokenType["PARAGRAPH"] = "paragraph"; TokenType["TEXT"] = "text"; TokenType["SPACE"] = "space"; TokenType["CODE"] = "code"; TokenType["HEADING"] = "heading"; // TODO add others })(TokenType = exports.TokenType || (exports.TokenType = {})); class MarkUp { constructor(type) { this.type = type; } render(tokens, separator = '\n') { return tokens.map(t => this.renderToken(t)).join(separator); // let render = '' // visitTokens(tokens, t => render += this.renderToken()) } /** Remove an inline content (https://spec.commonmark.org/0.29/#inlines) * eg. disableInlines('_hi_', EMPHASIS) = 'hi' */ disableInlines(input, inlineTypes) { // Ideally we should be able to modify the token tree and re-render, but I didn't // find any js library able to render markdown (they always render html) const tokens = this.parse(input); const bolds = recursiveTokenFind(tokens, t => inlineTypes.includes(t.type)); for (const bold of bolds) { const MARKER = (0, escape_string_regexp_1.default)(bold.raw[0]); const regex = new RegExp(`(?<!${MARKER})${(0, escape_string_regexp_1.default)(bold.raw)}(?!${MARKER})`); input = input.replace(regex, bold.tokens[0].text); } return input; } } exports.MarkUp = MarkUp; function visitTokens(input, visitor) { for (const token of input) { if (token.items) { token.items.forEach(t => visitTokens(t.tokens, visitor)); } else if (token.tokens) { visitTokens(token.tokens, visitor); } visitor(token); } } exports.visitTokens = visitTokens; function recursiveTokenFind(tokens, predicate) { const out = []; visitTokens(tokens, (t) => { if (predicate(t)) out.push(t); }); return out; } exports.recursiveTokenFind = recursiveTokenFind; //# sourceMappingURL=markup.js.map