Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POC: feat: introduce Component class for JSX #2933

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/jsx/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { escapeToBuffer, stringBufferToString } from '../utils/html'
import type { HtmlEscaped, HtmlEscapedString, StringBuffer } from '../utils/html'
import type { Context } from './context'
import { globalContexts } from './context'
import type { Component } from './component'
import type { Hono, IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements'
import { normalizeIntrinsicElementProps, styleObjectForEach } from './utils'

Expand All @@ -26,6 +27,8 @@ export namespace JSX {
}
}

export const toFunctionComponent = Symbol()

const emptyTags = [
'area',
'base',
Expand Down Expand Up @@ -273,15 +276,19 @@ export const jsx = (
}

export const jsxFn = (
tag: string | Function,
tag: string | Function | Component,
props: Props,
children: (string | number | HtmlEscapedString)[]
): JSXNode => {
if (typeof tag === 'function') {
if (toFunctionComponent in tag) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
tag = (tag as any)[toFunctionComponent]() as Function
}
return new JSXFunctionNode(tag, props, children)
} else {
normalizeIntrinsicElementProps(props)
return new JSXNode(tag, props, children)
return new JSXNode(tag as string, props, children)
}
}

Expand Down
103 changes: 103 additions & 0 deletions src/jsx/component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import type { HtmlEscapedString } from '../utils/html'
import { jsx, memo, toFunctionComponent } from './base'
import type { FC, Props } from './base'
import { ErrorBoundary } from './components'
import { useEffect, useState } from './hooks'
import type { Context } from './context'
import { useContext } from './context'

const functionComponent = Symbol()

export abstract class Component {
static contextType?: Context<unknown>
static [functionComponent]: FC | undefined = undefined
static [toFunctionComponent](
this: (new (props: Props) => Component) & {
contextType?: Context<unknown>
[functionComponent]: FC | undefined
getDerivedStateFromProps?: (
nextProps: unknown,
prevState: unknown
) => Record<string, unknown> | null
}
): FC {
return (this[functionComponent] ||= (props: Props) => {
let instance: Component | undefined = undefined
let rerender = true
if (props.children) {
const onError = (error: Error) => instance!.componentDidCatch(error)
props.children = jsx(
ErrorBoundary,
{
onError,
},
props.children as HtmlEscapedString
)
}
;[instance] = useState<Component>(() => {
rerender = false
return new this(props)
})
// eslint-disable-next-line @typescript-eslint/unbound-method
;[instance.state, instance.setState] = useState(instance.state)
const [, forceUpdate] = useState<boolean>(true)

useEffect(() => {
instance.componentDidMount()
return () => instance.componentWillUnmount()
}, [])

useEffect(() => {
if (rerender) {
instance.componentDidUpdate()
}
})

if (rerender) {
if (this.getDerivedStateFromProps) {
props = this.getDerivedStateFromProps(props, instance!.state) as Record<string, unknown>
}
if (props !== null) {
instance!.props = props
}
} else {
if (this.contextType) {
instance!.context = useContext(this.contextType)
}
instance.forceUpdate = (cb) => {
forceUpdate((current) => !current)
cb()
}
}
return instance.render()
})
}

state: unknown
props: Record<string, unknown> = {}
context: unknown

constructor(props: Record<string, unknown> | undefined) {
this.props = props || {}
}

render(): HtmlEscapedString | Promise<HtmlEscapedString> {
throw new Error('Component subclasses must implement a render method')
}

/* eslint-disable @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars */
componentDidCatch(error: Error) {}
setState(newState: unknown): void {}
componentDidMount(): void {}
componentDidUpdate(): void {}
componentWillUnmount(): void {}
forceUpdate(callback: Function): void {}
/* eslint-enable @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars */
}

export abstract class PureComponent extends Component {
static [toFunctionComponent](this: new (props: Record<string, unknown>) => Component) {
const render = super[toFunctionComponent]()
return memo(render)
}
}
52 changes: 52 additions & 0 deletions src/jsx/dom/component.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/** @jsxImportSource ../ */
import { JSDOM } from 'jsdom'
import { Component } from '../component'
import { render, useState } from '.'

