Skip to content

Instantly share code, notes, and snippets.

@moy2010
Created December 21, 2023 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moy2010/1c1dfbcb721d1b4d8751d6a1324194c2 to your computer and use it in GitHub Desktop.
Save moy2010/1c1dfbcb721d1b4d8751d6a1324194c2 to your computer and use it in GitHub Desktop.
A custom LexicalJs markdown transformer for code blocks
const CODE: TextMatchTransformer = {
dependencies: [CodeNode],
export: (node: LexicalNode) => {
if (!$isCodeNode(node)) {
return null;
}
const textContent = node.getTextContent();
return '```' + (node.getLanguage() ?? '') + (textContent ? '\n' + textContent : '') + '\n' + '```';
},
importRegExp: /```$/,
regExp: /```$/,
trigger: '`',
replace: (textNode) => {
const codeNode = $createCodeNode();
const textNodeClone = $createTextNode(textNode.getTextContent().replace(/```$/, ''));
const textNodeParent = textNode.getParent();
const selection = $getSelection();
if (textNodeParent) {
const siblings = textNodeParent.getChildren();
if (siblings.length > 2 || (siblings.length > 1 && textNode === siblings.at(-1))) {
selection?.insertNodes([codeNode]);
} else {
if ($isRangeSelection(selection)) {
codeNode.append(textNode);
$setBlocksType(selection, () => codeNode);
}
}
textNode.replace(textNodeClone);
}
codeNode.select(0, 0);
},
type: 'text-match',
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment