vadimdemedes / dom-chef Goto Github PK
View Code? Open in Web Editor NEWπ Build DOM elements using JSX automatically
License: MIT License
π Build DOM elements using JSX automatically
License: MIT License
by adding
const create = (
type: DocumentFragmentConstructor | ElementFunction | string,
+ attributes: any
): HTMLElement | SVGElement | DocumentFragment => {
// ...
- return type(type.defaultProps);
+ return type({ ...type.defaultProps, ...attributes });
};
export const h = (): Element | DocumentFragment => {
- const element = create(type);
+ const element = create(type, attributes);
}
you can create functions like this
const Flex = ({ children, gap, direction }: FlexProps}) => <div style={{ display: 'flex', flexDirection: direction ?? 'column', gap: getGap(gap ?? 'medium') }}>{children}</div>
which you can use like normal react component without the hooks and rerender on prop change, let me know if you want to add this (i can also make a pr if its too much work ;D).
Should classnames
really be part of this package? If dom-chef is meant as the plain-dom equivalent of react-dom, then maybe classnames
should be a user dependency, like it is for React users:
As I suggest in fregante/meta#1, this can be a proper ESM module and we can take the breaking opportunity to also have it output the types (instead of the handwritten d.ts)
I'm new to dom-chef
, and my React instincts quickly led me to structure some components like:
const Buttons = (props) => (
<div>
<button onClick={props.onClickSubmit}>Submit</button>
<button onClick={props.onClickCancel}>Cancel</button>
</div>
);
const App = () => (
<div>
<Buttons onClickSubmit={foo} onClickCancel={bar} />
</div>
);
But this fails because the props
parameter of Buttons
is undefined
. After reading the docs more closely, I see now that props
would only contain the component's defaultProps
.
Are you interested in supporting this style? If so, I'd be glad to attempt the PR.
First of all, thanks for the incredible work here!
In my test seems like the events are not attached to child elements.
import {h} from 'dom-chef'
function handleClick() {
console.log('hey')
}
document.body.appendChild(
<div>
<div onClick={handleClick}>
hey
</div>
</div>
);
In this example if you click on the div
nothing happens. Is this a bug or something that I get wrong?
@bfred-it, just moving our discussion about JSX and TypeScript types to this issue. For reference, here's the latest conversation about this, refined-github/refined-github#1943 (comment)
With dom-chef, we should be able to ship all the necessary types so that we don't need to include React's types as well like we currently do in Refined GitHub.
This problem occurs when you attach an onClick
handler to an element and want to access the underlying event argument. The current function signature displayed is incorrect.
Since the onClick
handler is converted into an addEventListener
, the function signature should be different from the one used in React (i.e. MouseEventHandler<HTMLButtonElement>
).
I believe this issue will occur for any on...
events that have a custom handler defined in React.
<button disabled={false}>
React won't add the attribute, but dom-chef currently does (to be "false" a boolean attribute has to be absent)
Hello! First of all, thank you for creating and maintaining this wonderful package! Now on to the problem..
This is interesting because this is an issue that I've encountered only in a browser environment. As far as I have tested, it is not reproduce-able in NodeJs with jsdom
. The thing is, CSSStyleDeclaration.setProperty()
doesn't always work apparently?
In the Chrome Dev Tools (I used Version 66.0.3359.139 (Official Build) (64-bit) on Windows), run:
const label = document.createElement('label')
label.style.setProperty('fontSize', '12px')
label.style.fontSize // will output "", should output "12px"
This is annoying because for some particular CSS properties I am forced to set the style manually without using dom-chef
. I've read the documentation on .setProperty
and I can't seem to find any warning of reference that this may happen. I find it specially strange because doing label.style['fontSize'] = "12px"
will actually work! So I'm inclined to think that this is a bug on the browser implementation of setProperty
itself.
What do you think? Do you have any clue on why this might be happening? Would it be possible to change dom-chef
's implementation to use style.cssPropertyName = 'value';
instead of setProperty
? Am I missing something?
const setCSSProps = (el, style) => {
Object
.keys(style)
.forEach(name => {
let value = style[name];
if (typeof value === 'number' && !IS_NON_DIMENSIONAL.test(name)) {
value += 'px';
}
- el.style.setProperty(name, value);
+ el.style[name] = value;
});
};
The package.json
was set to type:module
but it's not really a valid one (sigh, sindresorhus/project-ideas#116) because a dependency is a JSON file β they're not yet considered valid ES modules.
Fixing it requires bundling the JS file or vendoring it (easier)
Usage with TypeScript is rather difficult and the documentation should have section with copy-pastable code and instructions.
Edit: it will probably be made easier by #62
It looks like all default event names are lowercase and none of them have dashes: https://developer.mozilla.org/en-US/docs/Web/Events
I think there's an opportunity to add support for dashed event types via camelCased attributes:
// https://github.com/github/remote-input-element#events
<remote-input onRemoteInputSuccess={console.log} />
Currently this is converted to addEventListener('remoteinputsuccess')
but I think it's worth changing it to addEventListener('remote-input-success')
This would be a breaking change since anyone using something like <video onLoadStart={...}>
That appears to be how React people write those events as well, so perhaps this isn't a good idea.
Would be nice to bundle classnames in and be able to just pass an object to class
:
const el = <span class={{first: false, second: true}}/>;
//=> <span class="second"></span>
Automatic runtime is a feature available in v7.9.0. With this runtime enabled, the functions that JSX compiles to will be imported automatically.
When enabling automatic runtime for @babel/plugin-transform-react-jsx
, you can change from what source to use jsx/jsxs functions that transform jsx
{
"plugins": [
[
"@babel/plugin-transform-react-jsx",
{
"runtime": "automatic", // defaults to classic
"importSource": "dom-chef" // defaults to react
}
]
]
}
This will try to automatically use
import { jsx, jsxs } from 'dom-chef'
Related links:
https://babeljs.io/docs/en/babel-plugin-transform-react-jsx
babel/babel#11154
https://github.com/facebook/react/blob/master/packages/react/jsx-runtime.js
https://unpkg.io/browse/[email protected]/
<a href={undefined}>No link</a>
Results in
React.createElement("a", {
href: undefined
}, "No link");
You can test this code on https://jscomplete.com/playground
ReactDOM.render(<a href={undefined}>No link</a>, document.body)
React does not add a href
attribute but dom-chef
creates it and sets it to 'undefined'
It's needed to let bundlers know they can safely drop useless dom-chef
imports during tree-shaking.
<div style={{display: 'none'}}/>
<div style="display: none"/>
This isn't supported by JSX TypeScript types so they should be extended as well.
Like #38, but for null
<input name={null}/>
Results in
// https://babeljs.io/repl
React.createElement("input", {
name: null
});
You can test this code on https://jscomplete.com/playground
ReactDOM.render(<input name={null} />, document.body)
React does not add a name
attribute but dom-chef
creates it and sets it to 'null'
https://reactjs.org/docs/dom-elements.html#htmlfor
Currently causes this issue when used in TypeScript:
Current TypeScript workaround:
// In globals.d.ts
// More in #36
declare namespace JSX {
type LabelIntrinsicElement = IntrinsicElements['label'];
interface IntrinsicElements {
'label': LabelIntrinsicElement & {for?: string};
}
}
``
The list of SVG tags is incomplete, by looking at this one: https://github.com/wooorm/svg-tag-names/blob/master/index.json
In there you can also see regular HTML tag names so it's not as easy as requiring that module.
This uncovers an issue: all the tags in <svg><iframe></iframe></svg>
should be created with the SVG namespace, that's what the browser does:
The only way to do that is to also look for <svg>
and <foreignElement>
into the parents.
ReactDOM.render(
<div>
<p>My name is {'John'}</p>
<p>My name is {1}</p>
<p>My name is {<i>a Node</i>}</p>
<p>My name is {<>a DocumentFragment</>}</p>
<p>My name is {NaN /* rendered because typeof NaN === 'number' */}</p>
<p>My name is {false}</p>
<p>My name is {true}</p>
<p>My name is {null}</p>
<p>My name is {undefined}</p>
</div>,
document.body
);
Test it on: https://jscomplete.com/playground
Currently dom-chef
specifically tests to render falsey values as strings, but I think we should match React's behavior here.
I suppose theyβd compile to DocumentFragment
<>hello</>
Related:
As per #11, <use xlinkHref=#some-icon/>
should render <use xlink:href="#some-icon"></use>
, but the output is <use xlinkHref="#some-icon"></use>
and the icon doesn't work as expected. React converts xlinkHref
to xlink:href
as expected.
I tried using only href
, but that doesn't work on mobile Safari on iOS 11.
I'm using dom-chef: ^3.0.0
.
As is, it sounds like dom-chef will actually parse JSX, but it doesn't. The readme should mention its real API and the suggested usage with babel-plugin-transform-react-jsx
The only mention is "Make sure to use a JSX transpiler" which is actually what reads the JSX syntax.
Would be nice if there was a babel-preset-dom-chef
that set everything up for you.
Should contain:
babel-plugin-jsx
and babel-plugin-transform-react-jsx
dependenciesbabel-plugin-transform-react-jsx
configimport {h} from 'dom-chef';
. Something like https://github.com/jmm/babel-plugin-jsx-pragmatic, but that actually works. Make it ;)dom-chef
sets the attributes:
Line 77 in 99adeb6
but as far as I know JSX works with properties, not attributes: https://reactjs.org/docs/dom-elements.html#all-supported-html-attributes
This specifically breaks SVG attributes like: <line strokeWidth={1}>
It could be written as <line stroke-width={1}>
but then you'd also have to customize the TypeScript types
I think the code should be changed to set the property if it's available, but I don't know if this is "magic". React likely has a list of properties instead (I'd rather not have that)
if (name in element) {
element[name] = value;
} else {
element.setAttribute(name, value);
}
dom-chef
currently only supports creating elements via their name, which is then supplied to document.createElement(name)
JSX also supports creating elements with a function, like <Dropdown>
.
In our case, Dropdown()
returns a regular DOM element. The advantage would be using JSX to set attributes and append children in this new element (however without a <slot>
placeholder)
<Logo className="color-red"/>
// Instead of:
const logo = Logo();
logo.classList.add('color-red');
<Dropdown>
<Item>1</Item>
<Item>2</Item>
<Item>3</Item>
</Dropdown>
// Instead of something imperative much longer
<Icon/>
is transpiled to React.createElement(Icon)
<icon/>
is transpiled to React.createElement('icon')
Would be cool to use inline-style-prefixer to autoprefix style
props.
We use simple property accessors to set the style
:
Line 28 in 29186fa
This means that CSS variables aren't supported: refined-github/refined-github#3454 (comment)
<div
style={{
'--color': 'red'
}}
/>
More info: https://babeljs.io/docs/en/babel-plugin-transform-react-jsx
TypeScript issue: microsoft/TypeScript#34547
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.