Compare commits

...
5 Commits
Author SHA1 Message Date
paula 6e37c2aea7 Bump version 2026-11-12 14:58:28 -03:00
paula 7595cf396f Don't redirect to https if the request didn't come from https 2026-11-12 14:57:38 -03:00
paula 0b6be21d14 Bump version 2026-11-11 17:17:12 -03:00
paula 8c552d05d1 f-update-url 2026-11-11 17:16:21 -03:00
paula 3866b47741 Button partials with any methods 2026-11-11 16:56:47 -03:00
10 changed files with 580 additions and 26 deletions
+122 -1
View File
@@ -210,15 +210,136 @@ The `POST` button above only submits as a partial because the form has an
Keep the following in mind when using other methods: Keep the following in mind when using other methods:
- **The URL doesn't change:** Unlike `GET` and `POST`, these methods leave the
URL in the address bar as it is. See
[Controlling the URL](#controlling-the-url).
- **Redirects:** To redirect after a `DELETE`, `PATCH` or `PUT`, respond with - **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 status `303 See Other`. With a `301` or `302`, `fetch()` sends the request to
the new URL again with the same method. the new URL again with the same method. The partials from the redirect target
are applied, but the URL only changes to it if you set `f-update-url="true"`.
- **Without JavaScript:** If JavaScript isn't loaded, the browser doesn't - **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 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`. fields in the URL. If a form has to work without JavaScript, use `POST`.
- **CSRF protection:** The [CSRF middleware](/docs/plugins/csrf) treats these - **CSRF protection:** The [CSRF middleware](/docs/plugins/csrf) treats these
methods like `POST`, so they get the same checks. methods like `POST`, so they get the same checks.
### Controlling the URL
When a `GET` or `POST` form is submitted as a partial, Fresh replaces the URL in
the address bar with the form's action URL, or with the URL it was redirected
to. Other methods leave the URL as it is, so a `DELETE` to `/items/1` doesn't
leave `/items/1` in the address bar.
To change this, set `f-update-url` on the form or on the submit button. The
button's value wins if both have one.
- `f-update-url="true"` updates the URL, for any method
- `f-update-url="false"` leaves the URL as it is, for any method
```tsx
<form action="/search" f-update-url="false">
<input name="q" />
<button type="submit">Search</button>
</form>;
```
> [info]: Use the strings `"true"` and `"false"`. Preact leaves the attribute
> out when you pass the boolean `{false}`, so Fresh falls back to the default.
### Sending requests from buttons
A `<button>` with an `f-partial` attribute also triggers a partial request on
its own. This applies to buttons outside a form and to buttons with
`type="button"`. Submit buttons inside a form submit the form instead, as
described above. By default, the button sends a `GET` request to the `f-partial`
URL and applies the partials in the response. Unlike links, buttons don't change
the URL in the address bar.
To use another method, add an `f-method` attribute. This is handy for actions
like deleting an item from a list, where wrapping each button in a `<form>`
would be awkward.
```tsx routes/todos.tsx
import { Partial } from "sweet/runtime";
import { define } from "../utils.ts";
export const handler = define.handlers({
async DELETE(ctx) {
const form = await ctx.req.formData();
await deleteTodo(String(form.get("id")));
return ctx.render(<TodoList todos={await getTodos()} />);
},
});
function TodoList(props: { todos: Todo[] }) {
return (
<Partial name="todos">
<ul>
{props.todos.map((todo) => (
<li key={todo.id}>
{todo.title}
<button
type="button"
f-partial="/todos"
f-method="DELETE"
name="id"
value={todo.id}
>
Delete
</button>
</li>
))}
</ul>
</Partial>
);
}
export default define.page(async () => {
const todos = await getTodos();
return (
<div f-client-nav>
<TodoList todos={todos} />
</div>
);
});
```
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 `<form>`
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 (
<button
type="button"
f-partial="/todos"
f-method="DELETE"
name="id"
value={props.id}
onClick={(e) => {
if (!confirm("Delete this todo?")) e.preventDefault();
}}
>
Delete
</button>
);
}
```
[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 ## Sending multiple Partials at the same time
A neat aspect of partials in Fresh is that a response can return as many A neat aspect of partials in Fresh is that a response can return as many
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@paulaboks/sweet", "name": "@paulaboks/sweet",
"version": "2.3.5", "version": "2.3.7",
"license": "MIT", "license": "MIT",
"exports": { "exports": {
".": "./src/mod.ts", ".": "./src/mod.ts",
+17 -3
View File
@@ -99,12 +99,25 @@ export function csp<State>(options: CSPOptions = {}): Middleware<State> {
? "Content-Security-Policy-Report-Only" ? "Content-Security-Policy-Report-Only"
: "Content-Security-Policy"; : "Content-Security-Policy";
// Upgrading requests only makes sense when the page itself was served over
// HTTPS. On plain HTTP (e.g. local dev) it breaks things like partial
// redirects by upgrading them to an https:// URL the server doesn't serve.
// Behind a TLS-terminating proxy, enable `trustProxy` so the protocol is
// detected correctly.
const insecureMerged = merged.filter((d) =>
d !== "upgrade-insecure-requests"
);
if (!useNonce) { if (!useNonce) {
// Static CSP — no per-request nonce // Static CSP — no per-request nonce
const cspString = merged.join("; "); const cspString = merged.join("; ");
const insecureCspString = insecureMerged.join("; ");
return async (ctx) => { return async (ctx) => {
const res = await ctx.next(); const res = await ctx.next();
res.headers.set(headerName, cspString); res.headers.set(
headerName,
ctx.url.protocol === "https:" ? cspString : insecureCspString,
);
if (reportTo) { if (reportTo) {
res.headers.set("Reporting-Endpoints", `csp-endpoint="${reportTo}"`); res.headers.set("Reporting-Endpoints", `csp-endpoint="${reportTo}"`);
} }
@@ -117,10 +130,11 @@ export function csp<State>(options: CSPOptions = {}): Middleware<State> {
const res = await ctx.next(); const res = await ctx.next();
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
const nonce = (res as any)[NONCE_SYMBOL] as string | undefined; const nonce = (res as any)[NONCE_SYMBOL] as string | undefined;
const base = ctx.url.protocol === "https:" ? merged : insecureMerged;
let directives: string[]; let directives: string[];
if (nonce) { if (nonce) {
directives = merged.map((d) => { directives = base.map((d) => {
const spaceIdx = d.indexOf(" "); const spaceIdx = d.indexOf(" ");
const name = spaceIdx === -1 ? d : d.slice(0, spaceIdx); const name = spaceIdx === -1 ? d : d.slice(0, spaceIdx);
if (INLINE_DIRECTIVES.has(name) && d.includes("'unsafe-inline'")) { if (INLINE_DIRECTIVES.has(name) && d.includes("'unsafe-inline'")) {
@@ -129,7 +143,7 @@ export function csp<State>(options: CSPOptions = {}): Middleware<State> {
return d; return d;
}); });
} else { } else {
directives = merged; directives = base;
} }
res.headers.set(headerName, directives.join("; ")); res.headers.set(headerName, directives.join("; "));
@@ -17,6 +17,47 @@ Deno.test("CSP - GET default", async () => {
); );
}); });
Deno.test("CSP - omits upgrade-insecure-requests over http", async () => {
const handler = new App()
.use(csp())
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("http://localhost/"));
const header = res.headers.get("Content-Security-Policy")!;
expect(header).toContain("default-src 'self'");
expect(header).not.toContain("upgrade-insecure-requests");
});
Deno.test("CSP - useNonce omits upgrade-insecure-requests over http", async () => {
const handler = new App()
.use(csp({ useNonce: true }))
.get("/", () => new Response("ok"))
.handler();
const resHttp = await handler(new Request("http://localhost/"));
expect(resHttp.headers.get("Content-Security-Policy")).not.toContain(
"upgrade-insecure-requests",
);
const resHttps = await handler(new Request("https://localhost/"));
expect(resHttps.headers.get("Content-Security-Policy")).toContain(
"upgrade-insecure-requests",
);
});
Deno.test("CSP - keeps upgrade-insecure-requests with trusted x-forwarded-proto https", async () => {
const handler = new App({ trustProxy: true })
.use(csp())
.get("/", () => new Response("ok"))
.handler();
const res = await handler(
new Request("http://localhost/", {
headers: { "x-forwarded-proto": "https" },
}),
);
expect(res.headers.get("Content-Security-Policy")).toContain(
"upgrade-insecure-requests",
);
});
Deno.test("CSP - GET with override options", async () => { Deno.test("CSP - GET with override options", async () => {
const handler = new App() const handler = new App()
.use(csp({ .use(csp({
+50 -16
View File
@@ -25,6 +25,8 @@ import { parse } from "../../jsonify/parse.ts";
import { INTERNAL_PREFIX, PARTIAL_SEARCH_PARAM } from "../../constants.ts"; import { INTERNAL_PREFIX, PARTIAL_SEARCH_PARAM } from "../../constants.ts";
export const PARTIAL_ATTR = "f-partial"; export const PARTIAL_ATTR = "f-partial";
export const METHOD_ATTR = "f-method";
export const UPDATE_URL_ATTR = "f-update-url";
class NoPartialsError extends Error {} class NoPartialsError extends Error {}
@@ -112,6 +114,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) => { document.addEventListener("click", async (e) => {
let el = e.target; let el = e.target;
if (el && (el instanceof HTMLElement || el instanceof SVGElement)) { if (el && (el instanceof HTMLElement || el instanceof SVGElement)) {
@@ -178,20 +186,38 @@ document.addEventListener("click", async (e) => {
} }
} else if ( } else if (
el && el instanceof HTMLButtonElement && el && el instanceof HTMLButtonElement &&
(el.type !== "submit" || el.form === null) (el.type !== "submit" || el.form === null) &&
!e.defaultPrevented
) { ) {
const partial = el.getAttribute(PARTIAL_ATTR); const partial = el.getAttribute(PARTIAL_ATTR);
if (partial === null || !checkClientNavEnabled(el)) return;
// Check if the user opted out of client side navigation. const method = normalizeMethod(el.getAttribute(METHOD_ATTR));
if (partial === null || !checkClientNavEnabled(el)) { const partialUrl = new URL(partial, location.href);
return;
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( // deno-lint-ignore no-explicit-any
partial, const indicator = (el as any)._freshIndicator;
location.href, if (indicator !== undefined) {
); indicator.value = true;
await fetchPartials(partialUrl, partialUrl, false); }
try {
await withViewTransition(() =>
fetchPartials(partialUrl, partialUrl, false, init)
);
} finally {
if (indicator !== undefined) {
indicator.value = false;
}
}
} }
} }
}); });
@@ -262,14 +288,15 @@ document.addEventListener("submit", async (e) => {
return; return;
} }
const method = e.submitter?.getAttribute("formmethod")?.toLowerCase() || const method = normalizeMethod(
el.getAttribute("method")?.toLowerCase() || "get"; e.submitter?.getAttribute("formmethod") || el.getAttribute("method"),
);
if (method === "dialog") { if (method === "DIALOG") {
return; return;
} }
const isCustomMethod = method !== "get" && method !== "post"; const isCustomMethod = method !== "GET" && method !== "POST";
const hasExplicitPartial = isCustomMethod || const hasExplicitPartial = isCustomMethod ||
e.submitter?.hasAttribute(PARTIAL_ATTR) || e.submitter?.hasAttribute(PARTIAL_ATTR) ||
@@ -303,7 +330,7 @@ document.addEventListener("submit", async (e) => {
let init: RequestInit | undefined; let init: RequestInit | undefined;
// GET method appends form data via url search params // GET method appends form data via url search params
if (method === "get") { if (method === "GET") {
// TODO: Looks like constructor type for URLSearchParam is wrong // TODO: Looks like constructor type for URLSearchParam is wrong
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
const qs = new URLSearchParams(new FormData(el, e.submitter) as any); const qs = new URLSearchParams(new FormData(el, e.submitter) as any);
@@ -311,13 +338,20 @@ document.addEventListener("submit", async (e) => {
} else { } else {
init = { init = {
body: new FormData(el, e.submitter), body: new FormData(el, e.submitter),
method: method?.toUpperCase(), method,
}; };
} }
// GET and POST update the URL by default, other methods don't
const updateUrl = e.submitter?.getAttribute(UPDATE_URL_ATTR) ??
el.getAttribute(UPDATE_URL_ATTR);
const shouldNavigate = updateUrl === null
? !isCustomMethod
: updateUrl !== "false";
try { try {
await withViewTransition(async () => { await withViewTransition(async () => {
await fetchPartials(actionUrl, partialUrl, true, init); await fetchPartials(actionUrl, partialUrl, shouldNavigate, init);
}); });
} finally { } finally {
if (indicator !== undefined) { if (indicator !== undefined) {
+345 -1
View File
@@ -2128,7 +2128,12 @@ Deno.test({
<Partial name="foo"> <Partial name="foo">
<p class="init">init</p> <p class="init">init</p>
</Partial> </Partial>
<button type="submit" class="update" formmethod="DELETE"> <button
type="submit"
class="update"
formmethod="DELETE"
f-update-url="true"
>
delete delete
</button> </button>
</form> </form>
@@ -2150,6 +2155,345 @@ Deno.test({
}, },
}); });
Deno.test({
name: "partials - submit form f-update-url",
fn: async () => {
const app = testApp()
.delete("/items/1", renderMethodPartial)
.post("/partial", renderMethodPartial)
.get("/", (ctx) => {
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="delete"
formaction="/items/1"
formmethod="DELETE"
>
delete
</button>
<button
type="submit"
class="post"
formaction="/partial"
formmethod="POST"
f-update-url="false"
>
post
</button>
</form>
</div>
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
await page.goto(address, { waitUntil: "load" });
await page.locator(".init").wait();
// Custom methods leave the URL alone by default
await page.locator(".delete").click();
await page.locator(".done-DELETE-foo").wait();
let pathname = await page.evaluate(() => window.location.pathname);
expect(pathname).toEqual("/");
// f-update-url="false" opts POST out of updating the URL
await page.locator(".post").click();
await page.locator(".done-POST-foo").wait();
pathname = await page.evaluate(() => window.location.pathname);
expect(pathname).toEqual("/");
});
},
});
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(
<Doc>
<Partial name="foo">
<p class={`done-${ctx.req.method}-${name}`}>done</p>
</Partial>
</Doc>,
);
})
.get("/", (ctx) => {
return ctx.render(
<Doc>
<div f-client-nav>
<form action="/partial">
<input name="name" value="foo" />
<Partial name="foo">
<p class="init">init</p>
</Partial>
<button type="submit" class="update" formmethod="head">
update
</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-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(
<Doc>
<div f-client-nav>
<SelfCounter />
<button
type="button"
class="delete"
f-partial="/partial"
f-method="DELETE"
name="name"
value="foo"
>
delete
</button>
<button
type="button"
class="patch"
f-partial="/partial"
f-method="patch"
name="name"
value="bar"
>
patch
</button>
<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-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(
<Doc>
<Partial name="foo">
<p class={`done-${ctx.req.method}-${name}-${extra}`}>done</p>
</Partial>
</Doc>,
);
})
.get("/", (ctx) => {
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="button"
class="update"
f-partial="/partial"
f-method="PUT"
name="extra"
value="bar"
>
update
</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-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(
<Doc>
<Partial name="foo">
<p class="other">other</p>
</Partial>
</Doc>,
);
})
.get("/", (ctx) => {
return ctx.render(
<Doc>
<div f-client-nav>
<button
type="button"
class="delete"
f-partial="/partial"
f-method="DELETE"
name="name"
value="foo"
>
delete
</button>
<button type="button" class="other-btn" f-partial="/other">
other
</button>
<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(".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(
<Doc>
<div f-client-nav>
<button
type="button"
class="delete"
f-partial="/partial"
f-method="DELETE"
name="name"
value="foo"
>
delete
</button>
<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(".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({ Deno.test({
name: "partials - submit form via external submitter", name: "partials - submit form via external submitter",
fn: async () => { fn: async () => {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@paulaboks/sweet-init", "name": "@paulaboks/sweet-init",
"version": "2.3.5", "version": "2.3.7",
"license": "MIT", "license": "MIT",
"exports": { "exports": {
".": "./src/mod.ts", ".": "./src/mod.ts",
+1 -1
View File
@@ -5,7 +5,7 @@ import * as semver from "@std/semver";
import initConfig from "../deno.json" with { type: "json" }; import initConfig from "../deno.json" with { type: "json" };
// Keep these as is, as we replace these version in our release script // Keep these as is, as we replace these version in our release script
const FRESH_VERSION = "2.3.5"; const FRESH_VERSION = "2.3.7";
const FRESH_TAILWIND_VERSION = "1.0.0"; const FRESH_TAILWIND_VERSION = "1.0.0";
const FRESH_VITE_PLUGIN = "1.1.2"; const FRESH_VITE_PLUGIN = "1.1.2";
const PREACT_VERSION = "10.29.8"; const PREACT_VERSION = "10.29.8";
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@fresh/update", "name": "@fresh/update",
"version": "2.3.5", "version": "2.3.7",
"license": "MIT", "license": "MIT",
"exports": "./src/mod.ts", "exports": "./src/mod.ts",
"exclude": ["**/tmp/*"], "exclude": ["**/tmp/*"],
+1 -1
View File
@@ -7,7 +7,7 @@ import { walk } from "@std/fs/walk";
export const SyntaxKind = tsmorph.ts.SyntaxKind; export const SyntaxKind = tsmorph.ts.SyntaxKind;
export const FRESH_VERSION = "2.3.5"; export const FRESH_VERSION = "2.3.7";
export const PREACT_VERSION = "10.29.8"; export const PREACT_VERSION = "10.29.8";
export const PREACT_SIGNALS_VERSION = "2.11.4"; export const PREACT_SIGNALS_VERSION = "2.11.4";