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

feat(jsx/dom): improve compatibility with React #2553

Merged
merged 24 commits into from Apr 30, 2024

Conversation

usualoma
Copy link
Member

@usualoma usualoma commented Apr 24, 2024

#2508

What is this?

Improve compatibility with React and make the Getting started level code work for the following UI components

CleanShot.2024-04-24.at.22.14.10.mp4

by https://github.com/usualoma/hono-react-compat-demo

Simple usage

tsconfig.json
https://github.com/usualoma/hono-react-compat-demo/blob/main/tsconfig.json#L22-L28

vite.config.ts
https://github.com/usualoma/hono-react-compat-demo/blob/main/vite.config.ts#L5-L8

You can use /hono/jsx

It is better to use hono/jsx/dom in terms of performance, but simply specifying hono/jsx works just as well.

tsconfig.json

   "paths": {
      "react": ["./node_modules/hono/dist/jsx"],
      "react-dom": ["./node_modules/hono/dist/jsx/dom"],
    },

vite.config.ts

    alias: {
      'react': 'hono/jsx',
      'react-dom': 'hono/jsx/dom',
    },

New staffs

The following React compatible staffs are now exported from hono/jsx and hono/jsx/dom

  • createRef
  • forwardRef
  • useImperativeHandle
  • useSyncExternalStore

These staff are also exported from hono/jsx/dom.

  • flushSync
  • createPortal

Children

Implement Children API

https://react.dev/reference/react/Children#alternatives

CSS custom properties in style attribute

CSS custom properties can now be exported.

<div style={{"--my-custom-property": "10px"}}>{children}</div>

defaultProps

defaultProps is an old API, but there seems to be a library that uses it, so it is supported

https://legacy.reactjs.org/docs/react-component.html#defaultprops

Bug fixes

Various bugs have been fixed, such as the behaviour when deleting Elements.

Compatibility with [email protected]

There are no breaking changes from v4.2.7. However, the internal structure has been significantly refactored and there is a possibility of unintended incompatible behaviour, so please check the behaviour of your application when updating.

Author should do the followings, if applicable

  • Add tests
  • Run tests
  • yarn denoify to generate files for Deno

@usualoma usualoma force-pushed the feat/compat-react-element branch 2 times, most recently from ddcd4ca to 8c6dc95 Compare April 24, 2024 13:12
@usualoma usualoma force-pushed the feat/compat-react-element branch 3 times, most recently from 009083a to d3f0cce Compare April 25, 2024 14:20
@yusukebe
Copy link
Member

@usualoma

Coooool! I've tried your repo, it works great!

@usualoma usualoma changed the title [WIP] feat(jsx/dom): improve compatibility with React feat(jsx/dom): improve compatibility with React Apr 25, 2024
@usualoma usualoma marked this pull request as ready for review April 25, 2024 23:19
@usualoma
Copy link
Member Author

@yusukebe
Thanks for confirming.
Tests have been added and are ready for merging!

Copy link
Member

@yusukebe yusukebe left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@yusukebe
Copy link
Member

Hi @usualoma !

I'll merge this into the "next" branch! The next minor version will be released soon.

@yusukebe yusukebe merged commit 0653153 into honojs:next Apr 30, 2024
10 checks passed
nicolewhite pushed a commit to autoblocksai/cli that referenced this pull request May 3, 2024
[![Mend
Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com)

This PR contains the following updates:

| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
| [hono](https://hono.dev/) ([source](https://togithub.com/honojs/hono))
| [`4.2.9` ->
`4.3.0`](https://renovatebot.com/diffs/npm/hono/4.2.9/4.3.0) |
[![age](https://developer.mend.io/api/mc/badges/age/npm/hono/4.3.0?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![adoption](https://developer.mend.io/api/mc/badges/adoption/npm/hono/4.3.0?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![passing](https://developer.mend.io/api/mc/badges/compatibility/npm/hono/4.2.9/4.3.0?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![confidence](https://developer.mend.io/api/mc/badges/confidence/npm/hono/4.2.9/4.3.0?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|

---

### Release Notes

<details>
<summary>honojs/hono (hono)</summary>

### [`v4.3.0`](https://togithub.com/honojs/hono/releases/tag/v4.3.0)

[Compare
Source](https://togithub.com/honojs/hono/compare/v4.2.9...v4.3.0)

Hono v4.3.0 is now available! Let's take a look at the new features.

#### Improve the RPC-mode

Thanks to [@&#8203;kosei28](https://togithub.com/kosei28),
[@&#8203;nakasyou](https://togithub.com/nakasyou), and
[@&#8203;NamesMT](https://togithub.com/NamesMT), the RPC mode has been
improved!

##### `c.text()` is typed

The response of `c.text()` was just a `Response` object, not typed.

```ts
const routes = app.get('/about/me', (c) => {
  return c.text('Me!') // the response is not typed
})
```

With this release, it will be a `TypedResponse` and you can get the type
within the client created by `hc`.

```ts
const client = hc<typeof routes>('http://localhost:8787')

const res = await client.about.me.$get()
const text = await res.text() // text is typed as "Me!"
const json = await res.json() // json is never!
```

##### Support all JSON primitives

We added the tests for the responses of `c.json()` to have the correct
types and support inferring all primitives. The all tests below are
passed!

```ts
const app = new Hono()
const route = app
  .get('/api/string', (c) => c.json('a-string'))
  .get('/api/number', (c) => c.json(37))
  .get('/api/boolean', (c) => c.json(true))
  .get('/api/generic', (c) => c.json(Math.random() > 0.5 ? Boolean(Math.random()) : Math.random()))
type AppType = typeof route

const client = hc<AppType>('http://localhost')

const stringFetch = await client.api.string.$get()
const stringRes = await stringFetch.json()
const numberFetch = await client.api.number.$get()
const numberRes = await numberFetch.json()
const booleanFetch = await client.api.boolean.$get()
const booleanRes = await booleanFetch.json()
const genericFetch = await client.api.generic.$get()
const genericRes = await genericFetch.json()

type stringVerify = Expect<Equal<'a-string', typeof stringRes>>
expect(stringRes).toBe('a-string')
type numberVerify = Expect<Equal<37, typeof numberRes>>
expect(numberRes).toBe(37)
type booleanVerify = Expect<Equal<true, typeof booleanRes>>
expect(booleanRes).toBe(true)
type genericVerify = Expect<Equal<number | boolean, typeof genericRes>>
expect(typeof genericRes === 'number' || typeof genericRes === 'boolean').toBe(true)

// using .text() on json endpoint should return string
type textTest = Expect<Equal<Promise<string>, ReturnType<typeof genericFetch.text>>>
```

##### Status code type

If you explicitly specify the status code, such as `200` or `404`, in
`c.json()`. It will be added as a type for passing to the client.

```ts
// server.ts
const app = new Hono().get(
  '/posts',
  zValidator(
    'query',
    z.object({
      id: z.string()
    })
  ),
  async (c) => {
    const { id } = c.req.valid('query')
    const post: Post | undefined = await getPost(id)

    if (post === undefined) {
      return c.json({ error: 'not found' }, 404) // Specify 404
    }

    return c.json({ post }, 200) // Specify 200
  }
)

export type AppType = typeof app
```

You can get the data by the status code.

```ts
// client.ts
const client = hc<AppType>('http://localhost:8787/')

const res = await client.posts.$get({
  query: {
    id: '123'
  }
})

if (res.status === 404) {
  const data: { error: string } = await res.json()
  console.log(data.error)
}

if (res.ok) {
  const data: { post: Post } = await res.json()
  console.log(data.post)
}

// { post: Post } | { error: string }
type ResponseType = InferResponseType<typeof client.posts.$get>

// { post: Post }
type ResponseType200 = InferResponseType<typeof client.posts.$get, 200>
```

#### Improve compatibility with React

The compatibility of `hono/jsx/dom` has been improved. Now, these React
libraries work with `hono/jsx/dom`!

-   [react-toastify](https://togithub.com/fkhadra/react-toastify)
-   [spinners-react](https://togithub.com/adexin/spinners-react)
-   [Radix UI Primitives](https://www.radix-ui.com/primitives)

The below demo is working with `hono/jsx/dom`, not React.

![Google
Chrome](https://togithub.com/honojs/hono/assets/10682/b2f93c52-d1b6-40ea-b075-22c49d18a723)

If you want to use React libraries with `hono/jsx/dom`, set-up
`tsconfig.json` and `vite.config.ts` like the followings:

`tsconfig.json`:

```json
{
  "compilerOptions": {
    "paths": {
      "react": ["./node_modules/hono/dist/jsx/dom"],
      "react-dom": ["./node_modules/hono/dist/jsx/dom"]
    }
  }
}
```

`vite.config.ts`:

```ts
import { defineConfig } from 'vite'

export default defineConfig({
  resolve: {
    alias: {
      react: 'hono/jsx/dom',
      'react-dom': 'hono/jsx/dom'
    }
  }
})
```

Thanks [@&#8203;usualoma](https://togithub.com/usualoma)!

#### `createApp()` in Factory Helper

`createApp()` method is added to Factory Helper. If you use this method
with `createFactory()`, you can avoid redundancy in the definition of
the `Env` type.

If your application is like this, you have to set the `Env` in two
places:

```ts
import { createMiddleware } from 'hono/factory'

type Env = {
  Variables: {
    myVar: string
  }
}

// 1. Set the `Env` to `new Hono()`
const app = new Hono<Env>()

// 2. Set the `Env` to `createMiddleware()`
const mw = createMiddleware<Env>(async (c, next) => {
  await next()
})

app.use(mw)
```

By using `createFactory()` and `createApp()`, you can set the Env only
in one place.

```ts
import { createFactory } from 'hono/factory'

// ...

// Set the `Env` to `createFactory()`
const factory = createFactory<Env>()

const app = factory.createApp()

// factory also has `createMiddleware()`
const mw = factory.createMiddleware(async (c, next) => {
  await next()
})
```

#### Deprecate `serveStatic` for Cloudflare Workers

`serveStatic` exported by `hono/cloudflare-workers` has been deprecated.
If you create an application which serves static asset files, use
Cloudflare Pages instead.

#### Other features

- Cookie Helper - delete cookie returns the deleted value
[honojs/hono#2512
- Bearer Authenticate - add `headerName` option
[honojs/hono#2514
- JSX/DOM - preserve the state of element even if it is repeatedly
evaluated by children
[honojs/hono#2563
- Mimes utility - expose built-in MIME types
[honojs/hono#2516
- Serve Static - expose serve-static builder
[honojs/hono#2515
- Secure Headers - enable to set nonce in CSP
[honojs/hono#2577
- Server-Timing - allow `crossOrigin` in TimingOptions to be a function
[honojs/hono#2359
- Client - add `init` option
[honojs/hono#2592

#### All Updates

- fix(request): infer params in a path includes one or more optional
parameter by [@&#8203;yusukebe](https://togithub.com/yusukebe) in
[honojs/hono#2576
- feat(rpc): Add status code to response type by
[@&#8203;kosei28](https://togithub.com/kosei28) in
[honojs/hono#2499
- feat(helper/cookie): delete cookie returns the deleted value by
[@&#8203;sor4chi](https://togithub.com/sor4chi) in
[honojs/hono#2512
- feat(bearer-auth): add `headerName` option by
[@&#8203;eliasbrange](https://togithub.com/eliasbrange) in
[honojs/hono#2514
- feat(jsx/dom): improve compatibility with React by
[@&#8203;usualoma](https://togithub.com/usualoma) in
[honojs/hono#2553
- fix(jsx): preserve the state of element even if it is repeatedly
evaluated by children by
[@&#8203;usualoma](https://togithub.com/usualoma) in
[honojs/hono#2563
- feat: expose built-in MIME types by
[@&#8203;cometkim](https://togithub.com/cometkim) in
[honojs/hono#2516
- feat: expose serve-static builder by
[@&#8203;cometkim](https://togithub.com/cometkim) in
[honojs/hono#2515
- feat(secure-headers): enable to set nonce in CSP by
[@&#8203;usualoma](https://togithub.com/usualoma) in
[honojs/hono#2577
- chore(pr_template): Use Bun instead of yarn by
[@&#8203;nakasyou](https://togithub.com/nakasyou) in
[honojs/hono#2582
- feat(cloudflare-workers): deprecate `serveStatic` by
[@&#8203;yusukebe](https://togithub.com/yusukebe) in
[honojs/hono#2583
- feat(types): improve response types flow by
[@&#8203;NamesMT](https://togithub.com/NamesMT) in
[honojs/hono#2581
- docs(readme): remove Benchmarks section by
[@&#8203;yusukebe](https://togithub.com/yusukebe) in
[honojs/hono#2591
- feat: improve `ToSchema` & `WebSocket Helper` types by
[@&#8203;NamesMT](https://togithub.com/NamesMT) in
[honojs/hono#2588
- feat(factory): add `createApp()` by
[@&#8203;yusukebe](https://togithub.com/yusukebe) in
[honojs/hono#2573
- feat(hc): add `init` option by
[@&#8203;NamesMT](https://togithub.com/NamesMT) in
[honojs/hono#2592
- feat(timing): allow crossOrigin in TimingOptions to be a function by
[@&#8203;jonahsnider](https://togithub.com/jonahsnider) in
[honojs/hono#2359
- Next by [@&#8203;yusukebe](https://togithub.com/yusukebe) in
[honojs/hono#2600

#### New Contributors

- [@&#8203;kosei28](https://togithub.com/kosei28) made their first
contribution in
[honojs/hono#2499
- [@&#8203;NamesMT](https://togithub.com/NamesMT) made their first
contribution in
[honojs/hono#2581
- [@&#8203;jonahsnider](https://togithub.com/jonahsnider) made their
first contribution in
[honojs/hono#2359

**Full Changelog**:
honojs/hono@v4.2.9...v4.3.0

</details>

---

### Configuration

📅 **Schedule**: Branch creation - "before 4am on Monday" in timezone
America/Chicago, Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend
Renovate](https://www.mend.io/free-developer-tools/renovate/). View
repository job log
[here](https://developer.mend.io/github/autoblocksai/cli).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4zMzEuMCIsInVwZGF0ZWRJblZlciI6IjM3LjMzMS4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
@timurxyz
Copy link

Was able to integrate
https://ui.shadcn.com/docs/components/calendar#form
as an island with the above setup and 4.3.6. Picking works. The toast part doesn't yet.

@timurxyz
Copy link

I might horribly be disoriented if the below is a missing piece, but let me share my poc:

mountReactJsxNode.tsx:

import { useEffect } from 'hono/jsx'
import { render } from 'hono/jsx/dom'
import { v4 as uuidv4 } from 'uuid'

export function mountedReactJsxNode (
  jsxNode: JSX.Element  // shall come from island or other "browser-time" component
) {
  const mountPointId = uuidv4()

  console.log('starting a react-like component')

  useEffect(() => {
    console.log('mounting a react-like component')
    render(jsxNode, document.getElementById(mountPointId)!)
  }, [])

  return <span id={mountPointId} style={{display:'content'}} />
}

Demo

From: https://ui.shadcn.com/docs/components/tooltip
In islands:

import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger,} 
from '@/components/ui/tooltip'
import { mountedReactJsxNode } from '@/browser/mountReactJsxNode'

export default function TtDemo () {

  const tt = 
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger>Hover</TooltipTrigger>
        <TooltipContent>
          <p>Add to library</p>
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>

  return mountedReactJsxNode(tt)
}

(I still struggle with styles, but that must be my parallel tailwindcss v4-alpha experiments.)

@yusukebe
Copy link
Member

Hi @timurxyz

If you still think you want the feature/fix, can you create another issue?

@usualoma usualoma deleted the feat/compat-react-element branch May 19, 2024 09:12
@timurxyz
Copy link

timurxyz commented May 20, 2024

My experiment with getting tamagui to show at least a button in the faked react was blocked by the currently missing useInsertionEffect.

@usualoma
Copy link
Member Author

OK, I'll take a look.

tooltip, useInsertionEffect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants