From 2f7508798ccda4f31a38b50fd6e9348f83fdbaa0 Mon Sep 17 00:00:00 2001 From: David Di Biase <1168397+davedbase@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:53:06 -0500 Subject: [PATCH 1/8] fix(form): don't use onCleanup or create primitives inside ref callbacks form.ref and form.bind() registered their listeners with makeEventListener, which calls onCleanup, and bind() created a root and effect, all inside the ref callback. Solid 2 forbids both there (CLEANUP_IN_FORBIDDEN_SCOPE / PRIMITIVE_IN_EFFECT_CALLBACK), so the README usage threw, aborted hydration, and left the form submitting natively. - ref and bind attach plain listeners in the callback, which still returns its cleanup - bind() creates the field -> DOM sync effect in the factory (the component body) - the runtime ignores a ref callback's return value, so the listeners are also torn down with the owner of bind() / createForm - drop the now-unused @solid-primitives/event-listener dependency Adds regression tests that mount the real JSX refs and a hydration round trip. Fixes #1143 Co-Authored-By: Claude Sonnet 5.5 --- .changeset/form-ref-callbacks-solid2.md | 9 ++ packages/form/package.json | 1 - packages/form/src/form.ts | 93 ++++++++++---- packages/form/test/hydration.test.tsx | 54 ++++++++ packages/form/test/ref.test.tsx | 161 ++++++++++++++++++++++++ pnpm-lock.yaml | 3 - 6 files changed, 292 insertions(+), 29 deletions(-) create mode 100644 .changeset/form-ref-callbacks-solid2.md create mode 100644 packages/form/test/ref.test.tsx diff --git a/.changeset/form-ref-callbacks-solid2.md b/.changeset/form-ref-callbacks-solid2.md new file mode 100644 index 000000000..98e3a029b --- /dev/null +++ b/.changeset/form-ref-callbacks-solid2.md @@ -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. diff --git a/packages/form/package.json b/packages/form/package.json index 6d9c5993b..9f17ce6d4 100644 --- a/packages/form/package.json +++ b/packages/form/package.json @@ -35,7 +35,6 @@ ], "dependencies": { "@solid-primitives/a11y": "workspace:^", - "@solid-primitives/event-listener": "workspace:^", "@solid-primitives/utils": "workspace:^" }, "private": false, diff --git a/packages/form/src/form.ts b/packages/form/src/form.ts index 6fa7d2355..67035a04b 100644 --- a/packages/form/src/form.ts +++ b/packages/form/src/form.ts @@ -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, @@ -393,48 +393,91 @@ export function createForm(config: FormConfig): 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; + // 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?.(); }; }; + + // 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 { diff --git a/packages/form/test/hydration.test.tsx b/packages/form/test/hydration.test.tsx index ddfddff8b..e66f54924 100644 --- a/packages/form/test/hydration.test.tsx +++ b/packages/form/test/hydration.test.tsx @@ -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.fields.email.value()} + +
+ ); +} +`; + +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("#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"); + }); +}); diff --git a/packages/form/test/ref.test.tsx b/packages/form/test/ref.test.tsx new file mode 100644 index 000000000..56fc5406e --- /dev/null +++ b/packages/form/test/ref.test.tsx @@ -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 ( +
+ + +
+ ); + }), + ).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 ( +
+ +
+ ); + }); + + 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>; + const { container } = mount(() => { + form = createForm({ fields: { email: { initial: "start" } } }); + return ( +
+ +
+ ); + }); + 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>; + const { container } = mount(() => { + form = createForm({ fields: { email: { initial: "" } } }); + return ; + }); + 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>; + const { container } = mount(() => { + form = createForm({ fields: { agree: { initial: false } } }); + return ; + }); + 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>; + const onSubmit = vi.fn(); + const { container, unmount } = mount(() => { + form = createForm({ fields: { email: { initial: "" } }, onSubmit }); + return ( +
+ +
+ ); + }); + 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(); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cafa53c16..b1f9ba14a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -524,9 +524,6 @@ importers: '@solid-primitives/a11y': specifier: workspace:^ version: link:../a11y - '@solid-primitives/event-listener': - specifier: workspace:^ - version: link:../event-listener '@solid-primitives/utils': specifier: workspace:^ version: link:../utils From 2fc63374e0cd33c3646698820e820e48a1c6e2aa Mon Sep 17 00:00:00 2001 From: David Di Biase <1168397+davedbase@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:05:07 -0500 Subject: [PATCH 2/8] fix(form): keep per-element state when one bind() callback is attached to several elements The ref-callback rework shared a single element, classification and effect root across every attachment of one bind() callback, so a second element overwrote the first, a checkable/text mix misclassified listeners, and (without an owner) cleaning up one element disposed synchronization for the rest. Before the rework each attachment had its own state. Each attachment now keeps its own element, classification and teardown; the field -> DOM effect syncs all active attachments. Without an owner the root lives while at least one element is attached and is recreated on re-attach. Cleanups are idempotent. Co-Authored-By: Claude Sonnet 5.5 --- packages/form/src/form.ts | 87 ++++++----- packages/form/test/bind-multiple.test.ts | 184 +++++++++++++++++++++++ 2 files changed, 233 insertions(+), 38 deletions(-) create mode 100644 packages/form/test/bind-multiple.test.ts diff --git a/packages/form/src/form.ts b/packages/form/src/form.ts index 67035a04b..70e8f8e56 100644 --- a/packages/form/src/form.ts +++ b/packages/form/src/form.ts @@ -401,60 +401,71 @@ export function createForm(config: FormConfig): FormR const f = internalFields[name]; if (!f) throw new Error(`createForm: unknown field "${name}"`); - let el: HTMLInputElement | undefined; - let checkable = false; - // 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 ?? ""); + // One callback may be applied to several elements; each keeps its own state. + type Attachment = { + input: HTMLInputElement; + checkable: boolean; + teardown: () => void; }; - // 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. + const active = new Set(); + + // 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 (getOwner()) createEffect(f.value, syncDom); - else - disposeRoot = createRoot(d => { - createEffect(f.value, syncDom); - return d; - }); + if (owned) createEffect(f.value, syncAll); const refCallback = (nextEl: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement) => { const input = nextEl as HTMLInputElement; - el = input; - checkable = input.type === "checkbox" || input.type === "radio"; - - syncDom(untrack(f.value)); + const checkable = input.type === "checkbox" || input.type === "radio"; - // Plain listeners, removed by the returned cleanup: makeEventListener would register its - // removal with onCleanup, which is forbidden inside a ref callback. + // 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 teardown = () => { - if (!teardowns.delete(teardown)) return; - input.removeEventListener(valueEvent, onValue); - input.removeEventListener("blur", onBlur); - if (el === input) el = undefined; + 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; + } + }, }; - teardowns.add(teardown); + active.add(attachment); - return () => { - teardown(); - disposeRoot?.(); - }; + if (!owned && !disposeRoot) + disposeRoot = createRoot(d => { + createEffect(f.value, syncAll); + return d; + }); + + syncOne(attachment, untrack(f.value)); + + return attachment.teardown; }; - // Register in the factory (allowed here, forbidden inside the ref callback below). - if (getOwner()) onCleanup(() => [...teardowns].forEach(t => t())); + // 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; }; diff --git a/packages/form/test/bind-multiple.test.ts b/packages/form/test/bind-multiple.test.ts new file mode 100644 index 000000000..fe203c2b1 --- /dev/null +++ b/packages/form/test/bind-multiple.test.ts @@ -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>; + 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>; + 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(); + }); + }); +}); From bde45888907b842785ddbaf553359f30880fcd4b Mon Sep 17 00:00:00 2001 From: David Di Biase <1168397+davedbase@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:15:24 -0500 Subject: [PATCH 3/8] chore(form): shorten comments Co-Authored-By: Claude Sonnet 5.5 --- packages/form/src/form.ts | 25 ++++++++---------------- packages/form/test/bind-multiple.test.ts | 7 ++----- packages/form/test/hydration.test.tsx | 5 ++--- packages/form/test/ref.test.tsx | 11 +++-------- 4 files changed, 15 insertions(+), 33 deletions(-) diff --git a/packages/form/src/form.ts b/packages/form/src/form.ts index 70e8f8e56..30a59a8a0 100644 --- a/packages/form/src/form.ts +++ b/packages/form/src/form.ts @@ -393,15 +393,13 @@ export function createForm(config: FormConfig): FormR } }; - // 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. + // 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}"`); - // One callback may be applied to several elements; each keeps its own state. + // One callback can be attached to several elements; each keeps its own state. type Attachment = { input: HTMLInputElement; checkable: boolean; @@ -409,17 +407,14 @@ export function createForm(config: FormConfig): FormR }; const active = new Set(); - // field -> DOM, for every element this callback is currently attached to. + // 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)); - // 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). + // 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); @@ -428,8 +423,7 @@ export function createForm(config: FormConfig): FormR 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. + // 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); @@ -462,15 +456,12 @@ export function createForm(config: FormConfig): FormR 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). + // 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; }; - // 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. + // 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) => { diff --git a/packages/form/test/bind-multiple.test.ts b/packages/form/test/bind-multiple.test.ts index fe203c2b1..726772fc0 100644 --- a/packages/form/test/bind-multiple.test.ts +++ b/packages/form/test/bind-multiple.test.ts @@ -2,9 +2,7 @@ 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. +// One bind() callback attached to several elements: each keeps its own state and lifetime. const input = (type?: string) => { const el = document.createElement("input"); @@ -122,8 +120,7 @@ describe("one bind() callback attached to several elements", () => { }); 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. + // bind() called with no owner: the field -> DOM effect lives in a root tied to the attachments. const ownerless = () => { let form!: ReturnType>; const dispose = createRoot(d => { diff --git a/packages/form/test/hydration.test.tsx b/packages/form/test/hydration.test.tsx index e66f54924..b7fcdb63d 100644 --- a/packages/form/test/hydration.test.tsx +++ b/packages/form/test/hydration.test.tsx @@ -56,9 +56,8 @@ describe("createForm hydration round trip", () => { }); }); -// 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. +// 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"; diff --git a/packages/form/test/ref.test.tsx b/packages/form/test/ref.test.tsx index 56fc5406e..14e960178 100644 --- a/packages/form/test/ref.test.tsx +++ b/packages/form/test/ref.test.tsx @@ -3,13 +3,8 @@ 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. +// Regression for #1143. Calling form.bind("x")(el) directly bypasses the context where Solid 2 +// forbids onCleanup and creating primitives in a ref callback, so these tests mount real JSX refs. let disposers: Array<() => void> = []; @@ -91,7 +86,7 @@ describe("createForm as JSX ref callbacks", () => { flush(); expect(form.fields.email.value()).toBe("typed"); - // field -> DOM (the sync effect is created in the component body, not in the ref callback) + // field -> DOM form.fields.email.setValue("from-code"); flush(); expect(input.value).toBe("from-code"); From 25cf1bc32edf4916bc21a39328d5115a5d9e6786 Mon Sep 17 00:00:00 2001 From: David Di Biase <1168397+davedbase@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:21:05 -0500 Subject: [PATCH 4/8] fix(form): create the ownerless sync root detached from the ref callback's owner When bind() was evaluated without an owner, the fallback effect root was created inside the ref callback, which Solid forbids (PRIMITIVE_IN_EFFECT_CALLBACK) as soon as the callback ran as a real JSX ref. Create it with a null owner instead; the last attachment's teardown remains the only thing that disposes it. Co-Authored-By: Claude Sonnet 5.5 --- packages/form/src/form.ts | 13 +++++++++---- packages/form/test/ref.test.tsx | 18 +++++++++++++++++- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/packages/form/src/form.ts b/packages/form/src/form.ts index 30a59a8a0..d93682464 100644 --- a/packages/form/src/form.ts +++ b/packages/form/src/form.ts @@ -4,6 +4,7 @@ import { createRoot, getOwner, onCleanup, + runWithOwner, untrack, createEffect, type Accessor, @@ -445,11 +446,15 @@ export function createForm(config: FormConfig): FormR }; 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 = createRoot(d => { - createEffect(f.value, syncAll); - return d; - }); + disposeRoot = runWithOwner(null, () => + createRoot(d => { + createEffect(f.value, syncAll); + return d; + }), + ); syncOne(attachment, untrack(f.value)); diff --git a/packages/form/test/ref.test.tsx b/packages/form/test/ref.test.tsx index 14e960178..8553dc70b 100644 --- a/packages/form/test/ref.test.tsx +++ b/packages/form/test/ref.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect, vi, afterEach } from "vitest"; -import { flush } from "solid-js"; +import { createRoot, flush } from "solid-js"; import { render } from "@solidjs/web"; import { createForm } from "../src/index.js"; @@ -124,6 +124,22 @@ describe("createForm as JSX ref callbacks", () => { expect(input.checked).toBe(false); }); + it("works when bind() was evaluated without an owner", () => { + let form!: ReturnType>; + createRoot(d => { + form = createForm({ fields: { email: { initial: "x" } } }); + return d; + }); + const attach = form.bind("email"); // no owner here + const { container } = mount(() => ); + const input = container.querySelector("input")!; + + expect(input.value).toBe("x"); + form.fields.email.setValue("y"); + flush(); + expect(input.value).toBe("y"); + }); + it("removes every listener when the ref is cleaned up", () => { let form!: ReturnType>; const onSubmit = vi.fn(); From 6457c2483512e7054277325abed059d26cb2fc5f Mon Sep 17 00:00:00 2001 From: David Di Biase <1168397+davedbase@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:04:25 -0500 Subject: [PATCH 5/8] fix: don't use onCleanup or create primitives inside ref callbacks (active-element, cursor, mutation-observer, pagination, lifecycle) The same Solid 2 restriction behind #1143 broke more ref APIs, confirmed with real JSX render tests: - active-element focus(): makeEventListener (onCleanup) inside the ref callback - cursor cursorRef(): createElementCursor (an effect) inside the ref callback - mutation-observer mutationObserver(): createMutationObserver inside the ref callback - pagination createInfiniteScroll loader: tryOnCleanup inside the ref callback - lifecycle onElementConnect(): onCleanup inside the callback when used as documented Each now follows the form pattern: reactive setup in the factory, the ref callback only touches the DOM and returns a teardown, per-element state, and teardown also tied to the factory owner because the runtime ignores a ref callback's return value. lifecycle: onElementConnect no longer registers onCleanup (it returns a disposer and self-disconnects once connected) and createConnectRef is added as a ref factory that cleans up with the owner. mediastream: README examples no longer create an effect inside a ref callback. Co-Authored-By: Claude Sonnet 5.5 --- .../active-element-ref-callback-solid2.md | 7 + .changeset/cursor-ref-callback-solid2.md | 7 + .changeset/lifecycle-ref-callback-solid2.md | 5 + .changeset/mediastream-ref-callback-solid2.md | 5 + .../mutation-observer-ref-callback-solid2.md | 7 + .changeset/pagination-ref-callback-solid2.md | 7 + README.md | 2 +- packages/active-element/README.md | 2 +- packages/active-element/src/index.ts | 27 ++-- packages/active-element/test/ref.test.tsx | 101 ++++++++++++++ packages/cursor/README.md | 2 +- packages/cursor/src/index.ts | 30 +++- packages/cursor/test/ref.test.tsx | 89 ++++++++++++ packages/lifecycle/README.md | 29 +++- packages/lifecycle/package.json | 3 +- packages/lifecycle/src/index.ts | 68 +++++++-- packages/lifecycle/test/ref.test.tsx | 128 +++++++++++++++++ packages/mediastream/README.md | 49 ++++--- packages/mutation-observer/README.md | 2 + packages/mutation-observer/src/index.ts | 15 +- packages/mutation-observer/test/ref.test.tsx | 117 ++++++++++++++++ packages/pagination/README.md | 2 +- packages/pagination/src/index.ts | 11 +- packages/pagination/test/ref.test.tsx | 131 ++++++++++++++++++ 24 files changed, 774 insertions(+), 72 deletions(-) create mode 100644 .changeset/active-element-ref-callback-solid2.md create mode 100644 .changeset/cursor-ref-callback-solid2.md create mode 100644 .changeset/lifecycle-ref-callback-solid2.md create mode 100644 .changeset/mediastream-ref-callback-solid2.md create mode 100644 .changeset/mutation-observer-ref-callback-solid2.md create mode 100644 .changeset/pagination-ref-callback-solid2.md create mode 100644 packages/active-element/test/ref.test.tsx create mode 100644 packages/cursor/test/ref.test.tsx create mode 100644 packages/lifecycle/test/ref.test.tsx create mode 100644 packages/mutation-observer/test/ref.test.tsx create mode 100644 packages/pagination/test/ref.test.tsx diff --git a/.changeset/active-element-ref-callback-solid2.md b/.changeset/active-element-ref-callback-solid2.md new file mode 100644 index 000000000..0c992d768 --- /dev/null +++ b/.changeset/active-element-ref-callback-solid2.md @@ -0,0 +1,7 @@ +--- +"@solid-primitives/active-element": patch +--- + +Fix `focus()` throwing `CLEANUP_IN_FORBIDDEN_SCOPE` when used as a JSX `ref` callback (#1143). + +Solid 2 forbids `onCleanup` in a `ref` callback, and `focus()` registered its listeners with `makeEventListener`, which calls it. The callback now uses plain `addEventListener` and returns its teardown. Each element keeps its own teardown, so one `focus()` value works on several elements, and all of them are also removed with the owner of the `focus()` call because the runtime ignores a ref callback's return value. diff --git a/.changeset/cursor-ref-callback-solid2.md b/.changeset/cursor-ref-callback-solid2.md new file mode 100644 index 000000000..aad43ab7b --- /dev/null +++ b/.changeset/cursor-ref-callback-solid2.md @@ -0,0 +1,7 @@ +--- +"@solid-primitives/cursor": patch +--- + +Fix `cursorRef` throwing `PRIMITIVE_IN_EFFECT_CALLBACK` when used as a JSX `ref` callback (#1143). + +Solid 2 forbids creating effects inside a `ref` callback, and `cursorRef` created one there via `createElementCursor`. The effect is now created when `cursorRef(...)` is evaluated (the component body); the callback only registers the element and returns a teardown. The cursor is restored when the element unmounts or the owner is disposed, and one `cursorRef` value can be attached to several elements. diff --git a/.changeset/lifecycle-ref-callback-solid2.md b/.changeset/lifecycle-ref-callback-solid2.md new file mode 100644 index 000000000..3df784bc1 --- /dev/null +++ b/.changeset/lifecycle-ref-callback-solid2.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/lifecycle": patch +--- + +Fix `onElementConnect` throwing `CLEANUP_IN_FORBIDDEN_SCOPE` inside a `ref` callback (#1143). It no longer calls `onCleanup` and now returns a disposer. Add `createConnectRef` for `ref` usage that also cleans up with the owner. diff --git a/.changeset/mediastream-ref-callback-solid2.md b/.changeset/mediastream-ref-callback-solid2.md new file mode 100644 index 000000000..263d8b7d0 --- /dev/null +++ b/.changeset/mediastream-ref-callback-solid2.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/mediastream": patch +--- + +Fix the README `createStream` and `createScreen` examples, which created an effect inside a JSX `ref` callback and threw `PRIMITIVE_IN_EFFECT_CALLBACK` in Solid 2 (#1143). They now keep the element in a signal via `ref={setVideo}` and assign `srcObject` from an effect in the component body. Documentation only, no source change. diff --git a/.changeset/mutation-observer-ref-callback-solid2.md b/.changeset/mutation-observer-ref-callback-solid2.md new file mode 100644 index 000000000..86aed847a --- /dev/null +++ b/.changeset/mutation-observer-ref-callback-solid2.md @@ -0,0 +1,7 @@ +--- +"@solid-primitives/mutation-observer": patch +--- + +Fix `mutationObserver(options, callback)` throwing `PRIMITIVE_IN_EFFECT_CALLBACK` when used as a JSX `ref` (#1143). + +The observer was created inside the ref callback, where Solid 2 forbids `onSettled`, `onCleanup` and other primitives. It is now created once when `mutationObserver(...)` is evaluated (the component body) and the ref callback only calls `observe`. It disconnects with the owner of that call, and one factory value can be used on several elements. diff --git a/.changeset/pagination-ref-callback-solid2.md b/.changeset/pagination-ref-callback-solid2.md new file mode 100644 index 000000000..bb47265e7 --- /dev/null +++ b/.changeset/pagination-ref-callback-solid2.md @@ -0,0 +1,7 @@ +--- +"@solid-primitives/pagination": patch +--- + +Fix the `createInfiniteScroll` loader throwing `CLEANUP_IN_FORBIDDEN_SCOPE` when used as a JSX `ref` callback (#1143). + +The loader called `onCleanup` inside the ref callback, which Solid 2 forbids. It now observes the element (unobserving a previous sentinel) and returns a teardown; observation is also torn down with the owner of `createInfiniteScroll`. diff --git a/README.md b/README.md index 4deb909c1..22fb81781 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ See the [migration guide](https://primitives.solidjs.community/migration) and th |[controlled-signal](https://github.com/solidjs-community/solid-primitives/tree/main/packages/controlled-signal#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createControllableSignal](https://github.com/solidjs-community/solid-primitives/tree/main/packages/controlled-signal#createcontrollablesignal)
[createControllableBooleanSignal](https://github.com/solidjs-community/solid-primitives/tree/main/packages/controlled-signal#createcontrollablebooleansignal)
[createControllableArraySignal](https://github.com/solidjs-community/solid-primitives/tree/main/packages/controlled-signal#createcontrollablearraysignal)
[createControllableSetSignal](https://github.com/solidjs-community/solid-primitives/tree/main/packages/controlled-signal#createcontrollablesetsignal)
[createToggleState](https://github.com/solidjs-community/solid-primitives/tree/main/packages/controlled-signal#createtogglestate)|[![SIZE](https://img.shields.io/badge/size-528_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/controlled-signal)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/controlled-signal?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/controlled-signal)|✓| |[deep](https://github.com/solidjs-community/solid-primitives/tree/main/packages/deep#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[trackDeep](https://github.com/solidjs-community/solid-primitives/tree/main/packages/deep#trackdeep)
[trackStore](https://github.com/solidjs-community/solid-primitives/tree/main/packages/deep#trackstore)
[captureStoreUpdates](https://github.com/solidjs-community/solid-primitives/tree/main/packages/deep#capturestoreupdates)|[![SIZE](https://img.shields.io/badge/size-954_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/deep)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/deep?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/deep)|✓| |[destructure](https://github.com/solidjs-community/solid-primitives/tree/main/packages/destructure#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[destructure](https://github.com/solidjs-community/solid-primitives/tree/main/packages/destructure#destructure)|[![SIZE](https://img.shields.io/badge/size-507_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/destructure)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/destructure?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/destructure)|✓| -|[lifecycle](https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createIsMounted](https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#createismounted)
[isHydrated](https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#ishydrated)
[onElementConnect](https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#onelementconnect)|[![SIZE](https://img.shields.io/badge/size-306_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/lifecycle)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/lifecycle?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/lifecycle)|✓| +|[lifecycle](https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createIsMounted](https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#createismounted)
[isHydrated](https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#ishydrated)
[onElementConnect](https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#onelementconnect)
[createConnectRef](https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#createconnectref)|[![SIZE](https://img.shields.io/badge/size-306_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/lifecycle)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/lifecycle?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/lifecycle)|✓| |[map](https://github.com/solidjs-community/solid-primitives/tree/main/packages/map#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[ReactiveMap](https://github.com/solidjs-community/solid-primitives/tree/main/packages/map#reactivemap)
[ReactiveWeakMap](https://github.com/solidjs-community/solid-primitives/tree/main/packages/map#reactiveweakmap)|[![SIZE](https://img.shields.io/badge/size-732_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/map)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/map?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/map)|✓| |[memo](https://github.com/solidjs-community/solid-primitives/tree/main/packages/memo#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createLatest](https://github.com/solidjs-community/solid-primitives/tree/main/packages/memo#createlatest)
[createLatestMany](https://github.com/solidjs-community/solid-primitives/tree/main/packages/memo#createlatestmany)
[createWritableMemo](https://github.com/solidjs-community/solid-primitives/tree/main/packages/memo#createwritablememo)
[createLazyMemo](https://github.com/solidjs-community/solid-primitives/tree/main/packages/memo#createlazymemo)
[createPureReaction](https://github.com/solidjs-community/solid-primitives/tree/main/packages/memo#createpurereaction)
[createMemoCache](https://github.com/solidjs-community/solid-primitives/tree/main/packages/memo#creatememocache)
[createReducer](https://github.com/solidjs-community/solid-primitives/tree/main/packages/memo#createreducer)|[![SIZE](https://img.shields.io/badge/size-855_B-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/memo)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/memo?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/memo)|✓| |[mutable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/mutable#readme)|[![STAGE](https://img.shields.io/endpoint?style=for-the-badge&label=&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives/blob/main/CONTRIBUTING.md#contribution-process)|[createMutable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/mutable#createmutable)
[modifyMutable](https://github.com/solidjs-community/solid-primitives/tree/main/packages/mutable#modifymutable)|[![SIZE](https://img.shields.io/badge/size-1.14_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/mutable)|[![VERSION](https://img.shields.io/npm/v/@solid-primitives/mutable?style=for-the-badge&label=)](https://www.npmjs.com/package/@solid-primitives/mutable)|✓| diff --git a/packages/active-element/README.md b/packages/active-element/README.md index de0cbb3cd..61a5e24ff 100644 --- a/packages/active-element/README.md +++ b/packages/active-element/README.md @@ -169,7 +169,7 @@ const [active, setActive] = createSignal(false) #### Definition ```ts -function focus(callback: (isActive: boolean) => void): (target: Element) => void; +function focus(callback: (isActive: boolean) => void): (target: Element) => VoidFunction; ``` ## Changelog diff --git a/packages/active-element/src/index.ts b/packages/active-element/src/index.ts index e651fdf92..2af0ed76c 100644 --- a/packages/active-element/src/index.ts +++ b/packages/active-element/src/index.ts @@ -1,4 +1,4 @@ -import { type Accessor, onCleanup } from "solid-js"; +import { type Accessor, getOwner, onCleanup } from "solid-js"; import { isServer } from "@solidjs/web"; import { createHydratableSignal } from "@solid-primitives/utils"; import { makeEventListener } from "@solid-primitives/event-listener"; @@ -55,17 +55,24 @@ export function createActiveElement(): Accessor { * const [active, setActive] = createSignal(false) * */ -export function focus(callback: (isActive: boolean) => void): (target: Element) => void { - if (isServer) return () => {}; - let cleanup: (() => void) | null = null; - onCleanup(() => cleanup?.()); +export function focus(callback: (isActive: boolean) => void): (target: Element) => VoidFunction { + if (isServer) return () => () => {}; + // One teardown per element, so a single focus() value can be attached to several elements. + const teardowns = new Set(); + // The runtime ignores a ref callback's return value, so the factory owner tears down too. + if (getOwner()) onCleanup(() => [...teardowns].forEach(t => t())); return (target: Element) => { callback(document.activeElement === target); - const c1 = makeEventListener(target, "blur", () => callback(false), true); - const c2 = makeEventListener(target, "focus", () => callback(true), true); - cleanup = () => { - c1(); - c2(); + const onBlur = () => callback(false); + const onFocus = () => callback(true); + target.addEventListener("blur", onBlur, true); + target.addEventListener("focus", onFocus, true); + const teardown = () => { + target.removeEventListener("blur", onBlur, true); + target.removeEventListener("focus", onFocus, true); + teardowns.delete(teardown); }; + teardowns.add(teardown); + return teardown; }; } diff --git a/packages/active-element/test/ref.test.tsx b/packages/active-element/test/ref.test.tsx new file mode 100644 index 000000000..69bc9182e --- /dev/null +++ b/packages/active-element/test/ref.test.tsx @@ -0,0 +1,101 @@ +import { describe, it, expect, vi, afterEach } from "vitest"; +import { render } from "@solidjs/web"; +import { focus } from "../src/index.js"; + +// Regression for #1143: focus() must work as a real JSX ref, where onCleanup is forbidden. + +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 = []; +}); + +const fire = (el: Element, type: "focus" | "blur") => el.dispatchEvent(new FocusEvent(type)); + +describe("focus as a JSX ref callback", () => { + it("mounts a static ref without throwing and reports focus changes", () => { + const cb = vi.fn(); + let container!: HTMLElement; + expect(() => { + ({ container } = mount(() => )); + }).not.toThrow(); + const input = container.querySelector("input")!; + expect(cb).toHaveBeenLastCalledWith(false); + fire(input, "focus"); + expect(cb).toHaveBeenLastCalledWith(true); + fire(input, "blur"); + expect(cb).toHaveBeenLastCalledWith(false); + }); + + it("works inside an array of refs", () => { + const cb = vi.fn(); + const other = vi.fn(); + const { container } = mount(() => ); + const input = container.querySelector("input")!; + expect(other).toHaveBeenCalledWith(input); + fire(input, "focus"); + expect(cb).toHaveBeenLastCalledWith(true); + }); + + it("keeps per-element state when one focus() value is attached to two elements", () => { + const cb = vi.fn(); + const { container, unmount } = mount(() => { + const f = focus(cb); + return ( +
+ + +
+ ); + }); + const a = container.querySelector("#a")!; + const b = container.querySelector("#b")!; + cb.mockClear(); + fire(a, "focus"); + fire(b, "focus"); + expect(cb).toHaveBeenCalledTimes(2); + unmount(); + cb.mockClear(); + fire(a, "focus"); + fire(b, "focus"); + expect(cb).not.toHaveBeenCalled(); + }); + + it("removes listeners when the owner is disposed", () => { + const cb = vi.fn(); + const { container, unmount } = mount(() => ); + const input = container.querySelector("input")!; + unmount(); + cb.mockClear(); + fire(input, "focus"); + fire(input, "blur"); + expect(cb).not.toHaveBeenCalled(); + }); + + it("does not throw without an owner and returns a teardown", () => { + const cb = vi.fn(); + const el = document.createElement("input"); + const ref = focus(cb) as (t: Element) => unknown; + const teardown = ref(el) as () => void; + fire(el, "focus"); + expect(cb).toHaveBeenLastCalledWith(true); + teardown(); + teardown(); + cb.mockClear(); + fire(el, "focus"); + expect(cb).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cursor/README.md b/packages/cursor/README.md index 67ded8cc0..ee933b20a 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -229,7 +229,7 @@ createDragCursor(el, { grab: "crosshair", grabbing: "move" }); ## `cursorRef` -A ref factory for setting a cursor inline in JSX. Accepts a static cursor value or a reactive signal. The cursor is removed when the component unmounts. +A ref factory for setting a cursor inline in JSX. Accepts a static cursor value or a reactive signal. Call it in the component body. The cursor is restored when the element unmounts or the component is disposed, and one `cursorRef` value can be attached to several elements. ```tsx repl import { render } from "@solidjs/web"; diff --git a/packages/cursor/src/index.ts b/packages/cursor/src/index.ts index 23479fa6b..e44f634fe 100644 --- a/packages/cursor/src/index.ts +++ b/packages/cursor/src/index.ts @@ -186,10 +186,11 @@ export function createDragCursor( } /** - * Returns a ref callback that sets a cursor on the element it is attached to. + * Returns a ref callback that sets a cursor on the element(s) it is attached to. * - * Accepts a static cursor value or a reactive signal. The cursor is removed when the - * component unmounts. + * Accepts a static cursor value or a reactive signal. Call it in the component body: the + * cursor is restored when the element unmounts or the component is disposed. One returned + * callback can be attached to several elements. * * @example * ```tsx @@ -201,6 +202,25 @@ export function createDragCursor( *
...
* ``` */ -export function cursorRef(cursor: MaybeAccessor): (el: HTMLElement) => void { - return el => createElementCursor(el, cursor); +export function cursorRef( + cursor: MaybeAccessor, +): (el: HTMLElement) => VoidFunction { + if (isServer) return () => noop; + + // The ref callback can't create primitives, so the effect lives here and the callback only edits this list. + const [els, setEls] = createSignal([], { ownedWrite: true }); + + createEffect( + () => ({ list: els(), cursorValue: access(cursor) }), + ({ list, cursorValue }) => { + const restores = list.map(el => makeElementCursor(el, cursorValue)); + return () => restores.reverse().forEach(restore => restore()); + }, + ); + + return el => { + setEls(list => [...list, el]); + // The runtime ignores this return value; the owner disposal above restores the cursor. + return () => setEls(list => list.filter(item => item !== el)); + }; } diff --git a/packages/cursor/test/ref.test.tsx b/packages/cursor/test/ref.test.tsx new file mode 100644 index 000000000..aa3fa4ae6 --- /dev/null +++ b/packages/cursor/test/ref.test.tsx @@ -0,0 +1,89 @@ +import { describe, it, expect, afterEach } from "vitest"; +import { createRoot, createSignal, flush } from "solid-js"; +import { render } from "@solidjs/web"; +import { cursorRef, type CursorProperty } from "../src/index.js"; + +// Regression for #1143: cursorRef must work as a real JSX ref (no primitives created in the callback). + +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("cursorRef as a JSX ref", () => { + it("applies a static cursor and restores it on unmount", () => { + const { container, unmount } = mount(() => ( +
+ )); + flush(); + const el = container.firstElementChild as HTMLElement; + expect(el.style.cursor).toBe("pointer"); + unmount(); + expect(el.style.cursor).toBe("text"); + }); + + it("follows a reactive cursor", () => { + const [cursor, setCursor] = createSignal("pointer"); + const { container } = mount(() =>
); + flush(); + const el = container.firstElementChild as HTMLElement; + expect(el.style.cursor).toBe("pointer"); + setCursor("help"); + flush(); + expect(el.style.cursor).toBe("help"); + }); + + it("supports one cursorRef value on several elements", () => { + const { container, unmount } = mount(() => { + const ref = cursorRef("grab"); + return ( + <> +
+ + + ); + }); + flush(); + const [a, b] = Array.from(container.children) as HTMLElement[]; + expect(a.style.cursor).toBe("grab"); + expect(b.style.cursor).toBe("grab"); + unmount(); + expect(a.style.cursor).toBe(""); + expect(b.style.cursor).toBe(""); + }); + + it("does not throw when evaluated outside an owner", () => { + const el = document.createElement("div"); + let teardown: unknown; + expect(() => { + teardown = cursorRef("pointer")(el); + }).not.toThrow(); + if (typeof teardown === "function") teardown(); + }); + + it("restores when the owner is disposed directly", () => { + const el = document.createElement("div"); + const dispose = createRoot(d => { + cursorRef("wait")(el); + return d; + }); + flush(); + expect(el.style.cursor).toBe("wait"); + dispose(); + expect(el.style.cursor).toBe(""); + }); +}); diff --git a/packages/lifecycle/README.md b/packages/lifecycle/README.md index 1bbfabd6a..219fd0377 100644 --- a/packages/lifecycle/README.md +++ b/packages/lifecycle/README.md @@ -15,6 +15,7 @@ Package providing extra layer of lifecycle primitives for Solid. - [`createIsMounted`](#createismounted) - Returns a boolean signal indicating whether the component is mounted or not. - [`isHydrated`](#ishydrated) - A signal with the same behavior as [`isHydrating`](#ishydrating) but this one focused only on client-side updates. - [`onElementConnect`](#onelementconnect) - Calls the given callback when the target element is connected to the DOM. +- [`createConnectRef`](#createconnectref) - `ref` factory that calls the callback when each element is connected to the DOM. ## Installation @@ -146,7 +147,7 @@ export const ClientOnly: FlowComponent = props => { ```tsx repl import { render } from "@solidjs/web"; import { createSignal, Show } from "solid-js"; -import { onElementConnect } from "@solid-primitives/lifecycle"; +import { createConnectRef } from "@solid-primitives/lifecycle"; function Demo() { const [show, setShow] = createSignal(true); @@ -156,7 +157,7 @@ function Demo() {

connected {connects()} times

-
onElementConnect(el, () => setConnects(n => n + 1))}>Connected element
+
setConnects(n => n + 1))}>Connected element
); @@ -174,17 +175,16 @@ However, it is not certain that the elements are actually connected to the DOM w > > If you are not sure, you can use `onElementConnect` instead of `onSettled` to make sure that you are caling your callback when the elements are connected to the DOM. +Solid does not allow `onCleanup` (or creating primitives) inside a `ref` callback, so `onElementConnect` never calls it. +The observer disconnects itself once the element connects, and the function returns a disposer to stop waiting earlier. +In a `ref`, use [`createConnectRef`](#createconnectref), which also stops waiting when the owner is disposed. + ```tsx
{ // often false, but will be true during hydration el.isConnected; - onSettled(() => { - // often true, but will be false if the executed component is not actually getting rendered - el.isConnected; - }); - onElementConnect(el, () => { // always true el.isConnected; @@ -193,6 +193,21 @@ However, it is not certain that the elements are actually connected to the DOM w /> ``` +In an owned scope (component body, effect), tie the wait to the owner yourself: + +```tsx +onCleanup(onElementConnect(el, () => {})); +``` + +## `createConnectRef` + +Creates a `ref` callback that calls the given function with each element once it is connected to the DOM. +Call it in the component body: the pending observers are disconnected when the component is disposed. + +```tsx +
el.isConnected /* always true */)} /> +``` + ## Changelog See [CHANGELOG.md](./CHANGELOG.md) diff --git a/packages/lifecycle/package.json b/packages/lifecycle/package.json index 38388ccf8..ea5326035 100644 --- a/packages/lifecycle/package.json +++ b/packages/lifecycle/package.json @@ -19,7 +19,8 @@ "list": [ "createIsMounted", "isHydrated", - "onElementConnect" + "onElementConnect", + "createConnectRef" ], "category": "Reactivity", "gzip": 306 diff --git a/packages/lifecycle/src/index.ts b/packages/lifecycle/src/index.ts index 5cc677c75..f7207eb67 100644 --- a/packages/lifecycle/src/index.ts +++ b/packages/lifecycle/src/index.ts @@ -1,4 +1,4 @@ -import { type Accessor, createSignal, getObserver, onCleanup, onSettled } from "solid-js"; +import { type Accessor, createSignal, getObserver, getOwner, onCleanup, onSettled } from "solid-js"; import { sharedConfig } from "solid-js/internal"; import { isServer } from "@solidjs/web"; @@ -39,28 +39,66 @@ export const isHydrated = (): boolean => /** * Calls the {@link fn} callback when the {@link el} is connected to the DOM. + * + * Safe inside a ref callback: it never calls `onCleanup`, which Solid forbids there. + * The observer disconnects itself once the element connects. + * To also stop waiting when the owner is disposed, use {@link createConnectRef} or `onCleanup(onElementConnect(...))`. * @param el target element * @param fn callback + * @returns a function that stops waiting for the connection * @example * ```tsx - *
{ - * el.isConnected // => often false - * onMount(() => { - * el.isConnected // => often true - * }) - * onConnect(el, () => { - * el.isConnected // => always true - * }) - * }} /> + *
{ + * el.isConnected // => always true + * })} /> * ``` - * @see https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#onConnect + * @see https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#onElementConnect */ -export function onElementConnect(el: Element, fn: VoidFunction): void { - if (isServer) return; - if (el.isConnected) return fn(); +export function onElementConnect(el: Element, fn: VoidFunction): VoidFunction { + if (isServer) return noop; + if (el.isConnected) { + fn(); + return noop; + } const observer: ResizeObserver = new ResizeObserver( () => el.isConnected && (observer.disconnect(), fn()), ); observer.observe(el); - onCleanup(() => observer.disconnect()); + return () => observer.disconnect(); } + +/** + * Creates a `ref` callback that calls {@link fn} with each element once it is connected to the DOM. + * Call it in the component body: pending observers are disconnected when the owner is disposed. + * @example + * ```tsx + *
console.log(el.isConnected))} /> + * ``` + * @see https://github.com/solidjs-community/solid-primitives/tree/main/packages/lifecycle#createConnectRef + */ +export function createConnectRef( + fn: (el: T) => void, +): (el: T) => void { + if (isServer) return noop; + const stops = new Map(); + // The ref callback can't call onCleanup, so the factory registers the teardown. + if (getOwner()) { + onCleanup(() => { + stops.forEach(stop => stop()); + stops.clear(); + }); + } + return el => { + if (el.isConnected) return fn(el); + const key = {}; + stops.set( + key, + onElementConnect(el, () => { + stops.delete(key); + fn(el); + }), + ); + }; +} + +const noop = (): void => {}; diff --git a/packages/lifecycle/test/ref.test.tsx b/packages/lifecycle/test/ref.test.tsx new file mode 100644 index 000000000..d6e95a4e4 --- /dev/null +++ b/packages/lifecycle/test/ref.test.tsx @@ -0,0 +1,128 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { render } from "@solidjs/web"; +import { onElementConnect, createConnectRef } from "../src/index.js"; + +// Regression for #1143: onCleanup is forbidden inside a ref callback, so mount real JSX refs. + +class FakeResizeObserver { + static instances: FakeResizeObserver[] = []; + observing = new Set(); + constructor(public cb: () => void) { + FakeResizeObserver.instances.push(this); + } + observe(el: Element) { + this.observing.add(el); + } + disconnect() { + this.observing.clear(); + } + trigger() { + if (this.observing.size) this.cb(); + } +} +const live = () => FakeResizeObserver.instances.filter(o => o.observing.size); +const fire = () => FakeResizeObserver.instances.forEach(o => o.trigger()); + +beforeEach(() => { + FakeResizeObserver.instances = []; + vi.stubGlobal("ResizeObserver", FakeResizeObserver); +}); +afterEach(() => vi.unstubAllGlobals()); + +// Render into a detached container so the element is not connected yet. +function mountDetached(App: () => any) { + const container = document.createElement("div"); + const dispose = render(App, container); + return { container, dispose }; +} + +describe("onElementConnect as a JSX ref callback", () => { + it("does not throw and calls fn once when the element connects", () => { + const fn = vi.fn(); + let m!: ReturnType; + expect(() => { + m = mountDetached(() =>
void onElementConnect(el, fn)} />); + }).not.toThrow(); + expect(fn).not.toHaveBeenCalled(); + expect(live()).toHaveLength(1); + + document.body.appendChild(m.container); + fire(); + expect(fn).toHaveBeenCalledTimes(1); + expect(live()).toHaveLength(0); + fire(); + expect(fn).toHaveBeenCalledTimes(1); + m.dispose(); + m.container.remove(); + }); + + it("calls fn immediately for a connected element", () => { + const fn = vi.fn(); + const m = mountDetached(() => ( +
{ + document.body.appendChild(el); + onElementConnect(el, fn); + }} + /> + )); + expect(fn).toHaveBeenCalledTimes(1); + m.dispose(); + }); + + it("returns a disposer that stops observing", () => { + const fn = vi.fn(); + let stop!: VoidFunction; + const m = mountDetached(() =>
void (stop = onElementConnect(el, fn))} />); + stop(); + stop(); + expect(live()).toHaveLength(0); + document.body.appendChild(m.container); + fire(); + expect(fn).not.toHaveBeenCalled(); + m.dispose(); + m.container.remove(); + }); +}); + +describe("createConnectRef", () => { + it("calls fn once per element, without throwing", () => { + const fn = vi.fn(); + const m = mountDetached(() => { + const ref = createConnectRef(fn); + return ( +
+ + +
+ ); + }); + expect(live()).toHaveLength(2); + document.body.appendChild(m.container); + fire(); + expect(fn).toHaveBeenCalledTimes(2); + expect(live()).toHaveLength(0); + m.dispose(); + m.container.remove(); + }); + + it("stops observing when the owner is disposed before the element connects", () => { + const fn = vi.fn(); + const m = mountDetached(() =>
); + expect(live()).toHaveLength(1); + m.dispose(); + expect(live()).toHaveLength(0); + document.body.appendChild(m.container); + fire(); + expect(fn).not.toHaveBeenCalled(); + m.container.remove(); + }); + + it("works without an owner", () => { + const fn = vi.fn(); + const ref = createConnectRef(fn); + const el = document.createElement("div"); + expect(() => ref(el)).not.toThrow(); + expect(live()).toHaveLength(1); + }); +}); diff --git a/packages/mediastream/README.md b/packages/mediastream/README.md index c7fbc8a0c..80219e0ce 100644 --- a/packages/mediastream/README.md +++ b/packages/mediastream/README.md @@ -44,19 +44,25 @@ const [stream, { mute, stop }] = createStream(streamSource); The stream stops automatically when the reactive owner is disposed. Wrap in `` to handle the loading state: ```tsx -import { Loading } from "@solidjs/web"; +import { createEffect, createSignal, Loading } from "solid-js"; -const [stream] = createStream({ video: true }); +function Camera() { + const [stream] = createStream({ video: true }); + const [video, setVideo] = createSignal(); + + // a ref callback can't create effects, so keep the element in a signal + createEffect( + () => [video(), stream()] as const, + ([el, s]) => { + if (el) el.srcObject = s ?? null; + }, + ); + + return