UNPKG

remark-linkify

Version:

A remark plugin to automatically convert URLs and email addresses into links.

47 lines (46 loc) 1.29 kB
// src/index.ts import LinkifyIt from "linkify-it"; import { visit } from "unist-util-visit"; var linkify = new LinkifyIt(); function remarkLinkify() { return (tree) => { visit( tree, "text", (node, index, parent) => { if (!parent || index === void 0 || parent.type === "link" || parent.type === "linkReference" || !node.value) { return; } const text = node.value; const matches = linkify.match(text); if (!matches || matches.length === 0) { return; } const newNodes = []; let lastIndex = 0; for (const match of matches) { if (match.index > lastIndex) { newNodes.push({ type: "text", value: text.slice(lastIndex, match.index) }); } newNodes.push({ type: "link", url: match.url, children: [{ type: "text", value: match.text }] }); lastIndex = match.lastIndex; } if (lastIndex < text.length) { newNodes.push({ type: "text", value: text.slice(lastIndex) }); } parent.children.splice(index, 1, ...newNodes); return index + newNodes.length; } ); }; } export { remarkLinkify };