Make partials support any http method :3
This commit is contained in:
@@ -102,6 +102,12 @@ export default define.page<typeof handler>(function Upload(props) {
|
||||
});
|
||||
```
|
||||
|
||||
## Other HTTP methods
|
||||
|
||||
Browsers can only submit forms as `GET` or `POST`. To submit a form as `DELETE`,
|
||||
`PATCH` or `PUT` and update part of the page with the response, use
|
||||
[Partials](/docs/advanced/partials#using-other-http-methods).
|
||||
|
||||
## A note of caution
|
||||
|
||||
These examples are simplified to demonstrate how Deno and Fresh handle HTTP
|
||||
|
||||
@@ -145,6 +145,80 @@ two links and _only_ load the content rendered by our optimized partial route.
|
||||
> Currently, `f-partial` is scoped to `<a>`, `<button>` and `<form>` elements.
|
||||
> This might be extended to more elements in the future.
|
||||
|
||||
## Submitting forms
|
||||
|
||||
Forms inside an `f-client-nav` element can be submitted as a partial request.
|
||||
For `GET` and `POST` forms, this happens when the form opts in through one of
|
||||
these attributes:
|
||||
|
||||
- an `action` attribute on the `<form>`
|
||||
- an `f-partial` attribute on the `<form>`
|
||||
- a `formaction` or `f-partial` attribute on the submit button
|
||||
|
||||
A `GET` form sends its fields as URL search parameters. Every other method sends
|
||||
them as a `multipart/form-data` request body. If the submit button has a `name`,
|
||||
its value is included too.
|
||||
|
||||
A `GET` or `POST` form without any of these attributes is submitted the normal
|
||||
way, with a full page load. Forms with `method="dialog"` are never intercepted.
|
||||
|
||||
### Using other HTTP methods
|
||||
|
||||
Browsers can only submit forms as `GET` or `POST`. Fresh lets forms inside
|
||||
`f-client-nav` use any other method too, like `DELETE`, `PATCH` or `PUT`. You
|
||||
set it with the `method` attribute on the form or the `formmethod` attribute on
|
||||
a submit button, and Fresh sends the request with `fetch()`.
|
||||
|
||||
```tsx routes/index.tsx
|
||||
import { Partial } from "sweet/runtime";
|
||||
import { define } from "../utils.ts";
|
||||
|
||||
export const handler = define.handlers({
|
||||
POST(ctx) {
|
||||
return ctx.render(<Partial name="body">post!</Partial>);
|
||||
},
|
||||
DELETE(ctx) {
|
||||
return ctx.render(<Partial name="body">delete!</Partial>);
|
||||
},
|
||||
PATCH(ctx) {
|
||||
return ctx.render(<Partial name="body">patch!</Partial>);
|
||||
},
|
||||
});
|
||||
|
||||
export default define.page(function Home() {
|
||||
return (
|
||||
<div f-client-nav>
|
||||
<form action="/">
|
||||
<button type="submit" formmethod="POST">post</button>
|
||||
<button type="submit" formmethod="DELETE">delete</button>
|
||||
<button type="submit" formmethod="PATCH">patch</button>
|
||||
</form>
|
||||
<Partial name="body">nothing submitted yet</Partial>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
A form that uses another method is always submitted as a partial request. It
|
||||
doesn't need an `action` or `f-partial` attribute. Without them, the request
|
||||
goes to the current page. You can write the method in any case: Fresh converts
|
||||
it to uppercase, so `formmethod="patch"` reaches your `PATCH` handler.
|
||||
|
||||
The `POST` button above only submits as a partial because the form has an
|
||||
`action` attribute. Without it, `POST` would cause a full page load, while the
|
||||
`DELETE` and `PATCH` buttons would still work as partials.
|
||||
|
||||
Keep the following in mind when using other methods:
|
||||
|
||||
- **Redirects:** To redirect after a `DELETE`, `PATCH` or `PUT`, respond with
|
||||
status `303 See Other`. With a `301` or `302`, `fetch()` sends the request to
|
||||
the new URL again with the same method.
|
||||
- **Without JavaScript:** If JavaScript isn't loaded, the browser doesn't
|
||||
recognize the method and submits the form as a `GET` request instead, with the
|
||||
fields in the URL. If a form has to work without JavaScript, use `POST`.
|
||||
- **CSRF protection:** The [CSRF middleware](/docs/plugins/csrf) treats these
|
||||
methods like `POST`, so they get the same checks.
|
||||
|
||||
## Sending multiple Partials at the same time
|
||||
|
||||
A neat aspect of partials in Fresh is that a response can return as many
|
||||
|
||||
@@ -262,14 +262,17 @@ document.addEventListener("submit", async (e) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const lowerMethod =
|
||||
e.submitter?.getAttribute("formmethod")?.toLowerCase() ??
|
||||
el.method.toLowerCase();
|
||||
if (lowerMethod !== "get" && lowerMethod !== "post") {
|
||||
const method = e.submitter?.getAttribute("formmethod")?.toLowerCase() ||
|
||||
el.getAttribute("method")?.toLowerCase() || "get";
|
||||
|
||||
if (method === "dialog") {
|
||||
return;
|
||||
}
|
||||
|
||||
const hasExplicitPartial = e.submitter?.hasAttribute(PARTIAL_ATTR) ||
|
||||
const isCustomMethod = method !== "get" && method !== "post";
|
||||
|
||||
const hasExplicitPartial = isCustomMethod ||
|
||||
e.submitter?.hasAttribute(PARTIAL_ATTR) ||
|
||||
e.submitter?.hasAttribute("formaction") ||
|
||||
el.hasAttribute(PARTIAL_ATTR) ||
|
||||
el.hasAttribute("action");
|
||||
@@ -300,13 +303,16 @@ document.addEventListener("submit", async (e) => {
|
||||
let init: RequestInit | undefined;
|
||||
|
||||
// GET method appends form data via url search params
|
||||
if (lowerMethod === "get") {
|
||||
if (method === "get") {
|
||||
// TODO: Looks like constructor type for URLSearchParam is wrong
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const qs = new URLSearchParams(new FormData(el, e.submitter) as any);
|
||||
qs.forEach((value, key) => partialUrl.searchParams.append(key, value));
|
||||
} else {
|
||||
init = { body: new FormData(el, e.submitter), method: lowerMethod };
|
||||
init = {
|
||||
body: new FormData(el, e.submitter),
|
||||
method: method?.toUpperCase(),
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { App, staticFiles } from "sweet";
|
||||
import { App, type Context, staticFiles } from "sweet";
|
||||
import { Partial } from "sweet/runtime";
|
||||
import {
|
||||
ALL_ISLAND_DIR,
|
||||
@@ -1955,6 +1955,201 @@ Deno.test({
|
||||
},
|
||||
});
|
||||
|
||||
async function renderMethodPartial(ctx: Context<unknown>) {
|
||||
const data = await ctx.req.formData();
|
||||
const name = data.get("name");
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<Partial name="foo">
|
||||
<p class={`done-${ctx.req.method}-${name}`}>done</p>
|
||||
</Partial>
|
||||
</Doc>,
|
||||
);
|
||||
}
|
||||
|
||||
Deno.test({
|
||||
name: "partials - submit form with formmethod DELETE, PATCH and PUT",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.delete("/", renderMethodPartial)
|
||||
.patch("/", renderMethodPartial)
|
||||
.put("/", renderMethodPartial)
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<form>
|
||||
<input name="name" value="foo" />
|
||||
<SelfCounter />
|
||||
<button type="submit" class="delete" formmethod="DELETE">
|
||||
delete
|
||||
</button>
|
||||
<button type="submit" class="patch" formmethod="PATCH">
|
||||
patch
|
||||
</button>
|
||||
<button type="submit" class="put" formmethod="put">
|
||||
put
|
||||
</button>
|
||||
</form>
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".ready").wait();
|
||||
|
||||
await page.locator(".increment").click();
|
||||
await waitForText(page, ".output", "1");
|
||||
|
||||
await page.locator(".delete").click();
|
||||
await page.locator(".done-DELETE-foo").wait();
|
||||
|
||||
await page.locator(".patch").click();
|
||||
await page.locator(".done-PATCH-foo").wait();
|
||||
|
||||
await page.locator(".put").click();
|
||||
await page.locator(".done-PUT-foo").wait();
|
||||
|
||||
// Island state survives, so no full page reload happened
|
||||
await waitForText(page, ".output", "1");
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - submit form with custom method on form element",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.patch("/", renderMethodPartial)
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<form method="patch">
|
||||
<input name="name" value="foo" />
|
||||
<SelfCounter />
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
<button type="submit" class="update">update</button>
|
||||
</form>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".ready").wait();
|
||||
|
||||
await page.locator(".increment").click();
|
||||
await waitForText(page, ".output", "1");
|
||||
|
||||
await page.locator(".update").click();
|
||||
await page.locator(".done-PATCH-foo").wait();
|
||||
await waitForText(page, ".output", "1");
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - form without method inside f-client-nav not intercepted",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.get("/", (ctx) => {
|
||||
if (ctx.url.searchParams.has("name")) {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<p class="submitted">form submitted normally</p>
|
||||
</Doc>,
|
||||
);
|
||||
}
|
||||
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<form>
|
||||
<input name="name" value="foo" />
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
<button type="submit" class="update">update</button>
|
||||
</form>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".init").wait();
|
||||
|
||||
await Promise.all([
|
||||
page.waitForNavigation(),
|
||||
page.locator(".update").click(),
|
||||
]);
|
||||
await page.locator(".submitted").wait();
|
||||
|
||||
const search = await page.evaluate(() => window.location.search);
|
||||
expect(search).toEqual("?name=foo");
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - submit form DELETE with 303 redirect",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.get("/done", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<Partial name="foo">
|
||||
<h1 class="done">deleted</h1>
|
||||
</Partial>
|
||||
</Doc>,
|
||||
);
|
||||
})
|
||||
.delete("/", () => {
|
||||
return new Response(null, {
|
||||
status: 303,
|
||||
headers: { Location: "/done" },
|
||||
});
|
||||
})
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<form>
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
<button type="submit" class="update" formmethod="DELETE">
|
||||
delete
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".init").wait();
|
||||
|
||||
await page.locator(".update").click();
|
||||
await page.locator(".done").wait();
|
||||
|
||||
const pathname = await page.evaluate(() => window.location.pathname);
|
||||
expect(pathname).toEqual("/done");
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - submit form via external submitter",
|
||||
fn: async () => {
|
||||
|
||||
Reference in New Issue
Block a user