Skip to content

Instantly share code, notes, and snippets.

@moy2010
Created December 21, 2023 15:47
Show Gist options
  • Save moy2010/1c1dfbcb721d1b4d8751d6a1324194c2 to your computer and use it in GitHub Desktop.
Save moy2010/1c1dfbcb721d1b4d8751d6a1324194c2 to your computer and use it in GitHub Desktop.

Revisions

  1. moy2010 created this gist Dec 21, 2023.
    33 changes: 33 additions & 0 deletions lexical_code_markdown_transformer.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    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',
    };