describe('Component', () => {
beforeAll(() => {
global.requestAnimationFrame = (cb) => setTimeout(cb)
})

let dom: JSDOM
let root: HTMLElement
beforeEach(() => {
dom = new JSDOM('<html><body><div id="root"></div></body></html>', {
runScripts: 'dangerously',
})
global.document = dom.window.document
global.HTMLElement = dom.window.HTMLElement
global.Text = dom.window.Text
root = document.getElementById('root') as HTMLElement
})

it('render component', async () => {
class App extends Component {
render() {
return <div>Hello</div>
}
}
render(<App />, root)
expect(root.innerHTML).toBe('<div>Hello</div>')
})

it('update props', async () => {
class C extends Component {
render() {
return <div>{this.props.count}</div>
}
}
const App = () => {
const [count, setCount] = useState(0)
return <>
<button onClick={() => setCount(count + 1)}>+</button>
<C count={count} />
</>
}
render(<App />, root)
expect(root.innerHTML).toBe('<button>+</button><div>0</div>')
root.querySelector('button')!.click()
await Promise.resolve()
expect(root.innerHTML).toBe('<button>+</button><div>1</div>')
})
})
3 changes: 3 additions & 0 deletions src/jsx/dom/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { isValidElement, memo, reactAPICompatVersion } from '../base'
import type { Child, DOMAttributes, JSX, JSXNode, Props } from '../base'
import { Children } from '../children'
import { useContext } from '../context'
import { Component } from '../component'
import {
createRef,
forwardRef,
Expand Down Expand Up @@ -72,6 +73,7 @@ const cloneElement = <T extends JSXNode | JSX.Element>(
}

export {
Component,
reactAPICompatVersion as version,
createElement as jsx,
useState,
Expand Down Expand Up @@ -110,6 +112,7 @@ export {
}

export default {
Component,
version: reactAPICompatVersion,
useState,
useEffect,
Expand Down
3 changes: 2 additions & 1 deletion src/jsx/dom/jsx-dev-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
import type { JSXNode, Props } from '../base'
import { normalizeIntrinsicElementProps } from '../utils'
import { newJSXNode } from './utils'
import type { Component } from '../component'

export const jsxDEV = (tag: string | Function, props: Props, key?: string): JSXNode => {
export const jsxDEV = (tag: string | Function | Component, props: Props, key?: string): JSXNode => {
if (typeof tag === 'string') {
normalizeIntrinsicElementProps(props)
}
Expand Down
6 changes: 6 additions & 0 deletions src/jsx/dom/render.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { toFunctionComponent } from '../base'
import type { Child, FC, JSXNode, Props } from '../base'
import { toArray } from '../children'
import { DOM_ERROR_HANDLER, DOM_INTERNAL_TAG, DOM_RENDERER, DOM_STASH } from '../constants'
Expand Down Expand Up @@ -505,6 +506,11 @@ export const buildNode = (node: Child): Node | undefined => {
})
}
if (typeof (node as JSXNode).tag === 'function') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (toFunctionComponent in (node as any).tag) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(node as JSXNode).tag = ((node as JSXNode).tag as any)[toFunctionComponent]()
}
;(node as NodeObject)[DOM_STASH] = [0, []]
} else {
const ns = nameSpaceMap[(node as JSXNode).tag as string]
Expand Down
8 changes: 6 additions & 2 deletions src/jsx/dom/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { JSXNode, Props } from '../base'
import { DOM_INTERNAL_TAG } from '../constants'
import type { Component } from '../component'

export const setInternalTagFlag = (fn: Function): Function => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand All @@ -20,5 +21,8 @@ const JSXNodeCompatPrototype = {
},
}

export const newJSXNode = (obj: { tag: string | Function; props?: Props; key?: string }): JSXNode =>
Object.defineProperties(obj, JSXNodeCompatPrototype) as JSXNode
export const newJSXNode = (obj: {
tag: string | Function | Component
props?: Props
key?: string
}): JSXNode => Object.defineProperties(obj, JSXNodeCompatPrototype) as JSXNode
3 changes: 3 additions & 0 deletions src/jsx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { DOMAttributes } from './base'
import { Children } from './children'
import { ErrorBoundary } from './components'
import { createContext, useContext } from './context'
import { Component } from './component'
import {
createRef,
forwardRef,
Expand All @@ -33,6 +34,7 @@ import {
import { Suspense } from './streaming'

export {
Component,
reactAPICompatVersion as version,
jsx,
memo,
Expand Down Expand Up @@ -69,6 +71,7 @@ export {
}

export default {
Component,
version: reactAPICompatVersion,
memo,
Fragment,
Expand Down
3 changes: 2 additions & 1 deletion src/jsx/jsx-dev-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import { jsxFn } from './base'
import type { JSXNode } from './base'
export { Fragment } from './base'
export type { JSX } from './base'
import type { Component } from './component'

export function jsxDEV(
tag: string | Function,
tag: string | Function | Component,
props: Record<string, unknown>,
key?: string
): JSXNode {
Expand Down
Loading