Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
import { toHtml } from "hast-util-to-html";
import { gfmFromMarkdown } from "mdast-util-gfm";
import { frontmatter } from "micromark-extension-frontmatter";
import { gfm } from "micromark-extension-gfm";
import { fromMarkdown } from "mdast-util-from-markdown";
import { frontmatterFromMarkdown } from "mdast-util-frontmatter";
import { toHast } from "mdast-util-to-hast";
import { toString } from "mdast-util-to-string";
import GithubSlugger from "github-slugger";
import sanitizeHtml from "sanitize-html";
import type { ImageLoader } from "@webstudio-is/image";
import {
getGithubAlertType,
transformGithubAlerts,
} from "@webstudio-is/content-engine/remark-github-alerts";
import { getSdkImageProps, type SdkImageProps } from "./image-utils";
const parseMarkdown = (markdown: string) => {
const tree = fromMarkdown(markdown, {
extensions: [frontmatter(["yaml"]), gfm()],
mdastExtensions: [frontmatterFromMarkdown(["yaml"]), gfmFromMarkdown()],
});
transformGithubAlerts(tree);
const slugger = new GithubSlugger();
const visit = (node: unknown) => {
if (typeof node !== "object" || node === null) {
return;
}
if ("type" in node && node.type === "heading") {
const text = toString(node as Parameters<typeof toString>[0]);
const data =
"data" in node && typeof node.data === "object" ? node.data : {};
Object.assign(node, {
data: {
...data,
hProperties: { id: slugger.slug(text) || slugger.slug("heading") },
},
});
}
const alertType = getGithubAlertType(node);
if (alertType !== undefined) {
const data =
"data" in node && typeof node.data === "object" ? node.data : {};
Object.assign(node, {
data: {
...data,
hName: "div",
hProperties: {
role: "note",
"data-state": alertType.toLowerCase(),
},
},
});
}
if ("children" in node && Array.isArray(node.children)) {
for (const child of node.children) {
visit(child);
}
}
};
visit(tree);
return tree;
};
const sanitizeMarkdownHtml = (
html: string,
{
allowBlobImages,
transformTags,
}: {
allowBlobImages: boolean;
transformTags?: sanitizeHtml.IOptions["transformTags"];
}
) =>
sanitizeHtml(html, {
allowedTags: [
...sanitizeHtml.defaults.allowedTags,
"audio",
"del",
"details",
"iframe",
"img",
"input",
"picture",
"source",
"summary",
"video",
],
allowedAttributes: {
...sanitizeHtml.defaults.allowedAttributes,
"*": [
"aria-*",
"class",
"data-*",
"dir",
"id",
"lang",
"role",
"tabindex",
"title",
],
audio: ["autoplay", "controls", "loop", "muted", "preload", "src"],
iframe: [
"allow",
"allowfullscreen",
"frameborder",
"height",
"loading",
"referrerpolicy",
"src",
"width",
],
img: [
"alt",
"decoding",
"height",
"loading",
"sizes",
"src",
"srcset",
"width",
],
input: ["checked", "disabled", "type"],
source: ["media", "sizes", "src", "srcset", "type"],
video: [
"autoplay",
"controls",
"height",
"loop",
"muted",
"playsinline",
"poster",
"preload",
"src",
"width",
],
},
allowedSchemesByTag: {
audio: ["data", "http", "https"],
iframe: ["http", "https"],
img: [...(allowBlobImages ? ["blob"] : []), "data", "http", "https"],
source: ["data", "http", "https"],
video: ["data", "http", "https"],
},
allowProtocolRelative: false,
transformTags,
exclusiveFilter: ({ tag, attribs }) =>
tag === "input" &&
(attribs.type !== "checkbox" || attribs.disabled === undefined),
});
const createImageTransformer =
({
imageLoader,
renderer,
}: {
imageLoader: ImageLoader;
renderer: "canvas" | "preview" | undefined;
}): sanitizeHtml.Transformer =>
(tagName, attributes) => {
const { srcset, ...rest } = attributes;
const { imageProps } = getSdkImageProps({
props: {
...rest,
srcSet: srcset,
loading: attributes.loading as SdkImageProps["loading"],
decoding: attributes.decoding as SdkImageProps["decoding"],
} as SdkImageProps,
imageLoader,
renderer,
});
const { sizes, srcSet, src, decoding, loading, ...htmlProps } = imageProps;
const transformedAttributes: sanitizeHtml.Attributes = {};
for (const [name, value] of Object.entries(htmlProps)) {
if (typeof value === "string" || typeof value === "number") {
transformedAttributes[name] = String(value);
}
}
if (sizes !== undefined) {
transformedAttributes.sizes = String(sizes);
}
if (srcSet !== undefined) {
transformedAttributes.srcset = String(srcSet);
}
// Keep src after sizes and srcset so Safari does not load the image twice.
transformedAttributes.src = String(src);
transformedAttributes.decoding = String(decoding);
transformedAttributes.loading = String(loading);
return { tagName, attribs: transformedAttributes };
};
/** Shared safe renderer used by both the authoring preview and published component. */
export const renderMarkdownHtml = (
markdown: string,
{
allowBlobImages = false,
imageLoader,
renderer,
}: {
allowBlobImages?: boolean;
imageLoader?: ImageLoader;
renderer?: "canvas" | "preview";
} = {}
) => {
const tree = parseMarkdown(markdown);
const hast = toHast(tree, { allowDangerousHtml: true });
const html = sanitizeMarkdownHtml(
hast === undefined ? "" : toHtml(hast, { allowDangerousHtml: true }),
{ allowBlobImages }
);
if (imageLoader === undefined) {
return html;
}
// Sanitize before transforming so unsafe sources cannot become valid URLs
// after passing through the image loader. Sanitize the generated attributes
// again because loaders are application-provided.
return sanitizeMarkdownHtml(html, {
allowBlobImages,
transformTags: {
img: createImageTransformer({ imageLoader, renderer }),
},
});
};