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..5dc1484c1 --- /dev/null +++ b/.changeset/cursor-ref-callback-solid2.md @@ -0,0 +1,9 @@ +--- +"@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. + +`cursorRef` also mints a matching owner on the server, so the hydration ids of elements rendered after it stay aligned with the client. diff --git a/.changeset/form-ref-callbacks-solid2.md b/.changeset/form-ref-callbacks-solid2.md new file mode 100644 index 000000000..f8847f3b5 --- /dev/null +++ b/.changeset/form-ref-callbacks-solid2.md @@ -0,0 +1,11 @@ +--- +"@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. + +A `bind()` callback created without an owner is also torn down, together with its sync root, when the owner that mounted the ref is disposed. 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..22079f215 --- /dev/null +++ b/.changeset/mediastream-ref-callback-solid2.md @@ -0,0 +1,7 @@ +--- +"@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. + +The examples also no longer wrap in `` (`stream()` is a plain signal, so it never shows a fallback; they render their own loading state) and `createScreen` now starts from a click, since `getDisplayMedia` requires a user gesture. The same inaccurate `` claim is removed from the JSDoc. diff --git a/.changeset/mutation-observer-ref-callback-solid2.md b/.changeset/mutation-observer-ref-callback-solid2.md new file mode 100644 index 000000000..a3a36f12d --- /dev/null +++ b/.changeset/mutation-observer-ref-callback-solid2.md @@ -0,0 +1,9 @@ +--- +"@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. + +`createMutationObserver` (and so `mutationObserver`) also mints a matching owner on the server, so the hydration ids of elements rendered after it stay aligned with the client. 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/hydration.test.tsx b/packages/active-element/test/hydration.test.tsx new file mode 100644 index 000000000..852853705 --- /dev/null +++ b/packages/active-element/test/hydration.test.tsx @@ -0,0 +1,46 @@ +import { describe, it, expect, afterEach } from "vitest"; +import { + renderHydrationRoundTrip, + type HydrationRoundTripResult, +} from "../../../scripts/test-utils/hydration-harness.ts"; + +// A client-side owner created in the factory needs a matching server owner, or the hydration +// ids of everything after it shift and later elements miss their server-rendered twins. +const app = (imports: string, setup: string, tag: string) => ` +import { createUniqueId } from "solid-js"; +${imports} +export default function App() { + ${setup} + const id = createUniqueId(); + return ( +
+ <${tag} id="a" ref={ref}>box + {id} +
+ ); +} +`; + +let result: HydrationRoundTripResult | undefined; +afterEach(() => { + result?.cleanup(); + result = undefined; +}); + +async function expectAligned(source: string) { + result = await renderHydrationRoundTrip(source, import.meta.dirname); + const serverId = /id="uid">([^<]*) { + it("keeps hydration ids aligned", () => + expectAligned( + app( + `import { focus } from "@solid-primitives/active-element";`, + `const ref = focus(() => {});`, + "input", + ), + )); +}); 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..9ee60be67 100644 --- a/packages/cursor/src/index.ts +++ b/packages/cursor/src/index.ts @@ -1,4 +1,5 @@ -import { type Accessor, createEffect, createSignal } from "solid-js"; +// @ts-expect-error createOwner is exported at runtime but missing from the solid-js 2.0.0 types +import { type Accessor, createEffect, createOwner, createSignal } from "solid-js"; import { isServer } from "@solidjs/web"; import { access, noop, type FalsyValue, type MaybeAccessor } from "@solid-primitives/utils"; import { type CursorProperty } from "./types.ts"; @@ -186,10 +187,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 +203,29 @@ 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) { + // Match the client's effect owner so later siblings keep the same hydration ids. + createOwner(); + 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/hydration.test.tsx b/packages/cursor/test/hydration.test.tsx new file mode 100644 index 000000000..fdfa19c8e --- /dev/null +++ b/packages/cursor/test/hydration.test.tsx @@ -0,0 +1,46 @@ +import { describe, it, expect, afterEach } from "vitest"; +import { + renderHydrationRoundTrip, + type HydrationRoundTripResult, +} from "../../../scripts/test-utils/hydration-harness.ts"; + +// A client-side owner created in the factory needs a matching server owner, or the hydration +// ids of everything after it shift and later elements miss their server-rendered twins. +const app = (imports: string, setup: string, tag: string) => ` +import { createUniqueId } from "solid-js"; +${imports} +export default function App() { + ${setup} + const id = createUniqueId(); + return ( +
+ <${tag} id="a" ref={ref}>box + {id} +
+ ); +} +`; + +let result: HydrationRoundTripResult | undefined; +afterEach(() => { + result?.cleanup(); + result = undefined; +}); + +async function expectAligned(source: string) { + result = await renderHydrationRoundTrip(source, import.meta.dirname); + const serverId = /id="uid">([^<]*) { + it("keeps hydration ids aligned for later siblings", () => + expectAligned( + app( + `import { cursorRef } from "@solid-primitives/cursor";`, + `const ref = cursorRef("pointer");`, + "span", + ), + )); +}); 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/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..5eb00e647 100644 --- a/packages/form/src/form.ts +++ b/packages/form/src/form.ts @@ -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, @@ -393,48 +394,105 @@ 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. + // 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(); - 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); + + // Ownerless factory: once this callback returns (onCleanup is forbidden inside it), tie the + // attachment to the owner that mounted the ref. + if (!owned) { + const mounting = getOwner(); + if (mounting) + queueMicrotask(() => runWithOwner(mounting, () => onCleanup(attachment.teardown))); + } - 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; - }); + // 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, () => + createRoot(d => { + createEffect(f.value, syncAll); + return d; + }), + ); - const off1 = makeEventListener(el, checkable ? "change" : "input", () => - f._setValue(checkable ? el.checked : el.value), - ); - const off2 = makeEventListener(el, "blur", () => f._setTouched(true)); + syncOne(attachment, untrack(f.value)); - return () => { - off1(); - off2(); - disposeEffect(); - }; + return attachment.teardown; }; + + // The runtime 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 { diff --git a/packages/form/test/bind-multiple.test.ts b/packages/form/test/bind-multiple.test.ts new file mode 100644 index 000000000..726772fc0 --- /dev/null +++ b/packages/form/test/bind-multiple.test.ts @@ -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>; + 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>; + 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(); + }); + }); +}); diff --git a/packages/form/test/hydration.test.tsx b/packages/form/test/hydration.test.tsx index ddfddff8b..5938d97f5 100644 --- a/packages/form/test/hydration.test.tsx +++ b/packages/form/test/hydration.test.tsx @@ -55,3 +55,91 @@ 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.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"); + }); +}); + +// A client-side effect owner created by bind() needs a matching server owner, or later hydration +// ids shift and elements miss their server-rendered twins. +describe("form.bind() hydration ids", () => { + let result: HydrationRoundTripResult | undefined; + + afterEach(() => { + result?.cleanup(); + result = undefined; + }); + + it("stay aligned for elements after the bound input", async () => { + result = await renderHydrationRoundTrip( + ` +import { createUniqueId } from "solid-js"; +import { createForm } from "@solid-primitives/form"; +export default function App() { + const form = createForm({ fields: { email: { initial: "" } } }); + const ref = form.bind("email"); + const id = createUniqueId(); + return ( +
+ + {id} +
+ ); +} +`, + import.meta.dirname, + ); + const serverId = /id="uid">([^<]*) 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 + 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("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("tears down an ownerless attachment when the owner that mounted it is disposed", async () => { + let form!: ReturnType>; + createRoot(d => { + form = createForm({ fields: { email: { initial: "x" } } }); + return d; + }); + const attach = form.bind("email"); // no owner here + + const first = mount(() => ); + await Promise.resolve(); // the teardown is registered right after the ref callback returns + const a = first.container.querySelector("input")!; + first.unmount(); + + form.fields.email.setValue("after"); + flush(); + expect(a.value).not.toBe("after"); + a.value = "typed"; + a.dispatchEvent(new Event("input", { bubbles: true })); + flush(); + expect(form.fields.email.value()).toBe("after"); + + // the same callback can be mounted again and only the new element is kept in sync + const second = mount(() => ); + await Promise.resolve(); + const b = second.container.querySelector("input")!; + expect(b.value).toBe("after"); + form.fields.email.setValue("again"); + flush(); + expect(b.value).toBe("again"); + expect(a.value).not.toBe("again"); + }); + + 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/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/hydration.test.tsx b/packages/lifecycle/test/hydration.test.tsx new file mode 100644 index 000000000..27ce7ff65 --- /dev/null +++ b/packages/lifecycle/test/hydration.test.tsx @@ -0,0 +1,46 @@ +import { describe, it, expect, afterEach } from "vitest"; +import { + renderHydrationRoundTrip, + type HydrationRoundTripResult, +} from "../../../scripts/test-utils/hydration-harness.ts"; + +// A client-side owner created in the factory needs a matching server owner, or the hydration +// ids of everything after it shift and later elements miss their server-rendered twins. +const app = (imports: string, setup: string, tag: string) => ` +import { createUniqueId } from "solid-js"; +${imports} +export default function App() { + ${setup} + const id = createUniqueId(); + return ( +
+ <${tag} id="a" ref={ref}>box + {id} +
+ ); +} +`; + +let result: HydrationRoundTripResult | undefined; +afterEach(() => { + result?.cleanup(); + result = undefined; +}); + +async function expectAligned(source: string) { + result = await renderHydrationRoundTrip(source, import.meta.dirname); + const serverId = /id="uid">([^<]*) { + it("keeps hydration ids aligned", () => + expectAligned( + app( + `import { createConnectRef } from "@solid-primitives/lifecycle";`, + `const ref = createConnectRef(() => {});`, + "div", + ), + )); +}); 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..4c9885cc9 100644 --- a/packages/mediastream/README.md +++ b/packages/mediastream/README.md @@ -41,23 +41,32 @@ const [stream, { mute, stop }] = createStream(streamSource); - `mute(muted?)` — mutes the stream; pass `false` to unmute - `stop()` — stops the stream immediately -The stream stops automatically when the reactive owner is disposed. Wrap in `` to handle the loading state: +The stream stops automatically when the reactive owner is disposed. `stream()` is `undefined` until the request resolves. It is a plain signal, not a pending computation, so `` shows no fallback; render your own loading state: ```tsx -import { Loading } from "@solidjs/web"; - -const [stream] = createStream({ video: true }); - -Requesting camera...

}> -
; +import { createEffect, createSignal, Show } from "solid-js"; + +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 ( + <> + +

Requesting camera...

+
+