Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
93 changes: 68 additions & 25 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,91 @@ 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";

if (checkable) el.checked = Boolean(untrack(f.value));
else el.value = untrack(() => String(f.value() ?? ""));

const disposeEffect = createRoot(d => {
createEffect(f.value, v => {
if (checkable) el.checked = Boolean(v);
else if (el.value !== String(v ?? "")) el.value = String(v ?? "");
});
let el: HTMLInputElement | undefined;
let checkable = false;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Teardowns of every element this bind() was applied to. The runtime does not call a ref
// callback's returned cleanup (it ignores the return value), so they also run when the
// owner that evaluated bind() is disposed; each is idempotent.
const teardowns = new Set<() => void>();

// field -> DOM. Created in the factory so it is owned by (and disposed with) the component.
const syncDom = (v: unknown) => {
if (!el) return;
if (checkable) el.checked = Boolean(v);
else if (el.value !== String(v ?? "")) el.value = String(v ?? "");
};
// Called outside any owner (e.g. in an event handler or a plain function) there is nothing to
// own the effect, so give it a root that is disposed together with the ref cleanup below.
let disposeRoot: (() => void) | undefined;
if (getOwner()) createEffect(f.value, syncDom);
else
disposeRoot = createRoot(d => {
createEffect(f.value, syncDom);
return d;
});

const off1 = makeEventListener(el, checkable ? "change" : "input", () =>
f._setValue(checkable ? el.checked : el.value),
);
const off2 = makeEventListener(el, "blur", () => f._setTouched(true));
const refCallback = (nextEl: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement) => {
const input = nextEl as HTMLInputElement;
el = input;
checkable = input.type === "checkbox" || input.type === "radio";

syncDom(untrack(f.value));

// Plain listeners, removed by the returned 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 teardown = () => {
if (!teardowns.delete(teardown)) return;
input.removeEventListener(valueEvent, onValue);
input.removeEventListener("blur", onBlur);
if (el === input) el = undefined;
};
teardowns.add(teardown);

return () => {
off1();
off2();
disposeEffect();
teardown();
disposeRoot?.();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
};
};

// Register in the factory (allowed here, forbidden inside the ref callback below).
if (getOwner()) onCleanup(() => [...teardowns].forEach(t => t()));
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
54 changes: 54 additions & 0 deletions packages/form/test/hydration.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,57 @@ describe("createForm hydration round trip", () => {
expect(button?.disabled).toBe(true);
});
});

// Regression for https://github.com/solidjs-community/solid-primitives/issues/1143: the README
// usage threw CLEANUP_IN_FORBIDDEN_SCOPE from the `ref` callbacks, which aborted hydration. The
// form's submit handler was then never attached, so 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");
});
});
161 changes: 161 additions & 0 deletions packages/form/test/ref.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import { flush } from "solid-js";
import { render } from "@solidjs/web";
import { createForm } from "../src/index.js";

// Regression tests for https://github.com/solidjs-community/solid-primitives/issues/1143
//
// The other tests call `form.bind("x")(el)` / `form.ref(el)` directly, which bypasses the context
// Solid runs real JSX `ref` callbacks in. In that context Solid 2 forbids `onCleanup`
// (CLEANUP_IN_FORBIDDEN_SCOPE) and creating roots, memos or effects (PRIMITIVE_IN_EFFECT_CALLBACK):
// a ref callback may only return its cleanup. These tests mount the documented usage through the
// compiled JSX so those guards are active.

let disposers: Array<() => void> = [];

function mount(App: () => any) {
const container = document.createElement("div");
document.body.appendChild(container);
const dispose = render(App, container);
const unmount = () => {
dispose();
container.remove();
};
disposers.push(unmount);
return { container, unmount };
}

afterEach(() => {
disposers.forEach(d => d());
disposers = [];
});

describe("createForm as JSX ref callbacks", () => {
it("mounts the documented README usage without throwing", () => {
expect(() =>
mount(() => {
const form = createForm({ fields: { email: { initial: "" } } });
return (
<form ref={form.ref}>
<input ref={form.bind("email")} />
<button type="submit">Submit</button>
</form>
);
}),
).not.toThrow();
});

it("intercepts the native submit event", async () => {
const onSubmit = vi.fn();
const { container } = mount(() => {
const form = createForm({
fields: { email: { initial: "a@b.c" } },
onSubmit,
});
return (
<form ref={form.ref}>
<input ref={form.bind("email")} />
</form>
);
});

const formEl = container.querySelector("form")!;
const event = new Event("submit", { cancelable: true, bubbles: true });
formEl.dispatchEvent(event);
await Promise.resolve();
flush();

expect(event.defaultPrevented).toBe(true);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit.mock.calls[0]![0]).toEqual({ email: "a@b.c" });
});

it("syncs the DOM to the field in both directions", () => {
let form!: ReturnType<typeof createForm<{ email: { initial: string } }>>;
const { container } = mount(() => {
form = createForm({ fields: { email: { initial: "start" } } });
return (
<form ref={form.ref}>
<input ref={form.bind("email")} />
</form>
);
});
const input = container.querySelector("input")!;

// initial value is written synchronously by the ref callback
expect(input.value).toBe("start");

// DOM -> field
input.value = "typed";
input.dispatchEvent(new Event("input", { bubbles: true }));
flush();
expect(form.fields.email.value()).toBe("typed");

// field -> DOM (the sync effect is created in the component body, not in the ref callback)
form.fields.email.setValue("from-code");
flush();
expect(input.value).toBe("from-code");
});

it("tracks touched state on blur", () => {
let form!: ReturnType<typeof createForm<{ email: { initial: string } }>>;
const { container } = mount(() => {
form = createForm({ fields: { email: { initial: "" } } });
return <input ref={form.bind("email")} />;
});
const input = container.querySelector("input")!;

expect(form.fields.email.touched()).toBe(false);
input.dispatchEvent(new Event("blur"));
flush();
expect(form.fields.email.touched()).toBe(true);
});

it("supports checkable inputs", () => {
let form!: ReturnType<typeof createForm<{ agree: { initial: boolean } }>>;
const { container } = mount(() => {
form = createForm({ fields: { agree: { initial: false } } });
return <input type="checkbox" ref={form.bind("agree")} />;
});
const input = container.querySelector("input")!;

input.checked = true;
input.dispatchEvent(new Event("change", { bubbles: true }));
flush();
expect(form.fields.agree.value()).toBe(true);

form.fields.agree.setValue(false);
flush();
expect(input.checked).toBe(false);
});

it("removes every listener when the ref is cleaned up", () => {
let form!: ReturnType<typeof createForm<{ email: { initial: string } }>>;
const onSubmit = vi.fn();
const { container, unmount } = mount(() => {
form = createForm({ fields: { email: { initial: "" } }, onSubmit });
return (
<form ref={form.ref}>
<input ref={form.bind("email")} />
</form>
);
});
const formEl = container.querySelector("form")!;
const input = container.querySelector("input")!;

unmount();

// listeners are gone: nothing reaches the form state or the submit handler any more
input.value = "after-unmount";
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("blur"));
const event = new Event("submit", { cancelable: true, bubbles: true });
formEl.dispatchEvent(event);
flush();

expect(form.fields.email.value()).toBe("");
expect(form.fields.email.touched()).toBe(false);
expect(event.defaultPrevented).toBe(false);
expect(onSubmit).not.toHaveBeenCalled();
});
});
3 changes: 0 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading