lexical-remark
Version:
This package contains Markdown helpers and functionality for Lexical using remark-parse.
78 lines (77 loc) • 2.38 kB
JavaScript
import { visit } from 'unist-util-visit';
/**
* A remark plugin to enrich an mdast node tree by converting paragraph nodes containing only a Attachment url into Attachment nodes
*/
export const remarkAttachment = (options) => {
return convertAttachmentLinks;
function convertAttachmentLinks(tree) {
const filename = isAttachmentLinkNode(tree);
if (filename) {
tree.type = 'attachment';
tree.filename = filename;
delete tree.title;
tree.children = [
{
type: 'text',
value: `📎 ${filename}`,
},
];
}
visit(tree, function (node) {
const visitedFilename = isAttachmentLinkNode(node);
if (visitedFilename) {
node.type = 'attachment';
node.filename = visitedFilename;
delete node.title;
node.children = [
{
type: 'text',
value: `📎 ${visitedFilename}`,
},
];
}
});
}
function isAttachmentLinkNode(node) {
if (options.prefix &&
node.type === 'link' &&
node.children.length === 1 &&
node.children[0].type === 'text' &&
node.url.startsWith(options.prefix)) {
return node.children[0].value;
}
return false;
}
};
/**
* A remark plugin to simplify an mdast node tree by converting Attachment nodes back to paragraph nodes
*/
export function attachmentRemark() {
return convertToAttachmentLinks;
}
function convertToAttachmentLinks(tree) {
if (tree.type === 'attachment') {
tree.type = 'link';
tree.children = [
{
type: 'text',
value: tree.filename,
},
];
// @ts-expect-error casting to Attachment
delete tree.filename;
}
visit(tree, function (node) {
if (node.type === 'attachment') {
node.type = 'link';
node.children = [
{
type: 'text',
value: node.filename,
},
];
// @ts-expect-error casting to Attachment
delete node.filename;
}
});
}