@mkljczk/lexical-remark
Version:
This package contains Markdown helpers and functionality for Lexical using remark-parse.
33 lines (32 loc) • 1.18 kB
JavaScript
import { $getRoot } from 'lexical';
import remarkParse from 'remark-parse';
import { unified } from 'unified';
import { Parser } from './parser.js';
export function remarkLexify(handlers = {}) {
const compiler = (tree) => {
const parser = new Parser(handlers);
return parser.parse(tree).getChildren();
};
Object.assign(this, { Compiler: compiler });
}
export function $convertFromMarkdownViaRemark(markdownString, options) {
const root = $getRoot();
root.clear();
const file = unified()
.use(remarkParse)
.use(remarkLexify, options?.handlers)
.processSync(markdownString);
root.append(...file.result);
}
/**
* Creates a parsing function which converts a markdown string to a Lexical state via remark
*
* @param handlers A set of additional handlers designed to parse remark mdast nodes into Lexical nodes
* @returns A function which accepts a string in markdown format and replaces the tree of the active editor
* with the parsed Lexical nodes
*/
export function $createRemarkImport(options = {}) {
return (markdownString) => {
$convertFromMarkdownViaRemark(markdownString, options);
};
}