Code Monkey home page Code Monkey logo

unist-builder's Introduction

unist-builder

Build Coverage Downloads Size Sponsors Backers Chat

unist utility to create trees with ease.

Contents

What is this?

This package is a hyperscript interface (like createElement from React and h from Vue and such) to help with creating unist trees.

When should I use this?

You can use this utility in your project when you generate syntax trees with code. It helps because it replaces most of the repetition otherwise needed in a syntax tree with function calls.

You can instead use hastscript or xastscript when creating hast (HTML) or xast (XML) nodes.

Install

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

npm install unist-builder

In Deno with esm.sh:

import {u} from 'https://esm.sh/unist-builder@4'

In browsers with esm.sh:

<script type="module">
  import {u} from 'https://esm.sh/unist-builder@4?bundle'
</script>

Use

import {u} from 'unist-builder'

const tree = u('root', [
  u('subtree', {id: 1}),
  u('subtree', {id: 2}, [
    u('node', [u('leaf', 'leaf 1'), u('leaf', 'leaf 2')]),
    u('leaf', {id: 3}, 'leaf 3'),
    u('void', {id: 4})
  ])
])

console.dir(tree, {depth: undefined})

…yields:

{
  type: 'root',
  children: [
    {type: 'subtree', id: 1},
    {
      type: 'subtree',
      id: 2,
      children: [
        {
          type: 'node',
          children: [
            {type: 'leaf', value: 'leaf 1'},
            {type: 'leaf', value: 'leaf 2'}
          ]
        },
        {type: 'leaf', id: 3, value: 'leaf 3'},
        {type: 'void', id: 4}
      ]
    }
  ]
}

API

This package exports the identifier u. There is no default export.

u(type[, props][, children|value])

Build a node.

Signatures
  • u(type[, props], children) — create a parent (Parent)
  • u(type[, props], value) — create a literal (Literal)
  • u(type[, props]) — create a void node (neither parent not literal)
Parameters
  • type (string) — node type
  • props (Record<string, unknown>) — fields assigned to node
  • children (Array<Node>) — children of node
  • value (*) — value of node (cast to string)
Returns

Built node (Node).

ChildrenOrValue

List to use as children or value to use as value (TypeScript type).

Type
type ChildrenOrValue = Array<Node> | string

Props

Other fields to add to the node (TypeScript type).

Type
export type Props = Record<string, unknown>

Types

This package is fully typed with TypeScript. It exports the additional types ChildrenOrValue and Props.

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, unist-builder@^4, compatible with Node.js 16.

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 © Eugene Sharygin

unist-builder's People

Contributors

christianmurphy avatar eush77 avatar wooorm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unist-builder's Issues

Remove the String cast for the node's value

Initial checklist

Problem

I have some use cases in which I would need the value to be an actual value, not cast to string, to work around this I ended up making my own unist-builder without the String() call.

I don't even understand why we want to force string to it, if it's a value, we can even map it or filter it using the unist-filter and unist-map utilities without having to parse/stringify the value.

Solution

builder shouldn't hard cast to string the value provided, since it limits how we can use the value itself while mixing with other syntax-tree utilities.

Alternatives

  • JSON.parse when needed, which isn't much of a good alternative

Error while running tests with unist-builder version 3.0.0

Initial checklist

Affected packages and versions

3.0.0

Link to runnable example

No response

Steps to reproduce

Using jest for running the test throws error for unist-builder version 3.0.0. The same used to work fine for 2.0.3 version,
Error below,
Details:

