Coder Social home page Coder Social logo

hastscript's Issues

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.

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.

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?

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

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)

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!

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.

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">

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>

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.

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...)

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'}

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.