Skip to content
Merged
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
4 changes: 2 additions & 2 deletions packages/plugin-rsc/e2e/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ export const testNoJs = test.extend({
javaScriptEnabled: ({}, use) => use(false),
})

export async function waitForHydration(page: Page) {
export async function waitForHydration(page: Page, locator: string = 'body') {
await expect
.poll(
() =>
page
.locator('body')
.locator(locator)
.evaluate(
(el) =>
el &&
Expand Down
35 changes: 33 additions & 2 deletions packages/plugin-rsc/e2e/starter.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { expect, test } from '@playwright/test'
import { type Fixture, useFixture } from './fixture'
import { expectNoReload, testNoJs, waitForHydration } from './helper'
import {
expectNoReload,
testNoJs,
waitForHydration as waitForHydration_,
} from './helper'
import path from 'node:path'
import fs from 'node:fs'

test.describe('dev-default', () => {
const f = useFixture({ root: 'examples/starter', mode: 'dev' })
Expand All @@ -22,7 +28,24 @@ test.describe('build-cloudflare', () => {
defineTest(f)
})

function defineTest(f: Fixture) {
test.describe('dev-no-ssr', () => {
const f = useFixture({ root: 'examples/no-ssr', mode: 'dev' })
defineTest(f, 'no-ssr')
})

test.describe('build-no-ssr', () => {
const f = useFixture({ root: 'examples/no-ssr', mode: 'build' })
defineTest(f, 'no-ssr')

test('no ssr build', () => {
expect(fs.existsSync(path.join(f.root, 'dist/ssr'))).toBe(false)
})
})

function defineTest(f: Fixture, variant?: 'no-ssr') {
const waitForHydration: typeof waitForHydration_ = (page) =>
waitForHydration_(page, variant === 'no-ssr' ? '#root' : 'body')

test('basic', async ({ page }) => {
await page.goto(f.url())
await waitForHydration(page)
Expand All @@ -48,6 +71,8 @@ function defineTest(f: Fixture) {
})

testNoJs('server action @nojs', async ({ page }) => {
test.skip(variant === 'no-ssr')

await page.goto(f.url())
await page.getByRole('button', { name: 'Server Counter: 1' }).click()
await expect(
Expand All @@ -71,6 +96,12 @@ function defineTest(f: Fixture) {
page.getByRole('button', { name: 'Client [edit] Counter: 1' }),
).toBeVisible()

if (variant === 'no-ssr') {
editor.reset()
await page.getByRole('button', { name: 'Client Counter: 1' }).click()
return
}

// check next ssr is also updated
const res = await page.goto(f.url())
expect(await res?.text()).toContain('Client [edit] Counter')
Expand Down
1 change: 1 addition & 0 deletions packages/plugin-rsc/examples/no-ssr/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[examples/starter](https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-rsc/examples/starter) without SSR environment
12 changes: 12 additions & 0 deletions packages/plugin-rsc/examples/no-ssr/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<script async type="module" src="/src/framework/entry.browser.tsx"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
23 changes: 23 additions & 0 deletions packages/plugin-rsc/examples/no-ssr/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "@vitejs/plugin-rsc-examples-no-ssr",
"version": "0.0.0",
"private": true,
"license": "MIT",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@vitejs/plugin-rsc": "latest",
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "latest",
"vite": "^7.0.2"
}
}
1 change: 1 addition & 0 deletions packages/plugin-rsc/examples/no-ssr/public/vite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 11 additions & 0 deletions packages/plugin-rsc/examples/no-ssr/src/action.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use server'

let serverCounter = 0

export async function getServerCounter() {
return serverCounter
}

export async function updateServerCounter(change: number) {
serverCounter += change
}
1 change: 1 addition & 0 deletions packages/plugin-rsc/examples/no-ssr/src/assets/react.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 13 additions & 0 deletions packages/plugin-rsc/examples/no-ssr/src/client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use client'

import React from 'react'

export function ClientCounter() {
const [count, setCount] = React.useState(0)

return (
<button onClick={() => setCount((count) => count + 1)}>
Client Counter: {count}
</button>
)
}
122 changes: 122 additions & 0 deletions packages/plugin-rsc/examples/no-ssr/src/framework/entry.browser.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import * as ReactClient from '@vitejs/plugin-rsc/browser'
import React from 'react'
import * as ReactDOMClient from 'react-dom/client'
import type { RscPayload } from './entry.rsc'

async function main() {
// stash `setPayload` function to trigger re-rendering
// from outside of `BrowserRoot` component (e.g. server function call, navigation, hmr)
let setPayload: (v: RscPayload) => void

const initialPayload = await ReactClient.createFromFetch<RscPayload>(
fetch(window.location.href),
)

// browser root component to (re-)render RSC payload as state
function BrowserRoot() {
const [payload, setPayload_] = React.useState(initialPayload)

React.useEffect(() => {
setPayload = (v) => React.startTransition(() => setPayload_(v))
}, [setPayload_])

// re-fetch/render on client side navigation
React.useEffect(() => {
return listenNavigation(() => fetchRscPayload())
}, [])

return payload.root
}

// re-fetch RSC and trigger re-rendering
async function fetchRscPayload() {
const payload = await ReactClient.createFromFetch<RscPayload>(
fetch(window.location.href),
)
setPayload(payload)
}

// register a handler which will be internally called by React
// on server function request after hydration.
ReactClient.setServerCallback(async (id, args) => {
const url = new URL(window.location.href)
const temporaryReferences = ReactClient.createTemporaryReferenceSet()
const payload = await ReactClient.createFromFetch<RscPayload>(
fetch(url, {
method: 'POST',
body: await ReactClient.encodeReply(args, { temporaryReferences }),
headers: {
'x-rsc-action': id,
},
}),
{ temporaryReferences },
)
setPayload(payload)
return payload.returnValue
})

// hydration
const browserRoot = (
<React.StrictMode>
<BrowserRoot />
</React.StrictMode>
)
ReactDOMClient.createRoot(document.body).render(browserRoot)

// implement server HMR by trigering re-fetch/render of RSC upon server code change
if (import.meta.hot) {
import.meta.hot.on('rsc:update', () => {
fetchRscPayload()
})
}
}

// a little helper to setup events interception for client side navigation
function listenNavigation(onNavigation: () => void) {
window.addEventListener('popstate', onNavigation)

const oldPushState = window.history.pushState
window.history.pushState = function (...args) {
const res = oldPushState.apply(this, args)
onNavigation()
return res
}

const oldReplaceState = window.history.replaceState
window.history.replaceState = function (...args) {
const res = oldReplaceState.apply(this, args)
onNavigation()
return res
}

function onClick(e: MouseEvent) {
let link = (e.target as Element).closest('a')
if (
link &&
link instanceof HTMLAnchorElement &&
link.href &&
(!link.target || link.target === '_self') &&
link.origin === location.origin &&
!link.hasAttribute('download') &&
e.button === 0 && // left clicks only
!e.metaKey && // open in new tab (mac)
!e.ctrlKey && // open in new tab (windows)
!e.altKey && // download
!e.shiftKey &&
!e.defaultPrevented
) {
e.preventDefault()
history.pushState(null, '', link.href)
}
}
document.addEventListener('click', onClick)

return () => {
document.removeEventListener('click', onClick)
window.removeEventListener('popstate', onNavigation)
window.history.pushState = oldPushState
window.history.replaceState = oldReplaceState
}
}

main()
51 changes: 51 additions & 0 deletions packages/plugin-rsc/examples/no-ssr/src/framework/entry.rsc.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import * as ReactServer from '@vitejs/plugin-rsc/rsc'
import type { ReactFormState } from 'react-dom/client'
import { Root } from '../root.tsx'

export type RscPayload = {
root: React.ReactNode
returnValue?: unknown
formState?: ReactFormState
}

export default async function handler(request: Request): Promise<Response> {
const isAction = request.method === 'POST'
let returnValue: unknown | undefined
let formState: ReactFormState | undefined
let temporaryReferences: unknown | undefined
if (isAction) {
const actionId = request.headers.get('x-rsc-action')
if (actionId) {
const contentType = request.headers.get('content-type')
const body = contentType?.startsWith('multipart/form-data')
? await request.formData()
: await request.text()
temporaryReferences = ReactServer.createTemporaryReferenceSet()
const args = await ReactServer.decodeReply(body, { temporaryReferences })
const action = await ReactServer.loadServerAction(actionId)
returnValue = await action.apply(null, args)
} else {
const formData = await request.formData()
const decodedAction = await ReactServer.decodeAction(formData)
const result = await decodedAction()
formState = await ReactServer.decodeFormState(result, formData)
}
}

const rscStream = ReactServer.renderToReadableStream<RscPayload>({
root: <Root />,
returnValue,
formState,
})

return new Response(rscStream, {
headers: {
'content-type': 'text/x-component;charset=utf-8',
vary: 'accept',
},
})
}

if (import.meta.hot) {
import.meta.hot.accept()
}
Loading
Loading