Giter Site home page Giter Site logo

syntax-tree / mdast-util-mdx-expression Goto Github PK

View Code? Open in Web Editor NEW
3.0 8.0 0.0 140 KB

mdast extension to parse and serialize MDX or MDX.js expressions

Home Page: https://unifiedjs.com

License: MIT License

JavaScript 100.00%
mdast mdast-util es js expression mdx mdxjs

mdast-util-mdx-expression's Introduction

mdast-util-mdx-expression

Build Coverage Downloads Size Sponsors Backers Chat

mdast extensions to parse and serialize MDX expressions ({Math.PI}).

Contents

What is this?

This package contains two extensions that add support for MDX expression syntax in markdown to mdast. These extensions plug into mdast-util-from-markdown (to support parsing expressions in markdown into a syntax tree) and mdast-util-to-markdown (to support serializing expressions in syntax trees to markdown).

When to use this

You can use these extensions when you are working with mdast-util-from-markdown and mdast-util-to-markdown already.

When working with mdast-util-from-markdown, you must combine this package with micromark-extension-mdx-expression.

When you are working with syntax trees and want all of MDX, use mdast-util-mdx instead.

All these packages are used in remark-mdx, which focusses on making it easier to transform content by abstracting these internals away.

Install

This package is ESM only. In Node.js (version 16+), install with npm:

npm install mdast-util-mdx-expression

In Deno with esm.sh:

import {mdxExpressionFromMarkdown, mdxExpressionToMarkdown} from 'https://esm.sh/mdast-util-mdx-expression@2'

In browsers with esm.sh:

<script type="module">
  import {mdxExpressionFromMarkdown, mdxExpressionToMarkdown} from 'https://esm.sh/mdast-util-mdx-expression@2?bundle'
</script>

Use

Say our document example.mdx contains:

{
  a + 1
}

b {true}.

…and our module example.js looks as follows:

import fs from 'node:fs/promises'
import * as acorn from 'acorn'
import {mdxExpression} from 'micromark-extension-mdx-expression'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {mdxExpressionFromMarkdown, mdxExpressionToMarkdown} from 'mdast-util-mdx-expression'
import {toMarkdown} from 'mdast-util-to-markdown'

const doc = await fs.readFile('example.mdx')

const tree = fromMarkdown(doc, {
  extensions: [mdxExpression({acorn, addResult: true})],
  mdastExtensions: [mdxExpressionFromMarkdown()]
})

console.log(tree)

const out = toMarkdown(tree, {extensions: [mdxExpressionToMarkdown()]})

console.log(out)

…now running node example.js yields (positional info removed for brevity):

{
  type: 'root',
  children: [
    {
      type: 'mdxFlowExpression',
      value: '\na + 1\n',
      data: {
        estree: {
          type: 'Program',
          body: [
            {
              type: 'ExpressionStatement',
              expression: {
                type: 'BinaryExpression',
                left: {type: 'Identifier', name: 'a'},
                operator: '+',
                right: {type: 'Literal', value: 1, raw: '1'}
              }
            }
          ],
          sourceType: 'module'
        }
      }
    },
    {
      type: 'paragraph',
      children: [
        {type: 'text', value: 'b '},
        {
          type: 'mdxTextExpression',
          value: 'true',
          data: {
            estree: {
              type: 'Program',
              body: [
                {
                  type: 'ExpressionStatement',
                  expression: {type: 'Literal', value: true, raw: 'true'}
                }
              ],
              sourceType: 'module'
            }
          }
        },
        {type: 'text', value: '.'}
      ]
    }
  ]
}
{
  a + 1
}

b {true}.

API

This package exports the identifiers mdxExpressionFromMarkdown and mdxExpressionToMarkdown. There is no default export.

mdxExpressionFromMarkdown()

Create an extension for mdast-util-from-markdown to enable MDX expressions in markdown.

When using the micromark syntax extension with addResult, nodes will have a data.estree field set to an ESTree Program node.

Returns

Extension for mdast-util-from-markdown to enable MDX expressions (FromMarkdownExtension).

mdxExpressionToMarkdown()

Create an extension for mdast-util-to-markdown to enable MDX expressions in markdown.

Returns

Extension for mdast-util-to-markdown to enable MDX expressions (ToMarkdownExtension).

MdxFlowExpression

MDX expression node, occurring in flow (block) (TypeScript type).

Type
import type {Program} from 'estree-jsx'
import type {Data, Literal} from 'mdast'

interface MdxFlowExpression extends Literal {
  type: 'mdxFlowExpression'
  data?: MdxFlowExpressionData | undefined
}

interface MdxFlowExpressionData extends Data {
  estree?: Program | null | undefined
}

MdxTextExpression

MDX expression node, occurring in text (block) (TypeScript type).

Type
import type {Program} from 'estree-jsx'
import type {Data, Literal} from 'mdast'

