From afcac22e4dfff8b272906d193df95ffdf783c206 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Fri, 2 Oct 2026 08:36:45 -0400 Subject: [PATCH] Fix useResponsiveColumns observer leak; use VueUse for v2 resize observers (#5019) --- frontend/src/test-utils/resizeObserver.ts | 75 +++++++++++++++++ .../components/Gallery/SelectionBar.test.ts | 38 ++++++++- .../v2/components/Gallery/SelectionBar.vue | 28 +++---- .../useResponsiveColumns/index.test.ts | 80 +++++++++++++++++++ .../composables/useResponsiveColumns/index.ts | 39 +++------ frontend/src/v2/lib/forms/RSelect/RSelect.vue | 19 +---- frontend/src/v2/lib/media/RBox3D/RBox3D.vue | 14 ++-- 7 files changed, 216 insertions(+), 77 deletions(-) create mode 100644 frontend/src/test-utils/resizeObserver.ts create mode 100644 frontend/src/v2/composables/useResponsiveColumns/index.test.ts diff --git a/frontend/src/test-utils/resizeObserver.ts b/frontend/src/test-utils/resizeObserver.ts new file mode 100644 index 000000000..154a936f9 --- /dev/null +++ b/frontend/src/test-utils/resizeObserver.ts @@ -0,0 +1,75 @@ +import { vi } from "vitest"; + +// happy-dom's ResizeObserver never fires, so tests that depend on resizes +// swap in this one and deliver them by hand. +class FakeResizeObserver implements ResizeObserver { + static instances = new Set(); + readonly targets = new Set(); + readonly callback: ResizeObserverCallback; + + constructor(callback: ResizeObserverCallback) { + this.callback = callback; + FakeResizeObserver.instances.add(this); + } + + observe(el: Element) { + this.targets.add(el); + } + + unobserve(el: Element) { + this.targets.delete(el); + } + + disconnect() { + this.targets.clear(); + } +} + +interface Size { + width: number; + height: number; +} + +function rect({ width, height }: Size): DOMRectReadOnly { + const box = { x: 0, y: 0, width, height }; + return { + ...box, + top: 0, + left: 0, + right: width, + bottom: height, + toJSON: () => box, + }; +} + +function boxSize({ width, height }: Size): ResizeObserverSize[] { + return [{ inlineSize: width, blockSize: height }]; +} + +/** Installs the fake for the current test; undo with `vi.unstubAllGlobals()`. */ +export function stubResizeObserver() { + FakeResizeObserver.instances.clear(); + vi.stubGlobal("ResizeObserver", FakeResizeObserver); + + return { + /** Reports `el` at the given content size (and border-box size, which + * defaults to the same) to every observer watching it. */ + resize(el: Element, width: number, height = 0, border?: Size) { + const content = { width, height }; + const entry: ResizeObserverEntry = { + target: el, + contentRect: rect(content), + contentBoxSize: boxSize(content), + borderBoxSize: boxSize(border ?? content), + devicePixelContentBoxSize: boxSize(content), + }; + for (const observer of FakeResizeObserver.instances) { + if (observer.targets.has(el)) observer.callback([entry], observer); + } + }, + /** Whether any observer is still watching `el`. */ + isObserved(el: Element) { + return [...FakeResizeObserver.instances].some((o) => o.targets.has(el)); + }, + }; +} diff --git a/frontend/src/v2/components/Gallery/SelectionBar.test.ts b/frontend/src/v2/components/Gallery/SelectionBar.test.ts index 290a597ba..7ab5ef07d 100644 --- a/frontend/src/v2/components/Gallery/SelectionBar.test.ts +++ b/frontend/src/v2/components/Gallery/SelectionBar.test.ts @@ -1,15 +1,17 @@ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; import { createPinia, setActivePinia } from "pinia"; -import { beforeEach, describe, expect, it, vi } from "vitest"; -import { ref } from "vue"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { nextTick, ref } from "vue"; import storeAuth from "@/stores/auth"; import storeCollections, { type Collection } from "@/stores/collections"; import storeRoms, { type SimpleRom } from "@/stores/roms"; +import { stubResizeObserver } from "@/test-utils/resizeObserver"; import { collectionFixture } from "@/utils/collection.fixtures"; import { userFixture } from "@/utils/user.fixtures"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; import storeGallerySelection from "@/v2/stores/gallerySelection"; import SelectionBar from "./SelectionBar.vue"; +import { selectionBarOutline } from "./selectionBarOutline"; const { addRomsToCollection, @@ -388,3 +390,35 @@ describe("SelectionBar bulk status", () => { expect(updateUserRomProps).toHaveBeenCalledTimes(2); }); }); + +describe("SelectionBar outline", () => { + beforeEach(() => { + setActivePinia(createPinia()); + storeAuth().setCurrentUser(userFixture()); + }); + afterEach(() => vi.unstubAllGlobals()); + + it("draws the outline from the bar's and notch's measured sizes", async () => { + const observer = stubResizeObserver(); + const wrapper = mountBar(); + await flushPromises(); + expect(wrapper.find(".selection-bar__outline").exists()).toBe(false); + + // Padding makes each border box bigger than its content box; the outline + // has to trace the border box. + observer.resize(wrapper.get(".selection-bar").element, 580, 40, { + width: 600, + height: 48, + }); + observer.resize(wrapper.get(".selection-bar__notch").element, 48, 32, { + width: 64, + height: 40, + }); + await nextTick(); + + const expected = selectionBarOutline({ w: 600, h: 48 }, { w: 64, h: 40 }); + const svg = wrapper.get(".selection-bar__outline"); + expect(svg.attributes("width")).toBe(String(expected?.width)); + expect(svg.get("path").attributes("d")).toBe(expected?.d); + }); +}); diff --git a/frontend/src/v2/components/Gallery/SelectionBar.vue b/frontend/src/v2/components/Gallery/SelectionBar.vue index 3fd649ff1..e4d538693 100644 --- a/frontend/src/v2/components/Gallery/SelectionBar.vue +++ b/frontend/src/v2/components/Gallery/SelectionBar.vue @@ -45,8 +45,9 @@ import { RTooltip, RDivider, } from "@v2/lib"; +import { useElementSize } from "@vueuse/core"; import type { Emitter } from "mitt"; -import { computed, inject, onBeforeUnmount, onMounted, ref } from "vue"; +import { computed, inject, ref } from "vue"; import { useI18n } from "vue-i18n"; import type { RomUserData, RomUserStatus } from "@/__generated__"; import { useFavoriteToggle } from "@/composables/useFavoriteToggle"; @@ -332,26 +333,15 @@ const notchStyle = { const barEl = ref(null); const notchEl = ref(null); -const barSize = ref({ w: 0, h: 0 }); -const notchSize = ref({ w: 0, h: 0 }); - -function measure() { - const bar = barEl.value; - const notch = notchEl.value; - if (bar) barSize.value = { w: bar.offsetWidth, h: bar.offsetHeight }; - if (notch) notchSize.value = { w: notch.offsetWidth, h: notch.offsetHeight }; -} - // The bar's width follows its buttons and the hill's follows the digit count, // so both are watched rather than measured once. -let sizeObserver: ResizeObserver | null = null; -onMounted(() => { - measure(); - sizeObserver = new ResizeObserver(measure); - if (barEl.value) sizeObserver.observe(barEl.value); - if (notchEl.value) sizeObserver.observe(notchEl.value); -}); -onBeforeUnmount(() => sizeObserver?.disconnect()); +const bar = useElementSize(barEl, undefined, { box: "border-box" }); +const notch = useElementSize(notchEl, undefined, { box: "border-box" }); +const barSize = computed(() => ({ w: bar.width.value, h: bar.height.value })); +const notchSize = computed(() => ({ + w: notch.width.value, + h: notch.height.value, +})); const outline = computed(() => selectionBarOutline(barSize.value, notchSize.value), diff --git a/frontend/src/v2/composables/useResponsiveColumns/index.test.ts b/frontend/src/v2/composables/useResponsiveColumns/index.test.ts new file mode 100644 index 000000000..9e759e89b --- /dev/null +++ b/frontend/src/v2/composables/useResponsiveColumns/index.test.ts @@ -0,0 +1,80 @@ +import { mount } from "@vue/test-utils"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { defineComponent, h, nextTick, ref } from "vue"; +import { stubResizeObserver } from "@/test-utils/resizeObserver"; +import { useResponsiveColumns } from "./index"; + +let observer: ReturnType; +let layout: ReturnType; +const cardWidth = ref(158); + +const Host = defineComponent({ + props: { swapped: { type: Boolean, default: false } }, + setup(props) { + const el = ref(null); + layout = useResponsiveColumns(el, { cardWidth: () => cardWidth.value }); + return () => h(props.swapped ? "section" : "div", { ref: el }); + }, +}); + +async function mountHost() { + const wrapper = mount(Host); + // The observer binds once the template ref lands. + await nextTick(); + return wrapper; +} + +describe("useResponsiveColumns", () => { + beforeEach(() => { + observer = stubResizeObserver(); + cardWidth.value = 158; + }); + afterEach(() => vi.unstubAllGlobals()); + + it("derives the column count from the observed width", async () => { + const wrapper = await mountHost(); + + // floor((700 + 12) / (158 + 12)) = 4 + observer.resize(wrapper.element, 700); + expect(layout.columns.value).toBe(4); + expect(layout.usableWidth.value).toBe(700); + + observer.resize(wrapper.element, 340); + expect(layout.columns.value).toBe(2); + }); + + it("recomputes from the last width when a reactive option changes", async () => { + const wrapper = await mountHost(); + observer.resize(wrapper.element, 700); + + cardWidth.value = 100; + await nextTick(); + + // floor((700 + 12) / (100 + 12)) = 6 + expect(layout.columns.value).toBe(6); + }); + + it("follows the bound element when it is swapped", async () => { + const wrapper = await mountHost(); + const first = wrapper.element; + + await wrapper.setProps({ swapped: true }); + await nextTick(); + const second = wrapper.element; + + expect(second).not.toBe(first); + expect(observer.isObserved(first)).toBe(false); + observer.resize(second, 340); + expect(layout.columns.value).toBe(2); + }); + + it("stops observing once unmounted", async () => { + const wrapper = await mountHost(); + const el = wrapper.element; + expect(observer.isObserved(el)).toBe(true); + + wrapper.unmount(); + + expect(observer.isObserved(el)).toBe(false); + }); +}); diff --git a/frontend/src/v2/composables/useResponsiveColumns/index.ts b/frontend/src/v2/composables/useResponsiveColumns/index.ts index 5ecf008fb..47161dc8e 100644 --- a/frontend/src/v2/composables/useResponsiveColumns/index.ts +++ b/frontend/src/v2/composables/useResponsiveColumns/index.ts @@ -5,14 +5,8 @@ // virtualiser. The breakpoint logic mirrors the existing CSS grid // (`grid-template-columns: repeat(auto-fill, var(--r-card-art-w))`) so the // virtual rows visually match what the non-virtualised CSS grid would draw. -import { - onBeforeUnmount, - onMounted, - ref, - watch, - type Ref, - type ShallowRef, -} from "vue"; +import { useResizeObserver } from "@vueuse/core"; +import { onMounted, ref, watch, type Ref, type ShallowRef } from "vue"; /** A value that may be a constant or a reactive getter. Getters let the * caller vary card width / inset by breakpoint and have the column count @@ -48,7 +42,6 @@ export function useResponsiveColumns( // Observed content width minus `inset`: px available to a row of cards, // for consumers that flow-pack by width rather than a fixed column count. const usableWidth = ref(0); - let observer: ResizeObserver | null = null; // Last observed width: kept so a change in a reactive option (card // width / inset flipping at a breakpoint) can recompute without waiting // for the next resize event. @@ -80,30 +73,16 @@ export function useResponsiveColumns( }, ); - function attach(el: HTMLElement) { - compute(el.clientWidth); - observer = new ResizeObserver((entries) => { - for (const entry of entries) compute(entry.contentRect.width); - }); - observer.observe(el); - } - - function detach() { - observer?.disconnect(); - observer = null; - } + // Re-observes on its own if the bound ref swaps. + useResizeObserver(containerRef, (entries) => { + for (const entry of entries) compute(entry.contentRect.width); + }); + // Measure now so the first render has a column count before the observer's + // first callback. onMounted(() => { - if (containerRef.value) attach(containerRef.value); + if (containerRef.value) compute(containerRef.value.clientWidth); }); - // Re-attach if the bound ref swaps (rare, but safe). - watch(containerRef, (next, prev) => { - if (prev) detach(); - if (next) attach(next); - }); - - onBeforeUnmount(detach); - return { columns, usableWidth }; } diff --git a/frontend/src/v2/lib/forms/RSelect/RSelect.vue b/frontend/src/v2/lib/forms/RSelect/RSelect.vue index 614fc0812..d312dc27b 100644 --- a/frontend/src/v2/lib/forms/RSelect/RSelect.vue +++ b/frontend/src/v2/lib/forms/RSelect/RSelect.vue @@ -25,12 +25,11 @@ import { useFloating, } from "@floating-ui/vue"; import type { Placement } from "@floating-ui/vue"; +import { useElementSize } from "@vueuse/core"; import { computed, getCurrentInstance, nextTick, - onBeforeUnmount, - onMounted, ref, useAttrs, useSlots, @@ -341,7 +340,7 @@ const hasSelection = computed(() => selectedItems.value.length > 0); // `fitChipCount` of them. ResizeObserver re-measures on width changes. const valueRef = ref(null); const measureRef = ref(null); -const containerWidth = ref(0); +const { width: containerWidth } = useElementSize(valueRef); const fitChipCount = ref(Number.POSITIVE_INFINITY); const visibleChips = computed(() => { @@ -352,20 +351,6 @@ const overflowCount = computed(() => Math.max(0, selectedItems.value.length - visibleChips.value.length), ); -let resizeObserver: ResizeObserver | null = null; -onMounted(() => { - if (!valueRef.value) return; - containerWidth.value = valueRef.value.clientWidth; - resizeObserver = new ResizeObserver((entries) => { - for (const e of entries) containerWidth.value = e.contentRect.width; - }); - resizeObserver.observe(valueRef.value); -}); -onBeforeUnmount(() => { - resizeObserver?.disconnect(); - resizeObserver = null; -}); - // Walk through the mirror's chips and stop when the next one (plus // the reserved overflow-pill width) would overflow the visible row. function recomputeFit() { diff --git a/frontend/src/v2/lib/media/RBox3D/RBox3D.vue b/frontend/src/v2/lib/media/RBox3D/RBox3D.vue index f99a9e095..1e9a6a0d0 100644 --- a/frontend/src/v2/lib/media/RBox3D/RBox3D.vue +++ b/frontend/src/v2/lib/media/RBox3D/RBox3D.vue @@ -20,6 +20,7 @@ // Primitive boundaries (§II): no stores, no domain knowledge, it takes // three image URLs and a label. The feature composite (CoverColumn) decides // when a rom actually has all three faces and feeds them in. +import { useResizeObserver } from "@vueuse/core"; import { computed, onBeforeUnmount, onMounted, ref, type Ref } from "vue"; import { useReducedMotion } from "@/v2/composables/useReducedMotion"; @@ -285,18 +286,14 @@ const onFrontLoad = (e: Event) => measureRatio(e.target as HTMLImageElement, frontRatio); const onSpineLoad = (e: Event) => measureSpine(e.target as HTMLImageElement); -let ro: ResizeObserver | null = null; +useResizeObserver(rootEl, (entries) => { + const w = entries[0]?.contentRect.width ?? 0; + if (w > 0) widthPx.value = w; +}); onMounted(() => { const root = rootEl.value; if (root) { widthPx.value = root.clientWidth; - if (typeof ResizeObserver !== "undefined") { - ro = new ResizeObserver((entries) => { - const w = entries[0]?.contentRect.width ?? 0; - if (w > 0) widthPx.value = w; - }); - ro.observe(root); - } // Interaction listeners are bound imperatively (not in the template) so // the static box element doesn't trip the no-static-element-interactions // rule: the same approach GameCover takes for its hover motion. The box @@ -314,7 +311,6 @@ onMounted(() => { rafId = requestAnimationFrame(tick); }); onBeforeUnmount(() => { - ro?.disconnect(); cancelAnimationFrame(rafId); const root = rootEl.value; if (root) {