Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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: 78 additions & 28 deletions packages/form/src/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import {
createSignal,
createMemo,
createRoot,
getOwner,
onCleanup,
runWithOwner,
untrack,
createEffect,
type Accessor,
} from "solid-js";
import { makeEventListener } from "@solid-primitives/event-listener";
import type {
ValidatorFn,
FieldsConfig,
Expand Down Expand Up @@ -393,48 +394,97 @@ 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.
// A ref callback can't use onCleanup or create primitives (#1143), so bind() sets up everything
// reactive here, in the component body; the callback it returns only touches the DOM.
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 can be attached 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 attached element
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));

// Owned by the component; with no owner, a root that lives while an element is attached.
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: makeEventListener would call onCleanup, forbidden in 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);

// Detached (null owner): a root can't be created under the ref callback's owner, and only
// the last teardown should dispose it.
if (!owned && !disposeRoot)
disposeRoot = runWithOwner(null, () =>
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
createRoot(d => {
createEffect(f.value, syncAll);
return d;
}),
);

const disposeEffect = createRoot(d => {
createEffect(f.value, v => {
if (checkable) el.checked = Boolean(v);
else if (el.value !== String(v ?? "")) el.value = String(v ?? "");
});
return d;
});
syncOne(attachment, untrack(f.value));

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

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

// The runtime ignores a ref's returned cleanup, so also tear down with the owner.
if (owned) onCleanup(() => [...active].forEach(a => a.teardown()));
return refCallback;
};

const ref = (el: HTMLFormElement) =>
makeEventListener(el, "submit", (e: SubmitEvent) => {
// Same as bind(): also remove the submit listeners with createForm's owner.
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
181 changes: 181 additions & 0 deletions packages/form/test/bind-multiple.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import { describe, it, expect } from "vitest";
import { createRoot, flush } from "solid-js";
import { createForm } from "../src/index.js";

// One bind() callback attached to several elements: each keeps its own state and lifetime.

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", () => {
// bind() called with no owner: the field -> DOM effect lives in a root tied to 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();
});
});
});
53 changes: 53 additions & 0 deletions packages/form/test/hydration.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,56 @@ describe("createForm hydration round trip", () => {
expect(button?.disabled).toBe(true);
});
});

// Regression for #1143: the ref callbacks threw CLEANUP_IN_FORBIDDEN_SCOPE and aborted hydration,
// so the submit handler was never attached and submitting navigated with the fields in the URL.
const REF_APP_SOURCE = `
import { createForm } from "@solid-primitives/form";

export default function App() {
const form = createForm({ fields: { email: { initial: "" } } });
return (
<form id="out" ref={form.ref}>
<input id="email" ref={form.bind("email")} />
<span id="value">{form.fields.email.value()}</span>
<button type="submit">Send</button>
</form>
);
}
`;

describe("createForm ref callbacks during hydration", () => {
let result: HydrationRoundTripResult | undefined;

afterEach(() => {
result?.cleanup();
result = undefined;
});

it("hydrates the documented ref usage without any console error or warning", async () => {
result = await renderHydrationRoundTrip(REF_APP_SOURCE, import.meta.dirname);
expect(result.consoleMessages).toEqual([]);
});

it("claims the server-rendered nodes and attaches the submit listener", async () => {
result = await renderHydrationRoundTrip(REF_APP_SOURCE, import.meta.dirname);
const form = result.container.querySelector("form")!;
const button = result.container.querySelector("button")!;
expect(form.isConnected).toBe(true);
expect(button.isConnected).toBe(true);

// the listener is attached: a native submit is intercepted instead of navigating
const event = new Event("submit", { cancelable: true, bubbles: true });
form.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
});

it("wires the input to the field after hydration", async () => {
result = await renderHydrationRoundTrip(REF_APP_SOURCE, import.meta.dirname);
const input = result.container.querySelector<HTMLInputElement>("#email")!;
input.value = "ada@example.com";
input.dispatchEvent(new Event("input", { bubbles: true }));
await Promise.resolve();
expect(result.container.querySelector("#value")!.textContent).toBe("ada@example.com");
});
});
Loading
Loading