interface MdxTextExpression extends Literal {
  type: 'mdxTextExpression'
  data?: MdxTextExpressionData | undefined
}

interface MdxTextExpressionData extends Data {
  estree?: Program | null | undefined
}

MdxFlowExpressionHast

Same as MdxFlowExpression, but registered with @types/hast (TypeScript type).

Type
import type {Program} from 'estree-jsx'
import type {Data, Literal} from 'hast'

interface MdxFlowExpressionHast extends Literal {
  type: 'mdxFlowExpression'
  data?: MdxFlowExpressionData | undefined
}

interface MdxFlowExpressionData extends Data {
  estree?: Program | null | undefined
}

MdxTextExpressionHast

Same as MdxTextExpression, but registered with @types/hast (TypeScript type).

Type
import type {Program} from 'estree-jsx'
import type {Data, Literal} from 'hast'

interface MdxTextExpressionHast extends Literal {
  type: 'mdxTextExpression'
  data?: MdxTextExpressionData | undefined
}

interface MdxTextExpressionData extends Data {
  estree?: Program | null | undefined
}

HTML

MDX expressions have no representation in HTML. Though, when you are dealing with MDX, you will likely go through hast. You can enable passing MDX expressions through to hast by configuring mdast-util-to-hast with passThrough: ['mdxFlowExpression', 'mdxTextExpression'].

Syntax

See Syntax in micromark-extension-mdx-expression.

Syntax tree

The following interfaces are added to mdast by this utility.

Nodes

MdxFlowExpression

interface MdxFlowExpression <: Literal {
  type: 'mdxFlowExpression'
}

MdxFlowExpression (Literal) represents a JavaScript expression embedded in flow (block). It can be used where flow content is expected. Its content is represented by its value field.

For example, the following markdown:

{
  1 + 1
}

Yields:

{type: 'mdxFlowExpression', value: '\n1 + 1\n'}

MdxTextExpression

interface MdxTextExpression <: Literal {
  type: 'mdxTextExpression"
}

MdxTextExpression (Literal) represents a JavaScript expression embedded in text (span, inline). It can be used where phrasing content is expected. Its content is represented by its value field.

For example, the following markdown:

a {1 + 1} b.

Yields:

{type: 'mdxTextExpression', value: '1 + 1'}

Content model

FlowContent (MDX expression)

type FlowContentMdxExpression = MdxFlowExpression | FlowContent

PhrasingContent (MDX expression)

type PhrasingContentMdxExpression = MdxTextExpression | PhrasingContent

Types

This package is fully typed with TypeScript. It exports the additional types MdxFlowExpression, MdxFlowExpressionHast, MdxTextExpression, and MdxTextExpressionHast.

It also registers the node types with @types/mdast and @types/hast. If you’re working with the syntax tree, make sure to import this utility somewhere in your types, as that registers the new node types in the tree.

/**
 * @typedef {import('mdast-util-mdx-expression')}
 */

import {visit} from 'unist-util-visit'

/** @type {import('mdast').Root} */
const tree = getMdastNodeSomeHow()

visit(tree, function (node) {
  // `node` can now be an expression node.
})

Compatibility

Projects maintained by the unified collective are compatible with maintained versions of Node.js.

When we cut a new major release, we drop support for unmaintained versions of Node. This means we try to keep the current release line, mdast-util-mdx-expression@^2, compatible with Node.js 16.

This utility works with mdast-util-from-markdown version 2+ and mdast-util-to-markdown version 2+.

Related

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer

mdast-util-mdx-expression's People

Contributors

remcohaszing avatar wooorm avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mdast-util-mdx-expression's Issues

Duplicate on line 36 in complex-types.d.ts

Initial checklist

Affected packages and versions

1.2.0

Link to runnable example

No response

Steps to reproduce

mdxFlowExpression: MdxFlowExpression

CleanShot 2022-06-03 at 17 38 18

Expected behavior

no duplicate

Actual behavior

duplicate

Runtime

Node v16

Package manager

yarn v1

OS

macOS

Build and bundle tools

Vite

Expressions are indented weirdly

Initial checklist

Affected packages and versions

latest

Link to runnable example

No response

Steps to reproduce

Reformat:

 {
   (() => {
-    const advanced = props.navTree.children.find((item) => item.name === '/guides/')
+  const advanced = props.navTree.children.find((item) => item.name === '/guides/')
 
-    return (
-      <nav>
-        <NavGroup items={advanced.children} includeDescription />
-      </nav>
-    )
+  return (
+  <nav>
+  <NavGroup items={advanced.children} includeDescription />
+  </nav>
+  )
   })()

Expected behavior

Indent should be nice

Actual behavior

Indent is horrible

Runtime

No response

Package manager

No response

OS

No response

Build and bundle tools

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.