Skip to main content

markdownifyTo

Reduces or maps a markdown text to a certain structure. This function can be used to parse markdown text to a HTML structure.

Signature

markdownifyTo<T>(
markdown: string,
context?: Context,
options?:
(
{
reduce: (type: "paragraph" | "break" | "bold" | "italic" | "bold+italic" | "underline" | "strikethrough" | "code" | "hyperlink" | "image" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "codeblock" | "codeline" | "quote" | "mention" | "reference" | undefined, content: string | T[], value: string | IVariable | undefined) => T;
} | {
map: (
type: "paragraph" | "break" | "bold" | "italic" | "bold+italic" | "underline" | "strikethrough" | "code" | "hyperlink" | "image" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "codeblock" | "codeline" | "quote" | "mention" | "reference" | undefined,
content: string,
value: string | IVariable | undefined,
parent: T | undefined,
kind: "root" | "text" | "node"
) => T;
}
) & {
features?: MarkdownFeatures;
placeholder?: string;
lineBreaks?: boolean;
}
): T

Parameters

NameTypeOptionalDescription
markdownstringNoSpecifies the markdown text to parse.
contextContextYesOptional context for the parser. This context is used when referencing variables.
optionsobjectYesSpecifies options for the parser. Supports the following options:
- reduce or map: Specifies a reducer or map function;
- features: Specifies the supported markdown features (defaults to Formatting and Hyperlinks);
- placeholder: Specifies the placeholder to use for empty variables;
- lineBreaks: Specifies if line breaks are supported (default is false).

Return value

Returns the result of the reducer or map function.

Example

This example shows how you can use this function to parse markdown to a React element.

import { createElement } from "react";
import { Enumerator, IVariable, MarkdownFeatures, MarkdownTypes, castToString, isString, markdownifyTo } from "@tripetto/runner";

// We need this to generate unique keys for each element
const keyGenerator = new Enumerator();

const jsx = markdownifyTo("Example *markdown* text!", undefined, {
features: MarkdownFeatures.Formatting | MarkdownFeatures.Hyperlinks,
reduce: (
type: MarkdownTypes | undefined,
content: string | JSX.Element[],
value?: IVariable | string
) => {
const children = isString(content) ? [content] : content;

switch (type) {
case "bold":
return createElement("b", undefined, ...children);
case "italic":
return createElement("i", undefined, ...children);
case "bold+italic":
return createElement(
"b",
undefined,
createElement("i", undefined, ...children)
);
case "underline":
return createElement("u", undefined, ...children);
case "strikethrough":
return createElement("s", undefined, ...children);
case "break":
return createElement("br");
case "hyperlink":
return createElement(
"a",
{
href: castToString(value),
target: "_blank",
rel: "noopener",
},
...children
);
}

return createElement("span", { key: keyGenerator.n }, ...children);
},
});