Coder Social home page Coder Social logo

hastscript's Introduction

hastscript

Build Coverage Downloads Size Sponsors Backers Chat

hast 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 hast trees.

When should I use this?

You can use this utility in your project when you generate hast syntax trees with code. It helps because it replaces most of the repetition otherwise needed in a syntax tree with function calls. It also helps as it improves the attributes you pass by turning them into the form that is required by hast.

You can instead use unist-builder when creating any unist nodes and xastscript when creating xast (XML) nodes.

Install

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

npm install hastscript

In Deno with esm.sh:

import {h} from 'https://esm.sh/hastscript@9'

In browsers with esm.sh:

<script type="module">
  import {h} from 'https://esm.sh/hastscript@9?bundle'
</script>

Use

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', {xmlns: 'http://www.w3.org/2000/svg', viewbox: '0 0 500 500'}, [
    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: {xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 500 500'},
  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: []
    }
  ]
}

API

This package exports the identifiers h and s. There is no default export.

The export map supports the automatic JSX runtime. You can pass hastscript or hastscript/svg to your build tool (TypeScript, Babel, SWC) with an importSource option or similar.

h(selector?[, properties][, …children])

Create virtual hast trees for HTML.

Signatures
  • h(): root
  • h(null[, …children]): root
  • h(selector[, properties][, …children]): element
Parameters
selector

Simple CSS selector (string, optional). 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, h defaults to build a div element, and s to a g element. selector is parsed by hast-util-parse-selector. When string, builds an Element. When nullish, builds a Root instead.

properties

Properties of the element (Properties, optional).

children

Children of the node (Child or Array<Child>, optional).

Returns

Created tree (Result).

Element when a selector is passed, otherwise Root.

s(selector?[, properties][, …children])

Create virtual hast trees for SVG.

Signatures, parameters, and return value are the same as h above. Importantly, the selector and properties parameters are interpreted as SVG.

Child

(Lists of) children (TypeScript type).

When strings or numbers are encountered, they are turned into Text nodes. Root nodes are treated as “fragments”, meaning that their children are used instead.

Type
type Child =
  | Array<Node | number | string | null | undefined>
  | Node
  | number
  | string
  | null
  | undefined

Properties

Map of properties (TypeScript type). Keys should match either the HTML attribute name, or the DOM property name, but are case-insensitive.

Type
type Properties = 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

Result from a h (or s) call (TypeScript type).

Type
type Result = Element | Root

Syntax tree

The syntax tree is hast.

JSX

This package can be used with JSX. You should use the automatic JSX runtime set to hastscript or hastscript/svg.

