Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/tunnckoCore/mich-h

:tada: Create HAST-compliant virtual dom trees of HTML using hyperscript compatible syntax or JSX, just in ~570 bytes.
https://github.com/tunnckoCore/mich-h

ast components dom hast hyperscript jsx mich vdom virtual virtual-dom

Last synced: about 1 month ago
JSON representation

:tada: Create HAST-compliant virtual dom trees of HTML using hyperscript compatible syntax or JSX, just in ~570 bytes.

Awesome Lists containing this project

README

        

# mich-h [![NPM version](https://img.shields.io/npm/v/mich-h.svg?style=flat)](https://www.npmjs.com/package/mich-h) [![NPM monthly downloads](https://img.shields.io/npm/dm/mich-h.svg?style=flat)](https://npmjs.org/package/mich-h) [![npm total downloads][downloads-img]][downloads-url]

> Create [HAST](https://github.com/syntax-tree/hast)-compliant virtual dom trees of HTML using [hyperscript][] compatible syntax or JSX, just in ~570 bytes.

[![codeclimate][codeclimate-img]][codeclimate-url]
[![codestyle][standard-img]][standard-url]
[![linux build][travis-img]][travis-url]
[![windows build][appveyor-img]][appveyor-url]
[![codecov][coverage-img]][coverage-url]
[![dependency status][david-img]][david-url]

_You might also be interested in [hyperscript][] - a builder for real dom elements._

**[JSX CodePen Example](http://codepen.io/tunnckoCore/pen/xgQKzr?editors=0010)**

## Highlights
- **Tiny:** Very lightweight, ~600 bytes gzip + minify and the UMD wrapper.
- **Defaults:** Sane defaults and tiny css selector parser.
- **Components:** Can be used to create Stateless or Statefull Components.
- **Specificaition:** Creates [HAST](https://github.com/syntax-tree/hast)-compliant AST trees.
- **Customization:** Supports [JSX](), custom tags and attributes.
- **Minimalist:** Really, just a builder of AST trees.
- **Compatibility:** Same as [hyperscript][], but creates virtual DOM.
- **Friendly:** Plays well with [browserify][] users.
- **Bundled:** Available as ES6 Module, CommonJS, UMD.
- **SSR:** Supports server-side rendering through [mich-to-html][].
- **Clean:** Does not mess with DOM or anything.

## Table of Contents
- [Install](#install)
- [Usage](#usage)
- [API](#api)
* [michH](#michh)
- [Notes](#notes)
* [The `className` and `class`](#the-classname-and-class)
* [The `data-*` and `dataset`](#the-data--and-dataset)
* [The styles](#the-styles)
- [Related](#related)
- [Contributing](#contributing)
- [Building docs](#building-docs)
- [Running tests](#running-tests)
- [Author](#author)
- [License](#license)

_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_

## Install
Install with [npm](https://www.npmjs.com/)

```
$ npm install mich-h --save
```

or install using [yarn](https://yarnpkg.com)

```
$ yarn add mich-h
```

Builds are also available on [unpkg](https://unpkg.com/) CDN, so iniclude

```html

```

then access `mich-h` through the `michH` global property - notice the uppercased **H** letter.

```html

const h = michH
const node = h('h1.hero#home.big', 'Hello World')

console.log(node)

```

**Try [CodePen](http://codepen.io/tunnckoCore/pen/ZLmEyJ) or [JSBin](http://jsbin.com/bahefanasi/2/edit?css,js,output) Example**

## Usage
> For more use-cases see the [tests](test.js)

```js
const h = require('mich-h')

const ast = h('div#page.foo.bar.qux', { className: 'ok fool' },
h('#header',
h('h1.classy', 'hello', { style: 'background-color: #333; color: purple' })),
h('nav#menu', { style: {'background': '#2f2', 'font-size': '12px' } },
h('ul', [
// notice `dataset` and `data-zaz`
// both will be set to `properties.dataset`
h('li', 'one', { dataset: { foo: 'bar', qux: 'ok' }, 'data-zaz': 'huh' }),
h('li.sec', 'two', { className: ['huh'] }),
h('li', { 'data-foo': 'hi' }, 'three')
])),
h('h2#title', 'content title', { style: {'background-color': 'red'} }),
// notice `.first` and `className: 'foobie'`
// both will be set in `properties.className` array
h('p.first',
'so it is just like a templating engine,\n',
{ className: 'foobie' },
'but easy to use inline with javascript',
{ onclick: () => {} }),
h('p',
{ className: 'lastParagraph' },
'the intention is for this to be used to create\n',
h('strong', 'charlike', {
className: ['bold'],
style: 'background: white; color: green'
}),
' reusable, interactive html widgets.'))

console.log(ast)
```

Or with modern JSX syntax, adding [JSX Pragma](https://jasonformat.com/wtf-is-jsx/) somewhere at the top and using some transpiler - Rollup, Webpack or Babel with [babel-plugin-transform-react-jsx][].

```jsx
/** @jsx h */
const h = require('mich-h')

const onclick = (e) => console.log('hooray it is clicked!')
const list =


  • one

  • two

  • three

const ast =



hello




{list}

content title


so it is just like a templating engine,
but easy to use inline with javascript


the intention is for this to be used to create
charlike
reusable, interactive html widgets.


console.log(ast)
```

**Examples:**

- [CodePen Example, using JSX](http://codepen.io/tunnckoCore/pen/xgQKzr?editors=0010)
- [Showing AST of pseudo JSX router](http://codepen.io/tunnckoCore/pen/LxXYBq?editors=0010)

## API

### [michH](src/index.js#L52)
> Virtual DOM builder that is compatible to [hyperscript][], so it takes any number of arguments that can be string, object, or array. But the first one `selector` always should be a simple css-like selector supported by [mich-parse-selector][]. For example `.foo.bar` creates a node with tag name `div` and classes `foo bar`. Or selector like `p.foo#hero.bar` creates a node with id `hero`, classes `foo` and `bar`, and tag name `p`.

**Params**

* `selector` **{String}**: simple selector; supports IDs, classes and tag name only
* `props` **{Object}**: an attributes for the tag; can be in any position (i.e 4th)
* `children` **{String|Array}**: a child nodes; can be in any position (i.e. 2nd or 5th)
* `returns` **{Object}**: a HAST compliant node

**Example**

```js
const h = require('mich-h')

const node = h('a.foo#brand.bar.btn-large.xyz', {
className: 'btn'
href: 'https://i.am.charlike.online'
}, 'Charlike Web')

console.log(node.type) // => 'element'
console.log(node.tagName) // => 'p'
console.log(node.properties.id) // => 'brand'

console.log(node.properties.href)
// => 'https://i.am.charlike.online'

console.log(node.properties.className)
// => [ 'foo', 'bar', 'btn-large', 'xyz', 'btn' ]

console.log(node.children.length) // => 1
console.log(node.children[0])
// => { type: 'text', value: 'Charlike Web' }
```

## Notes

### The `className` and `class`
Notice that we write `className`, but `class` is also supported. Just in old javascript versions
it may throw you an error if you try to write it as object key. You will just always get an array as end result in the generated node - they are just concatenated.

```js
const tag = h('.foo', {
className: 'bar'
})

console.log(tag.properties.className)
// => [ 'foo', 'bar' ]

// or passing multiple classes in className
const div = h('.bar', {
className: ['qux', 'xyz']
})
console.log(div.properties.className)
// => [ 'bar', 'qux', 'xyz]
```

### The `data-*` and `dataset`
Another that you should be aware of is that we write `dataset` instead of `data` when want to define a `data-*` attributes for a tag while using `props` object. That name comes from DOM - it saves each data attribute to an object `dataset` in each DOM element. You can still define each data-* attribute as key in props object, like this

```js
const div = h('.foo', {
'data-abc': 'hello',
'data-bar': 'world'
})

// another way is using `dataset`
const node = h('.foo', {
dataset: {
abc: 'hello',
bar: 'world'
}
})
```

While using JSX you still can define it in both styles

```jsx
const node =

Hi

```

### The styles
Note that you can define style in both ways 1) using a string as value or 2) object as value.

```js
const node = h('p', {
style: 'background: red; font-size: 15px;'
})

console.log(node.properties.style)
// => 'background: red; font-size: 15px;'
```

Using above approach you'll end up finally with a node that has a `properties.style` a string, because we don't parse the value. So what you pass, you'll get.

If you pass an object, you'll have an object. Here in that example we'll use JSX, but it is the same as using the `h`-calls.

```jsx
const pTagStyle = {
background: 'red',
'font-size': '15px'
}
const node =

Hello World

console.log(node.properties.style.background) // => 'red'
console.log(node.properties.style)
// => { background: 'red', 'font-size': '15px' }
```

Notice that we also **don't decamelize** style keys, so you should use quotes.

## Related
- [hastscript](https://www.npmjs.com/package/hastscript): Hyperscript compatible DSL for creating virtual HAST trees | [homepage](https://github.com/wooorm/hastscript#readme "Hyperscript compatible DSL for creating virtual HAST trees")
- [hyperscript](https://www.npmjs.com/package/hyperscript): Create HyperText with JavaScript, on client or server. | [homepage](https://github.com/dominictarr/hyperscript "Create HyperText with JavaScript, on client or server.")
- [mich-parse-selector](https://www.npmjs.com/package/mich-parse-selector): Tiny parser for simple CSS selectors, just in ~300 bytes. Pretty similar to what is done in [hyperscript][] | [homepage](https://github.com/tunnckocore/mich-parse-selector#readme "Tiny parser for simple CSS selectors, just in ~300 bytes. Pretty similar to what is done in [hyperscript][]")
- [posthtml](https://www.npmjs.com/package/posthtml): HTML/XML processor | [homepage](https://github.com/posthtml/posthtml "HTML/XML processor")
- [rehype](https://www.npmjs.com/package/rehype): HTML processor powered by plugins | [homepage](https://github.com/wooorm/rehype "HTML processor powered by plugins")
- [reshape](https://www.npmjs.com/package/reshape): A plugin-based html template engine | [homepage](https://github.com/reshape/reshape "A plugin-based html template engine")
- [virtual-dom](https://www.npmjs.com/package/virtual-dom): A batched diff-based DOM rendering strategy | [homepage](https://github.com/Matt-Esch/virtual-dom "A batched diff-based DOM rendering strategy")
- [virtual-html](https://www.npmjs.com/package/virtual-html): Convert given HTML into Virtual DOM object | [homepage](https://github.com/azer/virtual-html#readme "Convert given HTML into Virtual DOM object")

## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/tunnckoCore/mich-h/issues/new).
Please read the [contributing guidelines](CONTRIBUTING.md) for advice on opening issues, pull requests, and coding standards.
If you need some help and can spent some cash, feel free to [contact me at CodeMentor.io](https://www.codementor.io/tunnckocore?utm_source=github&utm_medium=button&utm_term=tunnckocore&utm_campaign=github) too.

**In short:** If you want to contribute to that project, please follow these things

1. Please DO NOT edit [README.md](README.md), [CHANGELOG.md](CHANGELOG.md) and [.verb.md](.verb.md) files. See ["Building docs"](#building-docs) section.
2. Ensure anything is okey by installing the dependencies and run the tests. See ["Running tests"](#running-tests) section.
3. Always use `npm run commit` to commit changes instead of `git commit`, because it is interactive and user-friendly. It uses [commitizen][] behind the scenes, which follows Conventional Changelog idealogy.
4. Do NOT bump the version in package.json. For that we use `npm run release`, which is [standard-version][] and follows Conventional Changelog idealogy.

Thanks a lot! :)

## Building docs
Documentation and that readme is generated using [verb-generate-readme][], which is a [verb][] generator, so you need to install both of them and then run `verb` command like that

```
$ npm install verbose/verb#dev verb-generate-readme --global && verb
```

_Please don't edit the README directly. Any changes to the readme must be made in [.verb.md](.verb.md)._

## Running tests
Clone repository and run the following in that cloned directory

```
$ npm install && npm test
```

## Author
**Charlike Mike Reagent**

+ [github/tunnckoCore](https://github.com/tunnckoCore)
+ [twitter/tunnckoCore](https://twitter.com/tunnckoCore)
+ [codementor/tunnckoCore](https://codementor.io/tunnckoCore)

## License
Copyright © 2016-2017, [Charlike Mike Reagent](https://i.am.charlike.online). Released under the [MIT License](LICENSE).

***

_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.4.3, on March 03, 2017._
_Project scaffolded using [charlike][] cli._

[always-done]: https://github.com/hybridables/always-done
[async-done]: https://github.com/gulpjs/async-done
[babel-plugin-transform-react-jsx]: https://github.com/babel/babel
[base]: https://github.com/node-base/base
[browserify]: https://github.com/substack/node-browserify
[charlike]: https://github.com/tunnckocore/charlike
[commitizen]: https://github.com/commitizen/cz-cli
[dezalgo]: https://github.com/npm/dezalgo
[hyperscript]: https://github.com/dominictarr/hyperscript
[mich-parse-selector]: https://github.com/tunnckocore/mich-parse-selector
[mich-to-html]: https://github.com/tunnckocore/mich-to-html
[once]: https://github.com/isaacs/once
[standard-version]: https://github.com/conventional-changelog/standard-version
[verb-generate-readme]: https://github.com/verbose/verb-generate-readme
[verb]: https://github.com/verbose/verb

[downloads-url]: https://www.npmjs.com/package/mich-h
[downloads-img]: https://img.shields.io/npm/dt/mich-h.svg

[codeclimate-url]: https://codeclimate.com/github/tunnckoCore/mich-h
[codeclimate-img]: https://img.shields.io/codeclimate/github/tunnckoCore/mich-h.svg

[travis-url]: https://travis-ci.org/tunnckoCore/mich-h
[travis-img]: https://img.shields.io/travis/tunnckoCore/mich-h/master.svg?label=linux

[appveyor-url]: https://ci.appveyor.com/project/tunnckoCore/mich-h
[appveyor-img]: https://img.shields.io/appveyor/ci/tunnckoCore/mich-h/master.svg?label=windows

[coverage-url]: https://codecov.io/gh/tunnckoCore/mich-h
[coverage-img]: https://img.shields.io/codecov/c/github/tunnckoCore/mich-h/master.svg

[david-url]: https://david-dm.org/tunnckoCore/mich-h
[david-img]: https://img.shields.io/david/tunnckoCore/mich-h.svg

[standard-url]: https://github.com/feross/standard
[standard-img]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg