diff --git a/.changeset/gentle-windows-enjoy.md b/.changeset/gentle-windows-enjoy.md new file mode 100644 index 000000000000..6087cd3248ca --- /dev/null +++ b/.changeset/gentle-windows-enjoy.md @@ -0,0 +1,46 @@ +--- +"@astrojs/react": minor +"astro": minor +--- + +Adds two new functions `experimental_getActionState()` and `experimental_withState()` to support [the React 19 `useActionState()` hook](https://react.dev/reference/react/useActionState) when using Astro Actions. This introduces progressive enhancement when calling an Action with the `withState()` utility. + +This example calls a `like` action that accepts a `postId` and returns the number of likes. Pass this action to the `experimental_withState()` function to apply progressive enhancement info, and apply to `useActionState()` to track the result: + +```tsx +import { actions } from 'astro:actions'; +import { experimental_withState } from '@astrojs/react/actions'; + +export function Like({ postId }: { postId: string }) { + const [state, action, pending] = useActionState( + experimental_withState(actions.like), + 0, // initial likes + ); + + return ( +
+ + +
+ ); +} +``` + +You can also access the state stored by `useActionState()` from your action `handler`. Call `experimental_getActionState()` with the API context, and optionally apply a type to the result: + +```ts +import { defineAction, z } from 'astro:actions'; +import { experimental_getActionState } from '@astrojs/react/actions'; + +export const server = { + like: defineAction({ + input: z.object({ + postId: z.string(), + }), + handler: async ({ postId }, ctx) => { + const currentLikes = experimental_getActionState(ctx); + // write to database + return currentLikes + 1; + } + }) +} diff --git a/.changeset/twenty-cycles-bathe.md b/.changeset/twenty-cycles-bathe.md new file mode 100644 index 000000000000..208d4cf49962 --- /dev/null +++ b/.changeset/twenty-cycles-bathe.md @@ -0,0 +1,18 @@ +--- +"astro": minor +--- + +Adds compatibility for Astro Actions in the React 19 beta. Actions can be passed to a `form action` prop directly, and Astro will automatically add metadata for progressive enhancement. + +```tsx +import { actions } from 'astro:actions'; + +function Like() { + return ( +
+ {/* auto-inserts hidden input for progressive enhancement */} + +
+ ) +} +``` diff --git a/packages/astro/e2e/actions-react-19.test.js b/packages/astro/e2e/actions-react-19.test.js new file mode 100644 index 000000000000..5ce72a419acb --- /dev/null +++ b/packages/astro/e2e/actions-react-19.test.js @@ -0,0 +1,61 @@ +import { expect } from '@playwright/test'; +import { testFactory } from './test-utils.js'; + +const test = testFactory({ root: './fixtures/actions-react-19/' }); + +let devServer; + +test.beforeAll(async ({ astro }) => { + devServer = await astro.startDevServer(); +}); + +test.afterEach(async ({ astro }) => { + // Force database reset between tests + await astro.editFile('./db/seed.ts', (original) => original); +}); + +test.afterAll(async () => { + await devServer.stop(); +}); + +test.describe('Astro Actions - React 19', () => { + test('Like action - client pending state', async ({ page, astro }) => { + await page.goto(astro.resolveUrl('/blog/first-post/')); + + const likeButton = page.getByLabel('likes-client'); + await expect(likeButton).toBeVisible(); + await likeButton.click(); + await expect(likeButton, 'like button should be disabled when pending').toBeDisabled(); + await expect(likeButton).not.toBeDisabled({ timeout: 5000 }); + }); + + test('Like action - server progressive enhancement', async ({ page, astro }) => { + await page.goto(astro.resolveUrl('/blog/first-post/')); + + const likeButton = page.getByLabel('likes-server'); + await expect(likeButton, 'like button starts with 10 likes').toContainText('10'); + await likeButton.click(); + + await expect(likeButton, 'like button increments').toContainText('11'); + }); + + test('Like action - client useActionState', async ({ page, astro }) => { + await page.goto(astro.resolveUrl('/blog/first-post/')); + + const likeButton = page.getByLabel('likes-action-client'); + await expect(likeButton).toBeVisible(); + await likeButton.click(); + + await expect(likeButton, 'like button increments').toContainText('11'); + }); + + test('Like action - server useActionState progressive enhancement', async ({ page, astro }) => { + await page.goto(astro.resolveUrl('/blog/first-post/')); + + const likeButton = page.getByLabel('likes-action-server'); + await expect(likeButton, 'like button starts with 10 likes').toContainText('10'); + await likeButton.click(); + + await expect(likeButton, 'like button increments').toContainText('11'); + }); +}); diff --git a/packages/astro/e2e/fixtures/actions-blog/package.json b/packages/astro/e2e/fixtures/actions-blog/package.json index cf36f23266f5..4ce9ac525b42 100644 --- a/packages/astro/e2e/fixtures/actions-blog/package.json +++ b/packages/astro/e2e/fixtures/actions-blog/package.json @@ -1,5 +1,5 @@ { - "name": "@e2e/astro-actions-basics", + "name": "@e2e/actions-blog", "type": "module", "version": "0.0.1", "scripts": { diff --git a/packages/astro/e2e/fixtures/actions-blog/src/actions/index.ts b/packages/astro/e2e/fixtures/actions-blog/src/actions/index.ts index 036cc087fdca..0588f626c8a8 100644 --- a/packages/astro/e2e/fixtures/actions-blog/src/actions/index.ts +++ b/packages/astro/e2e/fixtures/actions-blog/src/actions/index.ts @@ -7,7 +7,7 @@ export const server = { like: defineAction({ input: z.object({ postId: z.string() }), handler: async ({ postId }) => { - await new Promise((r) => setTimeout(r, 200)); + await new Promise((r) => setTimeout(r, 1000)); const { likes } = await db .update(Likes) diff --git a/packages/astro/e2e/fixtures/actions-react-19/astro.config.mjs b/packages/astro/e2e/fixtures/actions-react-19/astro.config.mjs new file mode 100644 index 000000000000..acbed1768b3c --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/astro.config.mjs @@ -0,0 +1,17 @@ +import { defineConfig } from 'astro/config'; +import db from '@astrojs/db'; +import react from '@astrojs/react'; +import node from '@astrojs/node'; + +// https://astro.build/config +export default defineConfig({ + site: 'https://example.com', + integrations: [db(), react()], + output: 'hybrid', + adapter: node({ + mode: 'standalone', + }), + experimental: { + actions: true, + }, +}); diff --git a/packages/astro/e2e/fixtures/actions-react-19/db/config.ts b/packages/astro/e2e/fixtures/actions-react-19/db/config.ts new file mode 100644 index 000000000000..da005471e10c --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/db/config.ts @@ -0,0 +1,21 @@ +import { column, defineDb, defineTable } from "astro:db"; + +const Comment = defineTable({ + columns: { + postId: column.text(), + author: column.text(), + body: column.text(), + }, +}); + +const Likes = defineTable({ + columns: { + postId: column.text(), + likes: column.number(), + }, +}); + +// https://astro.build/db/config +export default defineDb({ + tables: { Comment, Likes }, +}); diff --git a/packages/astro/e2e/fixtures/actions-react-19/db/seed.ts b/packages/astro/e2e/fixtures/actions-react-19/db/seed.ts new file mode 100644 index 000000000000..11dc55f7fe00 --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/db/seed.ts @@ -0,0 +1,15 @@ +import { db, Likes, Comment } from "astro:db"; + +// https://astro.build/db/seed +export default async function seed() { + await db.insert(Likes).values({ + postId: "first-post.md", + likes: 10, + }); + + await db.insert(Comment).values({ + postId: "first-post.md", + author: "Alice", + body: "Great post!", + }); +} diff --git a/packages/astro/e2e/fixtures/actions-react-19/package.json b/packages/astro/e2e/fixtures/actions-react-19/package.json new file mode 100644 index 000000000000..28bbcde48586 --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/package.json @@ -0,0 +1,28 @@ +{ + "name": "@e2e/actions-react-19", + "type": "module", + "version": "0.0.1", + "scripts": { + "dev": "astro dev", + "start": "astro dev", + "build": "astro check && astro build", + "preview": "astro preview", + "astro": "astro" + }, + "dependencies": { + "@astrojs/check": "^0.6.0", + "@astrojs/db": "workspace:*", + "@astrojs/node": "workspace:*", + "@astrojs/react": "workspace:*", + "@types/react": "npm:types-react", + "@types/react-dom": "npm:types-react-dom", + "astro": "workspace:*", + "react": "19.0.0-beta-26f2496093-20240514", + "react-dom": "19.0.0-beta-26f2496093-20240514", + "typescript": "^5.4.5" + }, + "overrides": { + "@types/react": "npm:types-react", + "@types/react-dom": "npm:types-react-dom" + } +} diff --git a/packages/astro/e2e/fixtures/actions-react-19/src/actions/index.ts b/packages/astro/e2e/fixtures/actions-react-19/src/actions/index.ts new file mode 100644 index 000000000000..9cb867603add --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/src/actions/index.ts @@ -0,0 +1,47 @@ +import { db, Likes, eq, sql } from 'astro:db'; +import { defineAction, getApiContext, z } from 'astro:actions'; +import { experimental_getActionState } from '@astrojs/react/actions'; + +export const server = { + blog: { + like: defineAction({ + accept: 'form', + input: z.object({ postId: z.string() }), + handler: async ({ postId }) => { + await new Promise((r) => setTimeout(r, 1000)); + + const { likes } = await db + .update(Likes) + .set({ + likes: sql`likes + 1`, + }) + .where(eq(Likes.postId, postId)) + .returning() + .get(); + + return likes; + }, + }), + likeWithActionState: defineAction({ + accept: 'form', + input: z.object({ postId: z.string() }), + handler: async ({ postId }) => { + await new Promise((r) => setTimeout(r, 200)); + + const context = getApiContext(); + const state = await experimental_getActionState(context); + + const { likes } = await db + .update(Likes) + .set({ + likes: state + 1, + }) + .where(eq(Likes.postId, postId)) + .returning() + .get(); + + return likes; + }, + }), + }, +}; diff --git a/packages/astro/e2e/fixtures/actions-react-19/src/components/BaseHead.astro b/packages/astro/e2e/fixtures/actions-react-19/src/components/BaseHead.astro new file mode 100644 index 000000000000..5a2114003d5d --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/src/components/BaseHead.astro @@ -0,0 +1,43 @@ +--- +// Import the global.css file here so that it is included on +// all pages through the use of the component. +import '../styles/global.css'; + +interface Props { + title: string; + description: string; + image?: string; +} + +const canonicalURL = new URL(Astro.url.pathname, Astro.site); + +const { title, description, image = '/blog-placeholder-1.jpg' } = Astro.props; +--- + + + + + + + + + + + +{title} + + + + + + + + + + + + + + + + diff --git a/packages/astro/e2e/fixtures/actions-react-19/src/components/Footer.astro b/packages/astro/e2e/fixtures/actions-react-19/src/components/Footer.astro new file mode 100644 index 000000000000..96c2fce91208 --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/src/components/Footer.astro @@ -0,0 +1,62 @@ +--- +const today = new Date(); +--- + + + diff --git a/packages/astro/e2e/fixtures/actions-react-19/src/components/FormattedDate.astro b/packages/astro/e2e/fixtures/actions-react-19/src/components/FormattedDate.astro new file mode 100644 index 000000000000..1bcce73a2b67 --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/src/components/FormattedDate.astro @@ -0,0 +1,17 @@ +--- +interface Props { + date: Date; +} + +const { date } = Astro.props; +--- + + diff --git a/packages/astro/e2e/fixtures/actions-react-19/src/components/Header.astro b/packages/astro/e2e/fixtures/actions-react-19/src/components/Header.astro new file mode 100644 index 000000000000..71b8cdc55c58 --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/src/components/Header.astro @@ -0,0 +1,83 @@ +--- +import HeaderLink from './HeaderLink.astro'; +import { SITE_TITLE } from '../consts'; +--- + +
+ +
+ diff --git a/packages/astro/e2e/fixtures/actions-react-19/src/components/HeaderLink.astro b/packages/astro/e2e/fixtures/actions-react-19/src/components/HeaderLink.astro new file mode 100644 index 000000000000..bb600fb65ac3 --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/src/components/HeaderLink.astro @@ -0,0 +1,25 @@ +--- +import type { HTMLAttributes } from 'astro/types'; + +type Props = HTMLAttributes<'a'>; + +const { href, class: className, ...props } = Astro.props; + +const { pathname } = Astro.url; +const subpath = pathname.match(/[^\/]+/g); +const isActive = href === pathname || href === '/' + subpath?.[0]; +--- + + + + + diff --git a/packages/astro/e2e/fixtures/actions-react-19/src/components/Like.tsx b/packages/astro/e2e/fixtures/actions-react-19/src/components/Like.tsx new file mode 100644 index 000000000000..0d2dde00916e --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/src/components/Like.tsx @@ -0,0 +1,38 @@ +import { actions } from 'astro:actions'; +import { useActionState } from 'react'; +import { useFormStatus } from 'react-dom'; +import { experimental_withState } from '@astrojs/react/actions'; + +export function Like({ postId, label, likes }: { postId: string; label: string; likes: number }) { + return ( +
+ +
+ ) +} diff --git a/packages/astro/e2e/fixtures/actions-react-19/src/consts.ts b/packages/astro/e2e/fixtures/actions-react-19/src/consts.ts new file mode 100644 index 000000000000..0df8a61f4cf7 --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/src/consts.ts @@ -0,0 +1,5 @@ +// Place any global data in this file. +// You can import this data from anywhere in your site by using the `import` keyword. + +export const SITE_TITLE = 'Astro Blog'; +export const SITE_DESCRIPTION = 'Welcome to my website!'; diff --git a/packages/astro/e2e/fixtures/actions-react-19/src/content/blog/first-post.md b/packages/astro/e2e/fixtures/actions-react-19/src/content/blog/first-post.md new file mode 100644 index 000000000000..ee51f1541097 --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/src/content/blog/first-post.md @@ -0,0 +1,15 @@ +--- +title: 'First post' +description: 'Lorem ipsum dolor sit amet' +pubDate: 'Jul 08 2022' +--- + +Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Vitae ultricies leo integer malesuada nunc vel risus commodo viverra. Adipiscing enim eu turpis egestas pretium. Euismod elementum nisi quis eleifend quam adipiscing. In hac habitasse platea dictumst vestibulum. Sagittis purus sit amet volutpat. Netus et malesuada fames ac turpis egestas. Eget magna fermentum iaculis eu non diam phasellus vestibulum lorem. Varius sit amet mattis vulputate enim. Habitasse platea dictumst quisque sagittis. Integer quis auctor elit sed vulputate mi. Dictumst quisque sagittis purus sit amet. + +Morbi tristique senectus et netus. Id semper risus in hendrerit gravida rutrum quisque non tellus. Habitasse platea dictumst quisque sagittis purus sit amet. Tellus molestie nunc non blandit massa. Cursus vitae congue mauris rhoncus. Accumsan tortor posuere ac ut. Fringilla urna porttitor rhoncus dolor. Elit ullamcorper dignissim cras tincidunt lobortis. In cursus turpis massa tincidunt dui ut ornare lectus. Integer feugiat scelerisque varius morbi enim nunc. Bibendum neque egestas congue quisque egestas diam. Cras ornare arcu dui vivamus arcu felis bibendum. Dignissim suspendisse in est ante in nibh mauris. Sed tempus urna et pharetra pharetra massa massa ultricies mi. + +Mollis nunc sed id semper risus in. Convallis a cras semper auctor neque. Diam sit amet nisl suscipit. Lacus viverra vitae congue eu consequat ac felis donec. Egestas integer eget aliquet nibh praesent tristique magna sit amet. Eget magna fermentum iaculis eu non diam. In vitae turpis massa sed elementum. Tristique et egestas quis ipsum suspendisse ultrices. Eget lorem dolor sed viverra ipsum. Vel turpis nunc eget lorem dolor sed viverra. Posuere ac ut consequat semper viverra nam. Laoreet suspendisse interdum consectetur libero id faucibus. Diam phasellus vestibulum lorem sed risus ultricies tristique. Rhoncus dolor purus non enim praesent elementum facilisis. Ultrices tincidunt arcu non sodales neque. Tempus egestas sed sed risus pretium quam vulputate. Viverra suspendisse potenti nullam ac tortor vitae purus faucibus ornare. Fringilla urna porttitor rhoncus dolor purus non. Amet dictum sit amet justo donec enim. + +Mattis ullamcorper velit sed ullamcorper morbi tincidunt. Tortor posuere ac ut consequat semper viverra. Tellus mauris a diam maecenas sed enim ut sem viverra. Venenatis urna cursus eget nunc scelerisque viverra mauris in. Arcu ac tortor dignissim convallis aenean et tortor at. Curabitur gravida arcu ac tortor dignissim convallis aenean et tortor. Egestas tellus rutrum tellus pellentesque eu. Fusce ut placerat orci nulla pellentesque dignissim enim sit amet. Ut enim blandit volutpat maecenas volutpat blandit aliquam etiam. Id donec ultrices tincidunt arcu. Id cursus metus aliquam eleifend mi. + +Tempus quam pellentesque nec nam aliquam sem. Risus at ultrices mi tempus imperdiet. Id porta nibh venenatis cras sed felis eget velit. Ipsum a arcu cursus vitae. Facilisis magna etiam tempor orci eu lobortis elementum. Tincidunt dui ut ornare lectus sit. Quisque non tellus orci ac. Blandit libero volutpat sed cras. Nec tincidunt praesent semper feugiat nibh sed pulvinar proin gravida. Egestas integer eget aliquet nibh praesent tristique magna. diff --git a/packages/astro/e2e/fixtures/actions-react-19/src/content/config.ts b/packages/astro/e2e/fixtures/actions-react-19/src/content/config.ts new file mode 100644 index 000000000000..667a31cc7391 --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/src/content/config.ts @@ -0,0 +1,16 @@ +import { defineCollection, z } from 'astro:content'; + +const blog = defineCollection({ + type: 'content', + // Type-check frontmatter using a schema + schema: z.object({ + title: z.string(), + description: z.string(), + // Transform string to Date object + pubDate: z.coerce.date(), + updatedDate: z.coerce.date().optional(), + heroImage: z.string().optional(), + }), +}); + +export const collections = { blog }; diff --git a/packages/astro/e2e/fixtures/actions-react-19/src/layouts/BlogPost.astro b/packages/astro/e2e/fixtures/actions-react-19/src/layouts/BlogPost.astro new file mode 100644 index 000000000000..e67b2b30f859 --- /dev/null +++ b/packages/astro/e2e/fixtures/actions-react-19/src/layouts/BlogPost.astro @@ -0,0 +1,85 @@ +--- +import type { CollectionEntry } from 'astro:content'; +import BaseHead from '../components/BaseHead.astro'; +import Header from '../components/Header.astro'; +import Footer from '../components/Footer.astro'; +import FormattedDate from '../components/FormattedDate.astro'; + +type Props = CollectionEntry<'blog'>['data']; + +const { title, description, pubDate, updatedDate, heroImage } = Astro.props; +--- + + + + + + + + +
+
+
+
+ {heroImage && } +
+
+
+
+ + { + updatedDate && ( +
+ Last updated on +
+ ) + } +
+

{title}

+
+
+ +
+
+
+