/Users/lokeshkumar.n/mine/sandbox/doc-framework-monorepo/packages/@salesforcedocs/markdown-compiler/node_modules/unist-builder/index.js:16
export var u = /**
^^^^^^

SyntaxError: Unexpected token 'export'

  3 |
> 4 | import {u} from 'unist-builder';
    | ^

This is the error from Jest,
Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

I tried configuring transform option for unist-builder to use babel-jest, but still same problem persists for version 3.0.0

Expected behavior

Tests should be able to use the version 3.0.0

Actual behavior

Throws error while running tests using jest.

Runtime

Node v14

Package manager

yarn v1

OS

macOS

Build and bundle tools

Other (please specify in steps to reproduce)

Allow u(type, props, ...children) form of API

Initial checklist

Problem

I'm probably doing something cursed, but I'm trying to see if it's able to write unists in JSX. I reproduced the example in the README as:

import { u } from "unist-builder";

const tree = (
  <root>
    <subtree id={1} />
    <subtree id={2}>
      <node>
        <leaf>leaf 1</leaf>
        <leaf>leaf 2</leaf>
      </node>
      <leaf id={3}>leaf 3</leaf>
      <void id={4} />
    </subtree>
  </root>
);

And using u as the JSX factory. Unfortunately, this didn't work, because u only accepts an array of children. In order to make this work, I have to use a single array as children everywhere.

Solution

I propose to make this valid:

var tree = u(
  "root",
  null,
  u("subtree", { id: 1 }),
  u(
    "subtree",
    { id: 2 },
    u("node", null, u("leaf", null, "leaf 1"), u("leaf", null, "leaf 2")),
    u("leaf", { id: 3 }, "leaf 3"),
    u("void", { id: 4 })
  )
);

Because JSX always compiles to type, props, ...children, whenever there are more than three arguments, the rest must all be children, and we can simply collect them into an array.

Alternatives

Do not use JSX for unist? 😄

I'm really curious if I'm able to make it work, though

Changed build result in v1.0.3

Build result changed in v1.0.3

code:

u('blockquote', {
  "type": "root",
  "children": [
    {
      "type": "paragraph",
      "children": [
        {
          "type": "text",
          "value": "x"
        }
      ]
    }
  ]
})

v1.0.2:

{"type":"blockquote","children":[{"type":"paragraph","children":[{"type":"text","value":"x"}]}]}

v1.0.3

{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","value":"x"}]}]}

PS: root type is passed from code like this:

u('blockquote', remark().parse('x'))

Allow "type" to be a function (as a "component")

Initial checklist

Problem

Related to #10. If we think it's cool to write unists as JSX, a natural conclusion is we must support components as well.

Solution

I propose to support this pattern:

const root = u(Comp, { id: 1 }, u("leaf", "leaf 1"), u("leaf", "leaf 2"));

Which will be equivalent to

const root = Comp({ id: 1, children: [u("leaf", "leaf 1"), u("leaf", "leaf 2")] });

We don't necessarily need to support "class components", just the simple idea that you can provide a function which will be called with props and children.

Alternatives

If we are to support JSX—there doesn't seem to be another way.

Rename to `astscript`

Subject of the feature

Idea I’m having: this project’s name is very different from hastscript/mdastscript. How about using astscript? (it’s free on npm!)

Problem

Similar projects have different naming schemes.


What do you think?

Import issue in the package unist-builder in ES6 codebase

Initial checklist

  • I read the support docs
  • I read the contributing guide
  • I agree to follow the code of conduct
  • I searched issues and couldn’t find anything (or linked relevant results below)

Affected packages and versions: unist-builder 3.0.0

Steps to reproduce

  1. Imported the package into the project using ES6 and typescript.
  2. Imported the u from the package.
  3. Received the importing error.

Expected behavior

Should run without any issue, but throws import issues.

Actual behavior

Throwing errors after import.

Errror

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/khushal87/Projects/RNE-AutoGen/node_modules/unist-builder/index.js
require() of ES modules is not supported.
require() of /home/khushal87/Projects/RNE-AutoGen/node_modules/unist-builder/index.js from /home/khushal87/Projects/RNE-AutoGen/json-to-markdown/mdast/templates.ts is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/khushal87/Projects/RNE-AutoGen/node_modules/unist-builder/package.json.

Fix

  1. Remove type: "module" from package.json.
  2. Export u as module.exports = {u};

Note

The above fix works after doing the following changes in the package code under node_modules. So it will be great if this package adapts the new code so that the issue could be resolved.

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.