syntax-tree / hastscript Goto Github PK
View Code? Open in Web Editor NEWutility to create hast trees
Home Page: https://unifiedjs.com
License: MIT License
utility to create hast trees
Home Page: https://unifiedjs.com
License: MIT License
Add TypeScript type definitions
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).
When importing this module into a TypeScript project, the type should automatically be declared.
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.
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.
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.
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.
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?
8
https://jsbin.com/mivorid/2/edit?html,console
simply calling h("my-custom-element", {type: "date", value: ""}, [])
yields unexpected results.
It should yield
{
"type": "element",
"tagName": "my-custom-element",
"properties": {
"type": "date",
"value": ""
},
"children": []
}
It does yield
{
"type": "element",
"tagName": "my-custom-element",
"properties": {},
"children": [
{
"type": "date",
"value": ""
}
]
}
[email protected]/[email protected]
No response
No response
No response
hastscript==7.0.2
https://github.com/tvquizphd/hastscript-test
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"
}
The module should build without error.
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
}
}
Node v16
Other (please specify in steps to reproduce)
Linux
Other (please specify in steps to reproduce)
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.
Thank you!
There is no consistency with h()
behavoiur:
attributes
for attribues (and requires them to be kebab-case).attrs
for the same puprpose.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.
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">
This can never occur: https://github.com/syntax-tree/hastscript/blob/master/index.js#L112
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:
hastscript/lib/jsx-automatic.d.ts
Lines 9 to 12 in 2f8c133
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.
Allow functional components by removing type IntrinsicAttributes = never
. Or is there a reason they aren't?
This works, but it's clunky:
const Header = (children: HChild) => <h1 className="foo">{children}</h1>
const Section = <section>{Header("Bar")}</section>
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.
@types/react
puts JSX in declare global
. Could hastscript
do that too?
Export lib/core
.
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...)
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
.
var h = require('hastscript')
console.log(h('DIV'))
{children: [], properties: Object {}, tagName: 'div', type: 'element'}
{children: [], properties: Object {}, tagName: 'DIV', type: 'element'}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.