Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/form-ref-callbacks-solid2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@solid-primitives/form": patch
---

Fix `form.ref` and `form.bind()` throwing `CLEANUP_IN_FORBIDDEN_SCOPE` (and `PRIMITIVE_IN_EFFECT_CALLBACK`) when used as JSX `ref` callbacks (#1143).

Solid 2 runs a `ref` callback in a restricted context where `onCleanup` and creating roots, memos or effects are forbidden. `ref` and `bind` registered their listeners with `makeEventListener` (which calls `onCleanup`) and `bind` created its DOM-sync effect inside the callback. In a hydrated app the throw aborted hydration, so the submit handler was never attached and a native GET submission put the fields, including passwords, into the URL.

Listeners are now plain `addEventListener` calls inside the ref callback, which still returns its cleanup. The field → DOM sync effect is created when `form.bind("name")` is evaluated (the component body), and the listeners are also torn down with the owner of `createForm` / `bind()`, because the runtime ignores a ref callback's return value. The unused `@solid-primitives/event-listener` dependency is removed.
1 change: 0 additions & 1 deletion packages/form/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
],
"dependencies": {
"@solid-primitives/a11y": "workspace:^",
"@solid-primitives/event-listener": "workspace:^",
"@solid-primitives/utils": "workspace:^"
},
"private": false,
Expand Down
106 changes: 80 additions & 26 deletions packages/form/src/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import {
createSignal,
createMemo,
createRoot,
getOwner,
onCleanup,
untrack,
createEffect,
type Accessor,
} from "solid-js";
import { makeEventListener } from "@solid-primitives/event-listener";
import type {
ValidatorFn,
FieldsConfig,
Expand Down Expand Up @@ -393,48 +393,102 @@ export function createForm<C extends FieldsConfig>(config: FormConfig<C>): FormR
}
};