👉 Note: while h supports dots (.) for classes or number signs (#) for IDs in selector, 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 (or s) yourself and define it as the pragma (plus set the fragment to null).

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(
  <div class="foo" id="some-id">
    <span>some text</span>
    <input type="text" value="foo" />
    <a class="alpha bravo charlie" download>
      deltaecho
    </a>
  </div>
)

example-svg.jsx:

/** @jsxImportSource hastscript/svg */
console.log(
  <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 500 500">
    <title>SVG `&lt;circle&gt;` element</title>
    <circle cx={120} cy={120} r={100} />
  </svg>
)

Types

This package is fully typed with TypeScript. It exports the additional types Child, Properties, and Result.

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, hastscript@^9, compatible with Node.js 16.

Security

Use of hastscript can open you up to a cross-site scripting (XSS) when you pass user-provided input to it because values are injected into the syntax tree.

The following example shows how an image is injected that fails loading and therefore runs code in a browser.

const tree = h()

// Somehow someone injected these properties instead of an expected `src` and
// `alt`:
const otherProps = {src: 'x', onError: 'alert(1)'}

tree.children.push(h('img', {src: 'default.png', ...otherProps}))

Yields:

<img src="x" onerror="alert(1)">

The following example shows how code can run in a browser because someone stored an object in a database instead of the expected string.

const tree = h()

// Somehow this isn’t the expected `'wooorm'`.
const username = {
  type: 'element',
  tagName: 'script',
  children: [{type: 'text', value: 'alert(2)'}]
}

tree.children.push(h('span.handle', username))

Yields:

<span class="handle"><script>alert(2)</script></span>

Either do not use user-provided input in hastscript or use hast-util-santize.

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

hastscript's People

Contributors

brechtcs avatar christianmurphy avatar cowboyd avatar greenkeeperio-bot avatar taylorbeeston 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  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

hastscript's Issues

How to create boolean attributes?

h('button', { disabled: true })
h('button', { disabled: false })

will produce:

<button disabled="true"></button>
<button disabled="false"></button>

Is there any chance that we can make it produce this?

<button disabled></button>
<button></button>

(And this is gonna be a breaking change...)

SVG support

Hi, I just noticed there is a camel case issue in SVG. The property 'viewBox' will be parsed as 'view-box' in the produced HTML.

e.g.
Input

h('svg', {
    fill: '#000000',
    height: 24,
    width: 24,
    viewBox: '0 0 24 24',
    xmlns: 'http://www.w3.org/2000/svg',
    class: 'carousel-prev-step'
}

Output

<svg fill="#000000" height="24" width="24" view-box="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="carousel-prev-step"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg>

The expected result should be <svg viewBox="0 0 24 24">

Add docs for different `h()` algorithms

There is no consistency with h() behavoiur:

  • virtual-hyperscript uses property attributes for attribues (and requires them to be kebab-case).
  • snabbdom uses property attrs for the same puprpose.
  • hyperscript?
  • whatever ancestor of hyperscript?

And all of them does not document anything. Actual behaviour is salvaged from experiment and issues.

It would be really nice if hastscript would document what is actual format of h() arguments. Sorry if I'm missing something and this all is false.

custom element attributes are returned as children rather than properties

Initial checklist

Affected packages and versions

8

Link to runnable example

https://jsbin.com/mivorid/2/edit?html,console

Steps to reproduce

simply calling h("my-custom-element", {type: "date", value: ""}, []) yields unexpected results.

Expected behavior

It should yield

{
    "type": "element",
    "tagName": "my-custom-element",
    "properties": {
        "type": "date",
        "value": ""
    },
    "children": []
}

Actual behavior

It does yield

{
    "type": "element",
    "tagName": "my-custom-element",
    "properties": {},
    "children": [
        {
            "type": "date",
            "value": ""
        }
    ]
}

Affected runtime and version

[email protected]/[email protected]

Affected package manager and version

No response

Affected OS and version

No response

Build and bundle tools

No response

Add support for normalising tag names

Subject of the issue

Just like with properties, tag names should be normalised and fixed:

Tags contain a tag name, giving the element's name. HTML elements all have names that only use ASCII alphanumerics. In the HTML syntax, tag names, even those for foreign elements, may be written with any mix of lower- and uppercase letters that, when converted to all-lowercase, matches the element's tag name; tag names are case-insensitive.

We could lower-case all tag names. Even those for SVG, because of the reasons given in the above quote.
However, it makes more sense to me to use the proper name as defined by SVG, such as textPath instead of textpath.

Your environment

Steps to reproduce

var h = require('hastscript')
console.log(h('DIV'))

Expected behaviour

{children: [], properties: Object {}, tagName: 'div', type: 'element'}

Actual behaviour

{children: [], properties: Object {}, tagName: 'DIV', type: 'element'}

Support camelCased source properties

Hi,
I would like to use the hype ecosystem to build my own html formatter but I'm facing with a big issue. I use a fork of parse5 in order to handle element attributes case-sensitive for web frameworks like Angular, VueJs.

hastscript doesn't respect (in my case parse5 tree) as the source of truth (https://github.com/syntax-tree/hastscript/blob/master/index.js#L144) because it converts all attributes to camelCases, which I think is wrong from the point of view of a parser tool. But anyway I understand the reasons and my project isn't html5 compliant but it would be very great to have that flexibility in rehype precisely because rehype serve as a general interface between html parsers.

  • I couldn't find in the specification that attributes are handled case-insensitive.

Thank you!

Allow functional components in JSX

Initial checklist

Problem

I'm using TypeScript. I'd like to do something like this:

const Header = ({ children }: { children: HChild }) => <h1 className="foo">{children}</h1>
const Section = <section><Header>Bar</Header></section>

But this line makes TypeScript reject it:

/**
* This disallows the use of functional components.
*/
type IntrinsicAttributes = never

With one of the following errors (depending on the amount of children provided):

This JSX tag's 'children' prop expects a single child of type 'never', but multiple children were provided.
This JSX tag's 'children' prop expects type 'never' which requires multiple children, but only a single child was provided.

Solution

Allow functional components by removing type IntrinsicAttributes = never. Or is there a reason they aren't?

Alternatives

This works, but it's clunky:

const Header = (children: HChild) => <h1 className="foo">{children}</h1>
const Section = <section>{Header("Bar")}</section>

Add type definitions

Subject of the feature

Add TypeScript type definitions

Problem

It is currently difficult to use this package in a TypeScript project due to a lack of type definitions. This in turn also makes it different to add type definitions to a package that depends on this package (such as hast-util-sanitize).

Expected behaviour

When importing this module into a TypeScript project, the type should automatically be declared.

Alternatives

An alternative to simply adding a .d.ts file would be to actually convert the whole package to TypeScript, however it is much easier to simply add a .d.ts file.

Dynamic import issue for TypeScript 4.5.0-beta "module" of "nodenext" or "node12"

Initial checklist

Affected packages and versions

hastscript==7.0.2

Link to runnable example

https://github.com/tvquizphd/hastscript-test

Steps to reproduce

In index.ts, I simply import h from hastscript:

import { h } from 'hastscript' 

Here's a relevant tsconfig.json snippet:

  "compilerOptions": {
    "target": "es6",
    "outDir": "dist",
    "declaration": true,
    "module": "node12"
  }

Here's a relevant package.json snippet:

 "dependencies": {
   "hastscript": "^7.0.2"
 },
 "devDependencies": {
   "typescript": "^4.5.0-beta"
 }

Expected behavior

The module should build without error.

Actual behavior

There seems to be an error with dynamic import of jsx-classic in html.d.ts and svg.d.ts:

yarn run v1.22.17
warning package.json: No license field
$ tsc
node_modules/hastscript/lib/html.d.ts(19,27): error TS2307: Cannot find module './jsx-classic' or its corresponding type declarations.
node_modules/hastscript/lib/html.d.ts(20,39): error TS2307: Cannot find module './jsx-classic' or its corresponding type declarations.
node_modules/hastscript/lib/html.d.ts(21,37): error TS2307: Cannot find module './jsx-classic' or its corresponding type declarations.
node_modules/hastscript/lib/html.d.ts(23,14): error TS2307: Cannot find module './jsx-classic' or its corresponding type declarations.
node_modules/hastscript/lib/svg.d.ts(19,27): error TS2307: Cannot find module './jsx-classic' or its corresponding type declarations.
node_modules/hastscript/lib/svg.d.ts(20,39): error TS2307: Cannot find module './jsx-classic' or its corresponding type declarations.
node_modules/hastscript/lib/svg.d.ts(21,37): error TS2307: Cannot find module './jsx-classic' or its corresponding type declarations.
node_modules/hastscript/lib/svg.d.ts(23,14): error TS2307: Cannot find module './jsx-classic' or its corresponding type declarations.
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this comman

Here are lines 17-25 of node_modules/hastscript/lib/html.d.ts:

export namespace h {
  namespace JSX {
    type Element = import('./jsx-classic').Element
    type IntrinsicAttributes = import('./jsx-classic').IntrinsicAttributes
    type IntrinsicElements = import('./jsx-classic').IntrinsicElements
    type ElementChildrenAttribute =
      import('./jsx-classic').ElementChildrenAttribute
  }
}

Runtime

Node v16

Package manager

Other (please specify in steps to reproduce)

OS

Linux

Build and bundle tools

Other (please specify in steps to reproduce)

Issues bundling for production with `camelcase` dep

Not sure if I'm the only one to run into this issue, but he takes a hard stance here sindresorhus/ama#446. Problem is this causes uglify to choke in most systems using webpack since vendor dependencies are generally not babelified.

Do we really need to import a library here or can we just use a simple camel case function like:

const hyphenToCamelCase = str => str.replace(/-([a-z])/g, (m, w) => w.toUpperCase())

to handle the majority of these cases?

Support for Exotics

Initial checklist

Problem

This is arguably outside of the scope of the reason that hastscript exists, and I fully acknowledge that. However, I do believe it would be a value add.

I'm working on jsx-email and one of my goals to have cross-framework compatibility with the components it exports - effectively untethering from requiring react as a dependency. One of the bananas scenarios there is that users are running the components it exports in several different environments, one of which is Storybook. Since it has a few components that perform async operations, it needs to use <Suspense/>. Similar to Fragment in react, this is a symbol with children, with the added fallback prop.

I put together a little test script to see what would happen should I inject react-specific JSX into the generic JSX supported by hastscript:

/** @jsxImportSource hastscript */

import { h } from 'hastscript';
import { toJsxRuntime } from 'hast-util-to-jsx-runtime';
import { Suspense } from 'react';
import * as reactRuntime from 'react/jsx-runtime';

const component = (
  <>
    <Suspense fallback={<div>waiting</div>}>
      <div class="foo" id="some-id"></div>
    </Suspense>
  </>
);

console.log(component);
console.log();
console.log(toJsxRuntime(component, reactRuntime as any));

I was pleasantly surprised to find that it handled the Suspense "component" there quite gracefully by simply discarding it:

{
  type: 'root',
  children: [
    {
      type: 'element',
      tagName: 'div',
      properties: [Object],
      children: [Array]
    }
  ]
}

But that result (in this potentially erroneous context) discards the Suspense component altogether. Using hast-util-to-jsx-runtime to convert it to React predictably results in the missing Suspense component.

To that end, I'd love to see support for exotic components (which may just be symbols that have props) in hastscript. While probably not the intended use it would open up some new possibilities for this lib's use.

Solution

I'm not quite sure how this would be accomplished, and since I'm in an evaluation phase of possible broader solutions for my use-case, I haven't done a deep dive on the code here to suggest a path forward. I would love to get your initial thoughts on how this might be supported.

Alternatives

I've been unsuccessfully working on a generic renderer that can handle JSX formats of React, Preact, and SolidJS. The variances are significant and I haven't been able to accommodate them all - and that doesn't even go into the type incompatibilities between them. Coupled with the fact that I'd have to race to keep up with any changes in each framework, it seems like a losing path over time. I was excited to find this and hast-util-to-jsx-runtime because it opens a new path where I can write my components in a standard which can then be converted to the appropriate format for each.

Expose ~JSX namespace~ `HResult` globally

Initial checklist

Problem

I'm using TypeScript with "moduleResolution": "Node16" and JSX, and I want to have explicit return types. Currently I do this:

import type { Root, Element } from "hast";
const Foo = (): Root | Element => <div />;

Instead, I'd like to be able to do this:

const Foo = (): JSX.Element => <div />;

I know it's an alias of HResult, which can be imported from lib/core, but it isn't idiomatic, and lib/core currently isn't exposed, so it doesn't work in this module resolution mode.

Solution

@types/react puts JSX in declare global. Could hastscript do that too?

Alternatives

Export lib/core.

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.