npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vanjs-converter-nomd

v1.2.0

Published

Utility to convert MD or HTML text into VanJS code

Downloads

6

Readme

HTML and MD to VanJS Code Converter

This is a library that can convert any MD or HTML snippet into valid VanJS code. The UI version of the code converter is here.

Installation

The library is published as NPM package vanjs-converter.

Run the following command to install the package:

npm install vanjs-converter

To use the NPM package, add this line to your script:

import { htmlToVanCode, mdToVanCode } from "vanjs-converter"

htmlToVanCode: Convert HTML snippet to VanJS Code

Signature

htmlToVanCode(<HTML string>, <options>) => {code: <code>, tags: <tags>, components: <components>}

Example

htmlToVanCode('<div><p>👋Hello</p><ul><li>🗺️World</li><li><a href="https://vanjs.org/">🍦VanJS</a></li></ul></div>', {indent: 4})
/*
The following result will be returned:
{
  code: [
    'div(',
    '    p(',
    '        "👋Hello",',
    '    ),',
    '    ul(',
    '        li(',
    '            "🗺️World",',
    '        ),',
    '        li(',
    '            a({href: "https://vanjs.org/"},',
    '                "🍦VanJS",',
    '            ),',
    '        ),',
    '    ),',
    ')',
  ],
  tags: ["a", "div", "li", "p", "ul"],
  components: [],
}
*/

Using VanJS Components

This is only supported in the converter library, not in the UI. The root cause is html-dom-parser doesn't support case-sensitive parsing on the client side.

The input HTML string can be a mix of HTML elements and custom UI components built with VanJS. To use custom UI components, just specify the component similar to regular HTML tags. For instance, assume we have custom UI components similar to the ones shown in https://vanjs.org/ home page:

const Hello = text => div(
  p("👋Hello"),
  ul(
    li(text),
    li(a({href: "https://vanjs.org/"}, "🍦VanJS")),
  ),
)

const Counter = ({initValue}) => {
  const counter = van.state(initValue)
  return button({onclick: () => ++counter.val}, counter)
}

You can simply specify the input HTML string like this:

<h2>Hello</h2>
<Hello>🗺️World</Hello>
<h2>Counter</h2>
<Counter initValue="1"></Counter>
<Counter initValue="2"></Counter>

which will be converted into the following VanJS code:

h2(
  "Hello",
),
Hello(
  "🗺️World",
),
h2(
  "Counter",
),
Counter({initValue: "1"}),
Counter({initValue: "2"}),

Options

  • indent: Type number. Default 2. Optional. The indent level of the generated VanJS code.

  • spacing: Type boolean. Default false. Optional. The style of the property object in the generated VanJS code. If true, the property object will look like {href: "https://vanjs.org/"}; Otherwise, the property object will look like { href: "https://vanjs.org/" }.

  • skipEmptyText: Type boolean. Default false. Optional. Whether to skip empty text nodes in the generated VanJS code. For instance, the HTML snippet:

    <div>
      <p>👋Hello</p>
      <ul>
        <li>🗺️World</li>
        <li><a href="https://vanjs.org/">🍦VanJS</a></li>
      </ul>
    </div>

    will be converted to:

    div(
      p(
        "👋Hello",
      ),
      ul(
        li(
          "🗺️World",
        ),
        li(
          a({href: "https://vanjs.org/"},
            "🍦VanJS",
          ),
        ),
      ),
    )

    if skipEmptyText is true. But it will be converted to:

    div(
      "\n  ",
      p(
        "👋Hello",
      ),
      "\n  ",
      ul(
        "\n    ",
        li(
          "🗺️World",
        ),
        "\n    ",
        li(
          a({href: "https://vanjs.org/"},
            "🍦VanJS",
          ),
        ),
        "\n  ",
      ),
      "\n",
    )

    if skipEmptyText is false.

  • htmlTagPred: Type (name: string) => boolean. Default s => s.toLowerCase() === s. Optional. A predicate function to check whether a specific tag snippet such as <Counter> should be treated as a native HTML element or a custom UI component built with VanJS. By default, it will be treated as a native HTML element if the letters in the name are all lowercase.

Return Value

A plain object with the following fields:

  • code: A string[] for all lines of the generated VanJS code.
  • tags: A string[] for all HTML tag names used in the generated VanJS code, which can be used in the importing line of tag functions such as:
    const {<tags needs to import>} = van.tags
  • components: A string[] for all custom VanJS components used in the generated VanJS code, which can be used in the importing line such as:
    import {<components needs to import>} from "./my-component-lib.js"

DUMMY

This is only supported in the converter library, not in the UI.

There are 2 special cases while specifying custom VanJS components in the input HTML string. The first special case is that, sometimes, a custom component needs properties being specified in its first argument, even for empty properties {} (e.g.: the Counter component defined in the section above). In this case, you can specify the special DUMMY property as a placeholder. For instance:

<CustomElement DUMMY>content</CustomElement>

will be converted to:

CustomElement({},
  "content",
)

whereas

<CustomElement>content</CustomElement>

will be converted to:

CustomElement(
  "content",
)

The second special case is that, sometimes, a custom VanJS component needs consecutive string arguments. You can achieve that by inserting <DUMMY> element between text pieces. For instance:

<Link>🍦VanJS<DUMMY></DUMMY>https://vanjs.org/</Link>

will be converted to:

Link(
  "🍦VanJS",
  "https://vanjs.org/",
)

mdToVanCode: Convert MD snippet to VanJS Code

Signature

mdToVanCode(<MD string>, <options>) => {code: <code>, tags: <tags>, components: <components>}

Under the hood, there are 2 steps for converting an MD snippet to VanJS code:

  1. Convert the MD string into an HTML string with Marked library.
  2. Convert the HTML string into VanJS code with htmlToVanCode.

Example

mdToVanCode(`👋Hello
* 🗺️World
* [🍦VanJS](https://vanjs.org/)
`)
/*
The following result will be returned:
{
  code: [
    'p(',
    '  "👋Hello",',
    '),',
    'ul(',
    '  li(',
    '    "🗺️World",',
    '  ),',
    '  li(',
    '    a({href: "https://vanjs.org/"},',
    '      "🍦VanJS",',
    '    ),',
    '  ),',
    '),',
  ],
  tags: ["a", "li", "p", "ul"],
  components: [],
}
*/

Note that, you can insert custom HTML snippets, or even custom VanJS components in the input MD string.

Options

  • indent: Type number. Default 2. Optional. The indent level of the generated VanJS code.

  • spacing: Type boolean. Default false. Optional. The style of the property object in the generated VanJS code. If true, the property object will look like {href: "https://vanjs.org/"}; Otherwise, the property object will look like { href: "https://vanjs.org/" }.

  • htmlTagPred: Type (name: string) => boolean. Default s => s.toLowerCase() === s. Optional. A predicate function to check whether a specific tag snippet such as <Counter> represents a native HTML element or a custom UI component built with VanJS. By default, it will be considered a native HTML element if the letters in the name are all lowercase.

  • renderer: Optional. Custom renderer is only supported in the converter library, not in the UI. A custom object used to override how tokens in the MD string are being rendered. The specification of the renderer object can be found in Marked doc. For instance, the renderer object:

    {
      codespan: s => `<Symbol>${s}</Symbol>`,
      link: (href, _unused_title, text) => `<Link>${text}<DUMMY></DUMMY>${href}</Link>`,
    }

    will convert `text` in MD string into Symbol("text") (here Symbol is a custom VanJS component) instead of code("text"), and will convert [text](link) in MD string into Link("text", "link") instead of a({href: "link"}, "text").

Return Value

The same as the return value of htmlToVanCode.

Showroom

The https://vanjs.org/ website is using this library to keep README.md files in sync with their corresponding web pages (source code of the code generation):

  • The VanUI page is kept in sync with the README.md file in GitHub with the help of this library.
  • This README.md file is kept in sync with this page in https://vanjs.org/ website.