From 3866b47741851fd147a188fde9b82f0273860060 Mon Sep 17 00:00:00 2001 From: paulaboks Date: Wed, 11 Nov 2026 16:56:47 -0300 Subject: [PATCH] Button partials with any methods --- docs/latest/advanced/partials.md | 94 ++++++ packages/fresh/src/runtime/client/partials.ts | 56 +++- packages/fresh/tests/partials_test.tsx | 282 ++++++++++++++++++ 3 files changed, 417 insertions(+), 15 deletions(-) diff --git a/docs/latest/advanced/partials.md b/docs/latest/advanced/partials.md index 1eee088c..e5070d34 100644 --- a/docs/latest/advanced/partials.md +++ b/docs/latest/advanced/partials.md @@ -219,6 +219,100 @@ Keep the following in mind when using other methods: - **CSRF protection:** The [CSRF middleware](/docs/plugins/csrf) treats these methods like `POST`, so they get the same checks. +### Sending requests from buttons + +A ` + + ))} + + + ); +} + +export default define.page(async () => { + const todos = await getTodos(); + return ( +
+ +
+ ); +}); +``` + +When `f-method` is set to something other than `GET`, the request body is +`multipart/form-data` and contains: + +- the button's own `name` and `value`, if it has a `name` +- every field of the surrounding form, if the button is a `type="button"` inside + a `` + +A `GET` button doesn't send any data. Like with forms, you can write the method +in any case. + +To ask for confirmation first, call `preventDefault()` on the click event in an +island. Fresh won't send the request when the event was cancelled. + +```tsx islands/DeleteButton.tsx +export function DeleteButton(props: { id: string }) { + return ( + + ); +} +``` + +[Loading indicators](#loading-indicators) work on these buttons too, and the +same advice about redirects applies. Buttons with `f-partial` rely on +JavaScript, so they do nothing if JavaScript isn't loaded. + ## Sending multiple Partials at the same time A neat aspect of partials in Fresh is that a response can return as many diff --git a/packages/fresh/src/runtime/client/partials.ts b/packages/fresh/src/runtime/client/partials.ts index b3daabd0..dc2c21ce 100644 --- a/packages/fresh/src/runtime/client/partials.ts +++ b/packages/fresh/src/runtime/client/partials.ts @@ -25,6 +25,7 @@ import { parse } from "../../jsonify/parse.ts"; import { INTERNAL_PREFIX, PARTIAL_SEARCH_PARAM } from "../../constants.ts"; export const PARTIAL_ATTR = "f-partial"; +export const METHOD_ATTR = "f-method"; class NoPartialsError extends Error {} @@ -112,6 +113,12 @@ function maybeReplaceHistory(nextUrl: URL) { } } +function normalizeMethod(raw: string | null | undefined): string { + const method = (raw || "get").toUpperCase(); + // Browsers submit invalid methods like HEAD as GET + return method === "HEAD" ? "GET" : method; +} + document.addEventListener("click", async (e) => { let el = e.target; if (el && (el instanceof HTMLElement || el instanceof SVGElement)) { @@ -178,20 +185,38 @@ document.addEventListener("click", async (e) => { } } else if ( el && el instanceof HTMLButtonElement && - (el.type !== "submit" || el.form === null) + (el.type !== "submit" || el.form === null) && + !e.defaultPrevented ) { const partial = el.getAttribute(PARTIAL_ATTR); + if (partial === null || !checkClientNavEnabled(el)) return; - // Check if the user opted out of client side navigation. - if (partial === null || !checkClientNavEnabled(el)) { - return; + const method = normalizeMethod(el.getAttribute(METHOD_ATTR)); + const partialUrl = new URL(partial, location.href); + + let init: RequestInit | undefined; + if (method !== "GET") { + const body = el.form ? new FormData(el.form) : new FormData(); + if (el.name) { + body.append(el.name, el.value); + } + init = { method, body }; } - const partialUrl = new URL( - partial, - location.href, - ); - await fetchPartials(partialUrl, partialUrl, false); + // deno-lint-ignore no-explicit-any + const indicator = (el as any)._freshIndicator; + if (indicator !== undefined) { + indicator.value = true; + } + try { + await withViewTransition(() => + fetchPartials(partialUrl, partialUrl, false, init) + ); + } finally { + if (indicator !== undefined) { + indicator.value = false; + } + } } } }); @@ -262,14 +287,15 @@ document.addEventListener("submit", async (e) => { return; } - const method = e.submitter?.getAttribute("formmethod")?.toLowerCase() || - el.getAttribute("method")?.toLowerCase() || "get"; + const method = normalizeMethod( + e.submitter?.getAttribute("formmethod") || el.getAttribute("method"), + ); - if (method === "dialog") { + if (method === "DIALOG") { return; } - const isCustomMethod = method !== "get" && method !== "post"; + const isCustomMethod = method !== "GET" && method !== "POST"; const hasExplicitPartial = isCustomMethod || e.submitter?.hasAttribute(PARTIAL_ATTR) || @@ -303,7 +329,7 @@ document.addEventListener("submit", async (e) => { let init: RequestInit | undefined; // GET method appends form data via url search params - if (method === "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); @@ -311,7 +337,7 @@ document.addEventListener("submit", async (e) => { } else { init = { body: new FormData(el, e.submitter), - method: method?.toUpperCase(), + method, }; } diff --git a/packages/fresh/tests/partials_test.tsx b/packages/fresh/tests/partials_test.tsx index 53271ee7..c209705f 100644 --- a/packages/fresh/tests/partials_test.tsx +++ b/packages/fresh/tests/partials_test.tsx @@ -2150,6 +2150,288 @@ Deno.test({ }, }); +Deno.test({ + name: "partials - submit form with formmethod HEAD is sent as GET", + fn: async () => { + const app = testApp() + .get("/partial", (ctx) => { + const name = ctx.url.searchParams.get("name"); + return ctx.render( + + +

done

+
+
, + ); + }) + .get("/", (ctx) => { + return ctx.render( + +
+ + + +

init

+
+ + +
+
, + ); + }); + + 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-GET-foo").wait(); + }); + }, +}); + +Deno.test({ + name: "partials - button f-method outside form", + fn: async () => { + const app = testApp() + .delete("/partial", renderMethodPartial) + .patch("/partial", renderMethodPartial) + .get("/", (ctx) => { + return ctx.render( + +
+ + + + +

init

+
+
+
, + ); + }); + + 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-bar").wait(); + + // Island state survives and the URL is left alone + await waitForText(page, ".output", "1"); + const pathname = await page.evaluate(() => window.location.pathname); + expect(pathname).toEqual("/"); + }); + }, +}); + +Deno.test({ + name: "partials - button f-method inside form sends form fields", + fn: async () => { + const app = testApp() + .put("/partial", async (ctx) => { + const data = await ctx.req.formData(); + const name = data.get("name"); + const extra = data.get("extra"); + return ctx.render( + + +

done

+
+
, + ); + }) + .get("/", (ctx) => { + return ctx.render( + +
+
+ + +

init

+
+ +
+
+
, + ); + }); + + 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-PUT-foo-bar").wait(); + }); + }, +}); + +Deno.test({ + name: "partials - button f-method cancelled with preventDefault", + fn: async () => { + let deleteCalls = 0; + const app = testApp() + .delete("/partial", (ctx) => { + deleteCalls++; + return renderMethodPartial(ctx); + }) + .get("/other", (ctx) => { + return ctx.render( + + +

other

+
+
, + ); + }) + .get("/", (ctx) => { + return ctx.render( + +
+ + + +

init

+
+
+
, + ); + }); + + await withBrowserApp(app, async (page, address) => { + await page.goto(address, { waitUntil: "load" }); + await page.locator(".init").wait(); + + await page.evaluate(() => { + document.querySelector(".delete")!.addEventListener( + "click", + (e) => e.preventDefault(), + ); + }); + + await page.locator(".delete").click(); + + // Trigger a second partial request after the cancelled one so we know + // the click handler has run before checking the DELETE handler. + await page.locator(".other-btn").click(); + await page.locator(".other").wait(); + + expect(deleteCalls).toEqual(0); + }); + }, +}); + +Deno.test({ + name: "partials - button f-method indicator", + fn: async () => { + const app = testApp() + .delete("/partial", renderMethodPartial) + .get("/", (ctx) => { + return ctx.render( + +
+ + +

init

+
+
+
, + ); + }); + + await withBrowserApp(app, async (page, address) => { + await page.goto(address, { waitUntil: "load" }); + await page.locator(".init").wait(); + + await page.evaluate(() => { + const btn = document.querySelector(".delete")!; + const indicator = { _wasTrue: false, _value: false }; + Object.defineProperty(indicator, "value", { + get() { + return this._value; + }, + set(v: boolean) { + this._value = v; + if (v) this._wasTrue = true; + }, + }); + // deno-lint-ignore no-explicit-any + (btn as any)._freshIndicator = indicator; + // deno-lint-ignore no-explicit-any + (window as any).__indicator = indicator; + }); + + await page.locator(".delete").click(); + await page.locator(".done-DELETE-foo").wait(); + + const result = await page.evaluate(() => { + // deno-lint-ignore no-explicit-any + const ind = (window as any).__indicator; + return { wasTrue: ind._wasTrue, currentValue: ind.value }; + }); + expect(result.wasTrue).toBe(true); + expect(result.currentValue).toBe(false); + }); + }, +}); + Deno.test({ name: "partials - submit form via external submitter", fn: async () => {