// bind() returns a Phase 2 ref callback. The DOM-sync effect lives inside a createRoot
// scoped to the element's lifetime so it disposes automatically on unmount.
// Solid 2 runs a ref callback in a restricted context: it may not call onCleanup or create
// roots, memos or effects, it can only return its cleanup (see issue #1143). So bind() does
// everything reactive here, in the factory (the component body: `ref={form.bind("x")}` is
// evaluated there), and the ref callback it returns only touches the DOM and returns its cleanup.
const bind = (name: string) => {
const f = internalFields[name];
if (!f) throw new Error(`createForm: unknown field "${name}"`);

return (nextEl: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement) => {
const el = nextEl as HTMLInputElement;
const checkable = el.type === "checkbox" || el.type === "radio";
// One callback may be applied to several elements; each keeps its own state.
type Attachment = {
input: HTMLInputElement;
checkable: boolean;
teardown: () => void;
};
const active = new Set<Attachment>();

if (checkable) el.checked = Boolean(untrack(f.value));
else el.value = untrack(() => String(f.value() ?? ""));
// field -> DOM, for every element this callback is currently attached to.
const syncOne = (a: Attachment, v: unknown) => {
if (a.checkable) a.input.checked = Boolean(v);
else if (a.input.value !== String(v ?? "")) a.input.value = String(v ?? "");
};
const syncAll = (v: unknown) => active.forEach(a => syncOne(a, v));

// The effect is created in the factory so it is owned by (and disposed with) the component.
// Called outside any owner (an event handler, a plain function) nothing can own it, so it
// gets a root that lives while at least one element is attached and is disposed with the
// last one's cleanup (and recreated if the callback is attached again).
const owned = !!getOwner();
let disposeRoot: (() => void) | undefined;
if (owned) createEffect(f.value, syncAll);

const refCallback = (nextEl: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement) => {
const input = nextEl as HTMLInputElement;
const checkable = input.type === "checkbox" || input.type === "radio";

// Plain listeners, removed by the cleanup: makeEventListener would register its removal
// with onCleanup, which is forbidden inside a ref callback.
const valueEvent = checkable ? "change" : "input";
const onValue = () => f._setValue(checkable ? input.checked : input.value);
const onBlur = () => f._setTouched(true);
input.addEventListener(valueEvent, onValue);
input.addEventListener("blur", onBlur);

const attachment: Attachment = {
input,
checkable,
teardown: () => {
if (!active.delete(attachment)) return;
input.removeEventListener(valueEvent, onValue);
input.removeEventListener("blur", onBlur);
if (!owned && active.size === 0) {
disposeRoot?.();
disposeRoot = undefined;
}
},
};
active.add(attachment);

const disposeEffect = createRoot(d => {
createEffect(f.value, v => {
if (checkable) el.checked = Boolean(v);
else if (el.value !== String(v ?? "")) el.value = String(v ?? "");
if (!owned && !disposeRoot)
disposeRoot = createRoot(d => {
Comment thread
davedbase marked this conversation as resolved.
Resolved
createEffect(f.value, syncAll);
return d;
});
return d;
});

const off1 = makeEventListener(el, checkable ? "change" : "input", () =>
f._setValue(checkable ? el.checked : el.value),
);
const off2 = makeEventListener(el, "blur", () => f._setTouched(true));
syncOne(attachment, untrack(f.value));

return () => {
off1();
off2();
disposeEffect();
};
return attachment.teardown;
};

// The runtime does not call a ref callback's returned cleanup (it ignores the return value),
// so also tear every attachment down with the owner that evaluated bind(). Registered here
// in the factory, where onCleanup is allowed (it is forbidden inside the ref callback).
if (owned) onCleanup(() => [...active].forEach(a => a.teardown()));
return refCallback;
};

const ref = (el: HTMLFormElement) =>
makeEventListener(el, "submit", (e: SubmitEvent) => {
// Same constraint as bind(): the ref callback may not call onCleanup and the runtime ignores
// its return value, so the submit listeners are also removed when createForm's owner is disposed.
const submitTeardowns = new Set<() => void>();
const ref = (el: HTMLFormElement) => {
const onSubmit = (e: SubmitEvent) => {
e.preventDefault();
void submit();
});
};
el.addEventListener("submit", onSubmit);
const teardown = () => {
if (!submitTeardowns.delete(teardown)) return;
el.removeEventListener("submit", onSubmit);
};
submitTeardowns.add(teardown);
return teardown;
};

onCleanup(() => {
_isSubmitting = false;
[...submitTeardowns].forEach(t => t());
});

return {
Expand Down
184 changes: 184 additions & 0 deletions packages/form/test/bind-multiple.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import { describe, it, expect } from "vitest";
import { createRoot, flush } from "solid-js";
import { createForm } from "../src/index.js";

// One `form.bind("x")` callback may be attached to several elements (a callback kept in a
// variable and reused, an array of refs...). Each attachment must keep its own state and
// lifetime: they must not overwrite each other or dispose each other's synchronization.

const input = (type?: string) => {
const el = document.createElement("input");
if (type) el.type = type;
return el;
};

describe("one bind() callback attached to several elements", () => {
it("keeps every attached element in sync with the field", () => {
createRoot(dispose => {
const form = createForm({ fields: { email: { initial: "x" } } });
const attach = form.bind("email");
const a = input();
const b = input();
attach(a);
attach(b);
expect([a.value, b.value]).toEqual(["x", "x"]);

form.fields.email.setValue("y");
flush();
expect([a.value, b.value]).toEqual(["y", "y"]);
dispose();
});
});

it("each element writes to the field through its own listener", () => {
createRoot(dispose => {
const form = createForm({ fields: { email: { initial: "" } } });
const attach = form.bind("email");
const a = input();
const b = input();
attach(a);
attach(b);

a.value = "from-a";
a.dispatchEvent(new Event("input"));
flush();
expect(form.fields.email.value()).toBe("from-a");

b.value = "from-b";
b.dispatchEvent(new Event("input"));
flush();
expect(form.fields.email.value()).toBe("from-b");
// and the other element follows
expect(a.value).toBe("from-b");
dispose();
});
});

it("each listener uses its own element's classification (checkable vs text)", () => {
createRoot(dispose => {
const form = createForm({ fields: { v: { initial: "" as any } } });
const attach = form.bind("v");
const box = input("checkbox");
const text = input();
attach(box);
attach(text);

box.checked = true;
box.dispatchEvent(new Event("change"));
flush();
expect(form.fields.v.value()).toBe(true);

text.value = "typed";
text.dispatchEvent(new Event("input"));
flush();
expect(form.fields.v.value()).toBe("typed");
dispose();
});
});

it("cleaning up one element leaves the others attached and in sync", () => {
createRoot(dispose => {
const form = createForm({ fields: { email: { initial: "x" } } });
const attach = form.bind("email");
const a = input();
const b = input();
const offA = attach(a);
attach(b);

offA();
form.fields.email.setValue("z");
flush();
expect(b.value).toBe("z");
expect(a.value).toBe("x"); // detached: no longer driven by the field

a.value = "ignored";
a.dispatchEvent(new Event("input"));
flush();
expect(form.fields.email.value()).toBe("z");
dispose();
});
});

it("disposing the owner removes every attachment", () => {
let form!: ReturnType<typeof createForm<{ email: { initial: string } }>>;
const a = input();
const b = input();
createRoot(dispose => {
form = createForm({ fields: { email: { initial: "" } } });
const attach = form.bind("email");
attach(a);
attach(b);
dispose();
});

for (const el of [a, b]) {
el.value = "after-dispose";
el.dispatchEvent(new Event("input"));
el.dispatchEvent(new Event("blur"));
}
flush();
expect(form.fields.email.value()).toBe("");
expect(form.fields.email.touched()).toBe(false);
});

describe("without an owner", () => {
// The factory is called outside any owner (an event handler, a plain function), so the
// field -> DOM effect lives in a root that follows the attachments.
const ownerless = () => {
let form!: ReturnType<typeof createForm<{ email: { initial: string } }>>;
const dispose = createRoot(d => {
form = createForm({ fields: { email: { initial: "x" } } });
return d;
});
return { form, dispose, attach: form.bind("email") };
};

it("cleaning up one element does not stop synchronization for the others", () => {
const { form, dispose, attach } = ownerless();
const a = input();
const b = input();
const offA = attach(a);
attach(b);

offA();
form.fields.email.setValue("z");
flush();
expect(b.value).toBe("z");
dispose();
});

it("stops synchronizing after the last element is cleaned up, and resumes on re-attach", () => {
const { form, dispose, attach } = ownerless();
const a = input();
const offA = attach(a);
offA();

form.fields.email.setValue("while-detached");
flush();
expect(a.value).toBe("x"); // root disposed: nothing drives the detached element

const b = input();
attach(b);
expect(b.value).toBe("while-detached"); // initial sync on attach
form.fields.email.setValue("again");
flush();
expect(b.value).toBe("again"); // root recreated
dispose();
});

it("calling a cleanup twice does not dispose another element's synchronization", () => {
const { form, dispose, attach } = ownerless();
const a = input();
const b = input();
const offA = attach(a);
attach(b);

offA();
offA();
form.fields.email.setValue("still-synced");
flush();
expect(b.value).toBe("still-synced");
dispose();
});
});
});
Loading
Loading