Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork13
utility to create hast trees
License
syntax-tree/hastscript
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
hast utility to create trees with ease.
- What is this?
- When should I use this?
- Install
- Use
- API
- Syntax tree
- JSX
- Compatibility
- Security
- Related
- Contribute
- License
This package is a hyperscript interface (likecreateElement
from React andh
from Vue and such) to help with creating hast trees.
You can use this utility in your project when you generate hast syntax treeswith code.It helps because it replaces most of the repetition otherwise needed in a syntaxtree with function calls.It also helps as it improves the attributes you pass by turning them into theform that is required by hast.
You can instead useunist-builder
when creating any unist nodes andxastscript
when creating xast (XML) nodes.
This package isESM only.In Node.js (version 16+),install withnpm:
npm install hastscript
In Deno withesm.sh
:
import{h}from'https://esm.sh/hastscript@9'
In browsers withesm.sh
:
<scripttype="module">import{h}from'https://esm.sh/hastscript@9?bundle'</script>
import{h,s}from'hastscript'console.log(h('.foo#some-id',[h('span','some text'),h('input',{type:'text',value:'foo'}),h('a.alpha',{class:'bravo charlie',download:'download'},['delta','echo'])]))console.log(s('svg',{viewbox:'0 0 500 500',xmlns:'http://www.w3.org/2000/svg'},[s('title','SVG `<circle>` element'),s('circle',{cx:120,cy:120,r:100})]))
Yields:
{type:'element',tagName:'div',properties:{className:['foo'],id:'some-id'},children:[{type:'element',tagName:'span',properties:{},children:[{type:'text',value:'some text'}]},{type:'element',tagName:'input',properties:{type:'text',value:'foo'},children:[]},{type:'element',tagName:'a',properties:{className:['alpha','bravo','charlie'],download:true},children:[{type:'text',value:'delta'},{type:'text',value:'echo'}]}]}{type:'element',tagName:'svg',properties:{viewBox:'0 0 500 500',xmlns:'http://www.w3.org/2000/svg'},children:[{type:'element',tagName:'title',properties:{},children:[{type:'text',value:'SVG `<circle>` element'}]},{type:'element',tagName:'circle',properties:{cx:120,cy:120,r:100},children:[]}]}
This package exports the identifiersh
ands
.There is no default export.It exports the additionalTypeScript typesChild
,Properties
,andResult
.
The export map supports the automatic JSX runtime.You can passhastscript
orhastscript/svg
to your build tool(TypeScript, Babel, SWC)with animportSource
option or similar.
Create virtualhast trees for HTML.
h(): root
h(null[, …children]): root
h(selector[, properties][, …children]): element
Simple CSS selector(string
, optional).When string, builds anElement
.When nullish, builds aRoot
instead.The selector can contain a tag name (foo
),IDs (#bar
),and classes (.baz
).If the selector is a string but there is no tag name in it thenh
defaults tobuild adiv
element ands
to ag
element.selector
is parsed byhast-util-parse-selector
.
Properties of the element(Properties
, optional).
Children of the node (Child
orArray<Child>
, optional).
Created tree (Result
).
Element
when aselector
is passed,otherwiseRoot
.
Create virtualhast trees for SVG.
Signatures, parameters, and return value are the same ash
above.Importantly,theselector
andproperties
parameters are interpreted as SVG.
(Lists of) children (TypeScript type).
When strings or numbers are encountered,they are turned intoText
nodes.Root
nodes are treated as “fragments”,meaning that their children are used instead.
typeChild=|Array<Node|number|string|null|undefined>|Node|number|string|null|undefined
Map of properties (TypeScript type).Keys should match either the HTML attribute name or the DOM property name,but are case-insensitive.
typeProperties=Record<string,|boolean|number|string|null|undefined// For comma- and space-separated values such as `className`:|Array<number|string>// Accepts value for `style` prop as object.|Record<string,number|string>>
Result from ah
(ors
) call (TypeScript type).
typeResult=Element|Root
The syntax tree ishast.
This package can be used with JSX.You should use the automatic JSX runtime set tohastscript
orhastscript/svg
.
👉Notewhile
h
supports dots (.
) for classes or number signs (#
)for IDs inselector
,those are not supported in JSX.
🪦Legacy:you can also use the classic JSX runtime,but this is not recommended.To do so,import
h
(ors
) yourself and define it as the pragma(plus set the fragment tonull
).
The Use example above can then be written like so,using inline pragmas,so that SVG can be used too:
example-html.jsx
:
/**@jsxImportSource hastscript */console.log(<divclass="foo"id="some-id"><span>some text</span><inputtype="text"value="foo"/><aclass="alpha bravo charlie"download> deltaecho</a></div>)
example-svg.jsx
:
/**@jsxImportSource hastscript/svg */console.log(<svgxmlns="http://www.w3.org/2000/svg"viewbox="0 0 500 500"><title>SVG `<circle>` element</title><circlecx={120}cy={120}r={100}/></svg>)
Projects maintained by the unified collective are compatible with maintainedversions 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,hastscript@9
,compatible with Node.js 16.
Use ofhastscript
can open you up to across-site scripting (XSS)when you pass user-provided input to it because values are injected into thesyntax tree.
The following example shows how an image is injected that fails loading andtherefore runs code in a browser.
consttree=h()// Somehow someone injected these properties instead of an expected `src` and// `alt`:constotherProps={onError:'alert(1)',src:'x'}tree.children.push(h('img',{src:'default.png', ...otherProps}))
Yields:
<imgonerror="alert(1)"src="x">
The following example shows how code can run in a browser because someone storedan object in a database instead of the expected string.
consttree=h()// Somehow this isn’t the expected `'wooorm'`.constusername={type:'element',tagName:'script',children:[{type:'text',value:'alert(2)'}]}tree.children.push(h('span.handle',username))
Yields:
<spanclass="handle"><script>alert(2)</script></span>
Either do not use user-provided input inhastscript
or usehast-util-santize
.
unist-builder
— create unist treesxastscript
— create xast treeshast-to-hyperscript
— turn hast into React, Preact, Vue, etchast-util-to-html
— turn hast into HTMLhast-util-to-dom
— turn hast into DOM treesestree-util-build-jsx
— compile JSX away
Seecontributing.md
insyntax-tree/.github
for ways to get started.Seesupport.md
for ways to get help.
This project has acode of conduct.By interacting with this repository,organization,or community you agree to abide by its terms.
About
utility to create hast trees
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
Contributors7
Uh oh!
There was an error while loading.Please reload this page.