Skip to content

Commit

Permalink
fix(react-server-dom-vite): fix action imported by client (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa authored Dec 19, 2024
1 parent e21f222 commit 161b4a5
Show file tree
Hide file tree
Showing 7 changed files with 103 additions and 8 deletions.
41 changes: 38 additions & 3 deletions react-server-dom-vite-example/e2e/basic.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type Page, test } from "@playwright/test";
import { type Page, expect, test } from "@playwright/test";
import { createEditor } from "./helper";

test("client reference", async ({ page }) => {
Expand All @@ -14,13 +14,13 @@ test("client reference", async ({ page }) => {
await page.getByText("Client counter: 0").click();
});

test("server reference @js", async ({ page }) => {
test("server reference in server @js", async ({ page }) => {
await testServerAction(page);
});

test.describe(() => {
test.use({ javaScriptEnabled: false });
test("server reference @nojs", async ({ page }) => {
test("server reference in server @nojs", async ({ page }) => {
await testServerAction(page);
});
});
Expand All @@ -42,6 +42,41 @@ async function testServerAction(page: Page) {
await page.getByText("Server counter: 0").click();
}

test("server reference in client @js", async ({ page }) => {
await testServerAction2(page, { js: true });
});

test.describe(() => {
test.use({ javaScriptEnabled: false });
test("server reference in client @nojs", async ({ page }) => {
await testServerAction2(page, { js: false });
});
});

async function testServerAction2(page: Page, options: { js: boolean }) {
await page.goto("/");
if (options.js) {
await page.getByText("[hydrated: 1]").click();
}
await page.locator('input[name="x"]').fill("2");
await page.locator('input[name="y"]').fill("3");
await page.locator('input[name="y"]').press("Enter");
await expect(page.getByTestId("calculator-answer")).toContainText("5");
await page.locator('input[name="x"]').fill("2");
await page.locator('input[name="y"]').fill("three");
await page.locator('input[name="y"]').press("Enter");
await expect(page.getByTestId("calculator-answer")).toContainText(
"(invalid input)",
);
if (options.js) {
await expect(page.locator('input[name="x"]')).toHaveValue("2");
await expect(page.locator('input[name="y"]')).toHaveValue("three");
} else {
await expect(page.locator('input[name="x"]')).toHaveValue("");
await expect(page.locator('input[name="y"]')).toHaveValue("");
}
}

test("client hmr @dev", async ({ page }) => {
await page.goto("/");
await page.getByText("[hydrated: 1]").click();
Expand Down
14 changes: 14 additions & 0 deletions react-server-dom-vite-example/src/app/action-by-client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"use server";

export async function add(_prev: unknown, formData: FormData) {
let x = formData.get("x");
let y = formData.get("y");
if (typeof x === "string" && typeof y === "string") {
let x2 = parseFloat(x);
let y2 = parseFloat(y);
if (!Number.isNaN(x2) && !Number.isNaN(y2)) {
return x2 + y2;
}
}
return "(invalid input)";
}
34 changes: 34 additions & 0 deletions react-server-dom-vite-example/src/app/client.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client";

import React from "react";
import { add } from "./action-by-client";

export function Counter() {
const [count, setCount] = React.useState(0);
Expand All @@ -26,3 +27,36 @@ function useHydrated() {
() => false,
);
}

export function Calculator() {
const [returnValue, formAction, _isPending] = React.useActionState(add, null);
const [x, setX] = React.useState("");
const [y, setY] = React.useState("");

return (
<form
action={formAction}
style={{ padding: "0.5rem" }}
data-testid="calculator"
>
<div>Calculator</div>
<div style={{ display: "flex", gap: "0.3rem" }}>
<input
name="x"
style={{ width: "2rem" }}
value={x}
onChange={(e) => setX(e.target.value)}
/>
+
<input
name="y"
style={{ width: "2rem" }}
value={y}
onChange={(e) => setY(e.target.value)}
/>
=<span data-testid="calculator-answer">{returnValue ?? "?"}</span>
</div>
<button hidden></button>
</form>
);
}
3 changes: 2 additions & 1 deletion react-server-dom-vite-example/src/app/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { changeCounter, getCounter } from "./action";
import { Counter, Hydrated } from "./client";
import { Calculator, Counter, Hydrated } from "./client";

export async function IndexPage() {
return (
Expand All @@ -22,6 +22,7 @@ export async function IndexPage() {
</button>
</div>
</form>
<Calculator />
</div>
);
}
1 change: 1 addition & 0 deletions react-server-dom-vite-example/src/entry.client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ async function main() {
setPayload(payload);
return payload.returnValue;
};
Object.assign(globalThis, { __callServer: callServer });

async function onNavigation() {
const url = new URL(window.location.href);
Expand Down
2 changes: 2 additions & 0 deletions react-server-dom-vite-example/src/entry.ssr.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export default async function handler(
const htmlStream = fromPipeableToWebReadable(
ReactDomServer.renderToPipeableStream(payload.root, {
bootstrapModules: ssrAssets.bootstrapModules,
// @ts-ignore no type?
formState: payload.formState,
}),
);

Expand Down
16 changes: 12 additions & 4 deletions react-server-dom-vite-example/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import {
defineConfig,
} from "vite";

// state for build orchestration
let browserManifest: Manifest;
let clientReferences: Record<string, string> = {};
let clientReferences: Record<string, string> = {}; // TODO: normalize id
let serverReferences: Record<string, string> = {};
let buildScan = false;

Expand Down Expand Up @@ -166,7 +167,6 @@ export default defineConfig({
],
builder: {
sharedPlugins: true,
sharedConfigBuild: true,
async buildApp(builder) {
buildScan = true;
await builder.build(builder.environments.rsc);
Expand Down Expand Up @@ -220,8 +220,8 @@ function vitePluginUseServer(): Plugin[] {
name: vitePluginUseServer.name,
transform(code, id) {
if (/^(("use server")|('use server'))/.test(code)) {
serverReferences[id] = id;
if (this.environment.name === "rsc") {
serverReferences[id] = id;
const matches = code.matchAll(/export async function (\w+)\(/g);
const result = [
code,
Expand All @@ -233,7 +233,15 @@ function vitePluginUseServer(): Plugin[] {
].join(";\n");
return { code: result, map: null };
} else {
// TODO
const matches = code.matchAll(/export async function (\w+)\(/g);
const result = [
`import $$ReactClient from "@jacob-ebey/react-server-dom-vite/client"`,
...[...matches].map(
([, name]) =>
`export const ${name} = $$ReactClient.createServerReference(${JSON.stringify(id + "#" + name)}, (...args) => __callServer(...args))`,
),
].join(";\n");
return { code: result, map: null };
}
}
},
Expand Down

0 comments on commit 161b4a5

Please sign in to comment.