Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(sharedResizeObserver): independent subscriptions per element (#5817)

freddymetad55751f88f83
diff --git a/.changeset/shared-resize-observer-independent-callbacks.md b/.changeset/shared-resize-observer-independent-callbacks.md
new file mode 100644
index 0000000000..5b7bbf7a0f
--- /dev/null
+++ b/.changeset/shared-resize-observer-independent-callbacks.md
@@ -0,0 +1,17 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] sharedResizeObserver: independent subscriptions per element
+
+The module held **one callback per element** — `callbacks.set(element, callback)` overwrote. A second hook observing the same node silently replaced the first, and either one calling `unobserveResize(element)` blinded the other.
+
+Two hooks on one element is ordinary rather than exotic: a `TabList` root, a `useOverflow` container and a `useTruncation` target are all nodes another hook may reasonably watch.
+
+`observeResize` now returns an unsubscribe that removes only its own registration, and every caller in the package uses it. `unobserveResize(element, callback)` does the same by hand; the callback-less `unobserveResize(element)` still drops every callback on the element and stays for a caller that owns its element outright.
+
+Dispatch snapshots the callback keys, so a callback may unsubscribe while the batch is running without skipping its neighbour.
+
+Prerequisite for AST-010 §Implementation-requirements 9, kept separate so it is reviewable on its own. No component behaviour changes: 8534 core tests pass, and the five observer regressions fail against the old module.
+
+@freddymeta
diff --git a/apps/storybook/rtl-audit/rtl-audit-coverage.mjs b/apps/storybook/rtl-audit/rtl-audit-coverage.mjs
index c4ac167c23..a75e05fbf4 100644
--- a/apps/storybook/rtl-audit/rtl-audit-coverage.mjs
+++ b/apps/storybook/rtl-audit/rtl-audit-coverage.mjs
@@ -3,8 +3,9 @@
/**
* @file Shared RTL coverage and directional-decoration helpers.
* @input Rendered DOM decorations plus D1/D5/D6/curated audit results.
- * @output Contextual decoration candidates, pair verdicts, and per-component
- * measured / verified-N-A / coverage-gap classifications.
+ * @output Contextual decoration candidates, pair verdicts, component-filter
+ * reconciliation, and per-component measured / verified-N-A / coverage-gap
+ * classifications.
* @position Pure support layer for rtl-audit.mjs and its unit tests.
*/
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index ed930885e7..b0b671eb5c 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -90,6 +90,17 @@
"next": "button[aria-label=\"Next\"]"
}
},
+ {
+ "component": "TabList",
+ "storyId": "core-tablist--overflow",
+ "dims": [
+ "D3"
+ ],
+ "selectors": {
+ "scroller": ".astryx-tab-strip",
+ "nextButton": ".astryx-tab-scroll-button"
+ }
+ },
{
"component": "Typeahead",
"storyId": "core-typeahead--logical-order",
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index 1cc979472f..10bc3fe144 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -2,5 +2,13 @@
{
"component": "core/Spinner",
"reason": "No direction-sensitive visual, layout, or behavior. The ring is a concentric SVG — two <circle> elements sharing one center, sized by diameter and stroke, with no physical inset, offset, or asymmetry to mirror. Its only layout is the optional label wrapper, which is flexDirection: column + alignItems: center, so the label stacks below the ring on both axes' terms rather than beside it. The rotation keyframe (0deg to 360deg) is deliberately absolute: a loading spinner turns the same way in every locale, and mirroring it would be a bug, not RTL support."
+ },
+ {
+ "component": "core/Table",
+ "reason": "The Core/Table stories render native table rows and cells inside an overflow-x scroll wrapper. Column order, start/end alignment, column dividers and container bleed use table flow, text-align start/end, border-inline-end and logical inline margins, all resolved by CSS for the document direction. Horizontal overflow is native scrolling with no component-owned next/previous control or directional drag behavior, and these stories render no directional glyph or positioned element with a horizontal transform."
+ },
+ {
+ "component": "core/Text",
+ "reason": "Text sets typography — size, weight, colour, line-height, wrapping, truncation — and nothing else. Its one alignment prop is `justify`, which compiles to the logical `text-align: start | center | end` and defaults to `start`, so text hangs off the correct edge in either direction without a component-side branch. Truncation is `text-overflow: ellipsis` and `-webkit-line-clamp`, both of which put the ellipsis at the reading end on their own, and the tooltip that accompanies a clamped string is placed with the logical `above`/`below`/`start`/`end` vocabulary. Nothing is positioned, nothing is transformed, and the component renders no glyph, separator, or control."
}
]
diff --git a/packages/core/src/AppShell/AppShell.tsx b/packages/core/src/AppShell/AppShell.tsx
index 7de90d7c01..a85c954110 100644
--- a/packages/core/src/AppShell/AppShell.tsx
+++ b/packages/core/src/AppShell/AppShell.tsx
@@ -53,7 +53,7 @@ import type {BaseProps} from '../BaseProps';
import {mergeProps, isRenderable} from '../utils';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {useMediaQuery} from '../hooks/useMediaQuery';
-import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
+import {observeResize} from '../utils/sharedResizeObserver';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
import type {AppShellVariantMap} from './index';
@@ -593,8 +593,7 @@ export function AppShell({
shellEl.style.setProperty('--_app-shell-header-height', `${height}px`);
};
- observeResize(headerEl, () => updateHeight());
- return () => unobserveResize(headerEl);
+ return observeResize(headerEl, () => updateHeight());
}, [isAuto]);
// =========================================================================
diff --git a/packages/core/src/Chat/useChatNewMessages.ts b/packages/core/src/Chat/useChatNewMessages.ts
index 0ca8e7e66c..fe5c734022 100644
--- a/packages/core/src/Chat/useChatNewMessages.ts
+++ b/packages/core/src/Chat/useChatNewMessages.ts
@@ -24,7 +24,7 @@
*/
import {useCallback, useEffect, useRef, useState} from 'react';
-import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
+import {observeResize} from '../utils/sharedResizeObserver';
// =============================================================================
// Types
@@ -80,7 +80,7 @@ export function useChatNewMessages({
const cleanupRef = useRef<(() => void) | null>(null);
const attach = useCallback((el: HTMLElement) => {
- observeResize(el, () => {
+ const unobserve = observeResize(el, () => {
onResizeRef.current?.();
const messages = el.getElementsByClassName('astryx-chat-message');
@@ -94,7 +94,7 @@ export function useChatNewMessages({
}
});
- cleanupRef.current = () => unobserveResize(el);
+ cleanupRef.current = unobserve;
}, []);
const detach = useCallback(() => {
diff --git a/packages/core/src/TabList/TabList.tsx b/packages/core/src/TabList/TabList.tsx
index a40fef5fed..fd176b98b4 100644
--- a/packages/core/src/TabList/TabList.tsx
+++ b/packages/core/src/TabList/TabList.tsx
@@ -53,7 +53,7 @@ import {isRtlElement} from '../hooks/isRtlElement';
import {Icon} from '../Icon';
import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';
import {themeProps} from '../utils/themeProps';
-import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
+import {observeResize} from '../utils/sharedResizeObserver';
import {devWarn} from '../utils/devWarning';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {useTranslator} from '../i18n';
@@ -494,8 +494,7 @@ export function TabList({
return;
}
const onResize = () => revealSelectedTabRef.current();
- observeResize(root, onResize);
- return () => unobserveResize(root);
+ return observeResize(root, onResize);
}, [hasScroll, listRef]);
const scrollByPage = useCallback((direction: -1 | 1) => {
diff --git a/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx b/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx
index 608bcdc597..12f744663e 100644
--- a/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx
+++ b/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx
@@ -23,10 +23,7 @@ import type {
ColumnWidth,
} from '../../types';
import {DEFAULT_MIN_COLUMN_WIDTH} from '../../columnUtils';
-import {
- observeResize,
- unobserveResize,
-} from '../../../utils/sharedResizeObserver';
+import {observeResize} from '../../../utils/sharedResizeObserver';
// =============================================================================
// Config Type
@@ -727,12 +724,12 @@ export function useTableColumnResize<T extends Record<string, unknown>>(
// --table-resize-height on the <table> element. This is initialized
// entirely by the resize plugin — the base table has no knowledge of it.
const observedTableRef = useRef<HTMLTableElement | null>(null);
+ const unobserveTableRef = useRef<(() => void) | null>(null);
const measureRef = useCallback((el: HTMLDivElement | null) => {
- if (observedTableRef.current) {
- unobserveResize(observedTableRef.current);
- observedTableRef.current = null;
- }
+ unobserveTableRef.current?.();
+ unobserveTableRef.current = null;
+ observedTableRef.current = null;
if (!el) {
return;
}
@@ -743,7 +740,7 @@ export function useTableColumnResize<T extends Record<string, unknown>>(
}
if (table && typeof ResizeObserver !== 'undefined') {
- observeResize(table, () => {
+ unobserveTableRef.current = observeResize(table, () => {
const height = table.getBoundingClientRect().height;
table.style.setProperty('--table-resize-height', `${height}px`);
});
@@ -754,9 +751,8 @@ export function useTableColumnResize<T extends Record<string, unknown>>(
// Clean up observer on unmount
useEffect(() => {
return () => {
- if (observedTableRef.current) {
- unobserveResize(observedTableRef.current);
- }
+ unobserveTableRef.current?.();
+ unobserveTableRef.current = null;
};
}, []);
diff --git a/packages/core/src/Text/useTruncation.ts b/packages/core/src/Text/useTruncation.ts
index 4de0ddbda0..207fef8511 100644
--- a/packages/core/src/Text/useTruncation.ts
+++ b/packages/core/src/Text/useTruncation.ts
@@ -13,7 +13,7 @@
*/
import {useCallback, useRef, useState, type RefCallback} from 'react';
-import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
+import {observeResize} from '../utils/sharedResizeObserver';
export interface UseTruncationOptions {
/**
@@ -43,7 +43,7 @@ export interface UseTruncationReturn {
/**
* Hook for detecting text overflow/truncation.
*
- * Uses a shared ResizeObserver singleton (via observeResize/unobserveResize)
+ * Uses a shared ResizeObserver singleton (via observeResize)
* for efficient detection when content or container changes. A single
* ResizeObserver instance is shared across all mounted useTruncation hooks,
* so even hundreds of table cells only create one observer.
@@ -70,6 +70,7 @@ export function useTruncation(
const [isTruncated, setIsTruncated] = useState(false);
const [fullText, setFullText] = useState('');
const elementRef = useRef<HTMLElement | null>(null);
+ const unobserveRef = useRef<(() => void) | null>(null);
const checkTruncation = useCallback(
(element: HTMLElement) => {
@@ -108,10 +109,10 @@ export function useTruncation(
const ref: RefCallback<HTMLElement> = useCallback(
(element: HTMLElement | null) => {
- // Cleanup previous observation
- if (elementRef.current) {
- unobserveResize(elementRef.current);
- }
+ // Cleanup previous observation. Unsubscribing by callback rather than
+ // by element leaves any other observer of the same node untouched.
+ unobserveRef.current?.();
+ unobserveRef.current = null;
elementRef.current = element;
@@ -120,7 +121,7 @@ export function useTruncation(
// observeResize fires the callback once on registration,
// so no separate initial check is needed.
if (typeof ResizeObserver !== 'undefined') {
- observeResize(element, () => {
+ unobserveRef.current = observeResize(element, () => {
checkTruncation(element);
});
} else {
diff --git a/packages/core/src/Tokenizer/useEndLaneReserve.ts b/packages/core/src/Tokenizer/useEndLaneReserve.ts
index ee4435f95f..8a0ee31cc1 100644
--- a/packages/core/src/Tokenizer/useEndLaneReserve.ts
+++ b/packages/core/src/Tokenizer/useEndLaneReserve.ts
@@ -27,7 +27,7 @@
import {useCallback} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
+import {observeResize} from '../utils/sharedResizeObserver';
/**
* The measured lane width, published on the field wrapper and read by the
@@ -92,7 +92,7 @@ export function useEndLaneReserve(
// of the input either way, which is what inheritance needs.
const host = node.parentElement;
- observeResize(node, () => {
+ const unobserve = observeResize(node, () => {
// `offsetWidth`, not `getBoundingClientRect().width`. The rect is in
// VIEWPORT space — it carries every CSS transform between this element
// and the root — while the padding it feeds is in the element's own
@@ -116,7 +116,7 @@ export function useEndLaneReserve(
// React 19 runs a ref callback's return value as its cleanup, so the
// observer is released exactly when the lane unmounts.
return () => {
- unobserveResize(node);
+ unobserve();
// The room the lane claimed goes back to the input. Removing beats
// setting 0px: the rule's fallback is already that, and this leaves no
// stale property behind on the DOM.
diff --git a/packages/core/src/hooks/useOverflow.ts b/packages/core/src/hooks/useOverflow.ts
index 8391c5faad..3cc134d6ff 100644
--- a/packages/core/src/hooks/useOverflow.ts
+++ b/packages/core/src/hooks/useOverflow.ts
@@ -22,7 +22,7 @@
import {useState, useCallback, useRef} from 'react';
import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
-import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
+import {observeResize} from '../utils/sharedResizeObserver';
import {computeOverflow} from './computeOverflow';
import {useDevWarning} from './useDevWarning';
@@ -138,6 +138,8 @@ export function useOverflow(
const measureElRef = useRef<HTMLElement | null>(null);
const observedElRef = useRef<HTMLElement | null>(null);
const observedMeasureElRef = useRef<HTMLElement | null>(null);
+ const unobserveContainerRef = useRef<(() => void) | null>(null);
+ const unobserveMeasureRef = useRef<(() => void) | null>(null);
const calculate = useCallback(() => {
const container = containerElRef.current;
@@ -219,15 +221,14 @@ export function useOverflow(
containerElRef.current = el;
// Clean up previous observation
- if (observedElRef.current) {
- unobserveResize(observedElRef.current);
- observedElRef.current = null;
- }
+ unobserveContainerRef.current?.();
+ unobserveContainerRef.current = null;
+ observedElRef.current = null;
if (el) {
const target =
observeParent && el.parentElement ? el.parentElement : el;
- observeResize(target, () => {
+ unobserveContainerRef.current = observeResize(target, () => {
calculate();
});
observedElRef.current = target;
@@ -238,17 +239,16 @@ export function useOverflow(
const measureRef = useCallback(
(el: HTMLElement | null) => {
- if (observedMeasureElRef.current) {
- unobserveResize(observedMeasureElRef.current);
- observedMeasureElRef.current = null;
- }
+ unobserveMeasureRef.current?.();
+ unobserveMeasureRef.current = null;
+ observedMeasureElRef.current = null;
measureElRef.current = el;
if (!el) {
return;
}
- observeResize(el, () => {
+ unobserveMeasureRef.current = observeResize(el, () => {
calculate();
});
observedMeasureElRef.current = el;
diff --git a/packages/core/src/hooks/useScrollOverflow.ts b/packages/core/src/hooks/useScrollOverflow.ts
index 4f2bca44c9..0f79e82407 100644
--- a/packages/core/src/hooks/useScrollOverflow.ts
+++ b/packages/core/src/hooks/useScrollOverflow.ts
@@ -16,7 +16,7 @@
*/
import {useState, useCallback, useEffect, useRef} from 'react';
-import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
+import {observeResize} from '../utils/sharedResizeObserver';
export interface ScrollOverflowState {
/** Content overflows the start (left in LTR, right in RTL) */
@@ -41,6 +41,7 @@ export interface ScrollOverflowState {
*/
export function useScrollOverflow() {
const elRef = useRef<HTMLElement | null>(null);
+ const unobserveRef = useRef<(() => void) | null>(null);
const [state, setState] = useState<ScrollOverflowState>({
overflowStart: false,
@@ -77,7 +78,8 @@ export function useScrollOverflow() {
const scrollRef = useCallback(
(el: HTMLElement | null) => {
if (elRef.current) {
- unobserveResize(elRef.current);
+ unobserveRef.current?.();
+ unobserveRef.current = null;
elRef.current.removeEventListener('scroll', measure);
}
@@ -85,7 +87,7 @@ export function useScrollOverflow() {
if (el) {
el.addEventListener('scroll', measure, {passive: true});
- observeResize(el, measure);
+ unobserveRef.current = observeResize(el, measure);
}
},
[measure],
@@ -94,7 +96,8 @@ export function useScrollOverflow() {
useEffect(() => {
return () => {
if (elRef.current) {
- unobserveResize(elRef.current);
+ unobserveRef.current?.();
+ unobserveRef.current = null;
elRef.current.removeEventListener('scroll', measure);
}
};
diff --git a/packages/core/src/utils/sharedResizeObserver.test.ts b/packages/core/src/utils/sharedResizeObserver.test.ts
index 907fccf1a7..f30206612e 100644
--- a/packages/core/src/utils/sharedResizeObserver.test.ts
+++ b/packages/core/src/utils/sharedResizeObserver.test.ts
@@ -135,30 +135,149 @@ describe('sharedResizeObserver', () => {
unobserveResize(el2);
});
- it('replaces callback when same element is observed twice', async () => {
+ it('keeps every callback registered on one element', async () => {
const {observeResize, unobserveResize} =
await import('./sharedResizeObserver');
+ // Two hooks observing the same node is ordinary — a resizable region's
+ // container is also what `useOverflow` or a `TabList` root watches. This
+ // map used to hold one callback per element, so whichever registered first
+ // silently stopped receiving resizes.
const el = document.createElement('div');
const cb1 = vi.fn();
const cb2 = vi.fn();
observeResize(el, cb1);
+ observeResize(el, cb2);
cb1.mockClear();
+ cb2.mockClear();
+
+ capturedCallback(
+ [{target: el} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+
+ expect(cb1).toHaveBeenCalledTimes(1);
+ expect(cb2).toHaveBeenCalledTimes(1);
+ unobserveResize(el);
+ });
+
+ it('unsubscribing one observer leaves its peers observing', async () => {
+ const {observeResize} = await import('./sharedResizeObserver');
+
+ // The other half of the same bug: one hook unmounting must not blind the
+ // others still mounted on the element it shared.
+ const el = document.createElement('div');
+ const cb1 = vi.fn();
+ const cb2 = vi.fn();
+
+ const unsubscribe = observeResize(el, cb1);
observeResize(el, cb2);
+ unsubscribe();
+ cb1.mockClear();
+ cb2.mockClear();
capturedCallback(
[{target: el} as unknown as ResizeObserverEntry],
{} as ResizeObserver,
);
- // Only the latest callback fires for subsequent resizes
expect(cb1).not.toHaveBeenCalled();
- // cb2: initial fire (1) + observer fire (1) = but we only check the observer fire
- // cb2 was called once on registration, then once from capturedCallback
- expect(cb2).toHaveBeenCalledTimes(2);
+ expect(cb2).toHaveBeenCalledTimes(1);
+ // Still observed while anyone is listening.
+ expect(mockUnobserve).not.toHaveBeenCalledWith(el);
+ });
+
+ it('keeps duplicate callback registrations independently subscribed', async () => {
+ const {observeResize} = await import('./sharedResizeObserver');
+
+ const el = document.createElement('div');
+ const callback = vi.fn();
+ const unsubscribeFirst = observeResize(el, callback);
+ const unsubscribeSecond = observeResize(el, callback);
+ callback.mockClear();
+
+ unsubscribeFirst();
+ unsubscribeFirst();
+ capturedCallback(
+ [{target: el} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(mockUnobserve).not.toHaveBeenCalledWith(el);
+
+ callback.mockClear();
+ unsubscribeSecond();
+ capturedCallback(
+ [{target: el} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+
+ expect(callback).not.toHaveBeenCalled();
+ expect(mockUnobserve).toHaveBeenCalledWith(el);
+ });
+
+ it('releases the element once its last observer unsubscribes', async () => {
+ const {observeResize} = await import('./sharedResizeObserver');
+ const el = document.createElement('div');
+ const off1 = observeResize(el, vi.fn());
+ const off2 = observeResize(el, vi.fn());
+
+ off1();
+ expect(mockUnobserve).not.toHaveBeenCalledWith(el);
+ off2();
+ expect(mockUnobserve).toHaveBeenCalledWith(el);
+ expect(mockDisconnect).toHaveBeenCalled();
+ });
+
+ it('a callback may unsubscribe while the batch is dispatching', async () => {
+ const {observeResize} = await import('./sharedResizeObserver');
+
+ // Dispatch iterates a copy: mutating the live set mid-iteration would skip
+ // the neighbour that had not been called yet.
+ const el = document.createElement('div');
+ const cb2 = vi.fn();
+ const off1: {current: (() => void) | null} = {current: null};
+ const cb1 = vi.fn(() => off1.current?.());
+
+ off1.current = observeResize(el, cb1);
+ observeResize(el, cb2);
+ cb1.mockClear();
+ cb2.mockClear();
+
+ capturedCallback(
+ [{target: el} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+
+ expect(cb1).toHaveBeenCalledTimes(1);
+ expect(cb2).toHaveBeenCalledTimes(1);
+ });
+
+ it('still drops the whole element when no callback is named', async () => {
+ const {observeResize, unobserveResize} =
+ await import('./sharedResizeObserver');
+
+ // Back-compat for a caller that owns its element outright.
+ const el = document.createElement('div');
+ const cb1 = vi.fn();
+ const cb2 = vi.fn();
+
+ observeResize(el, cb1);
+ observeResize(el, cb2);
unobserveResize(el);
+ cb1.mockClear();
+ cb2.mockClear();
+
+ capturedCallback(
+ [{target: el} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+
+ expect(cb1).not.toHaveBeenCalled();
+ expect(cb2).not.toHaveBeenCalled();
});
});
diff --git a/packages/core/src/utils/sharedResizeObserver.ts b/packages/core/src/utils/sharedResizeObserver.ts
index 0633be9c21..349b022337 100644
--- a/packages/core/src/utils/sharedResizeObserver.ts
+++ b/packages/core/src/utils/sharedResizeObserver.ts
@@ -22,7 +22,10 @@
type ResizeCallback = (entry: ResizeObserverEntry) => void;
let observer: ResizeObserver | null = null;
-const callbacks = new Map<Element, ResizeCallback>();
+// A callback may be registered more than once for one element. The inner map
+// keeps those registrations alive independently without dispatching duplicate
+// work for the same callback reference.
+const callbacks = new Map<Element, Map<ResizeCallback, number>>();
/**
* The shared observer, or null where the API does not exist (jsdom, an old
@@ -36,9 +39,12 @@ function getObserver(): ResizeObserver | null {
if (!observer) {
observer = new ResizeObserver(entries => {
for (const entry of entries) {
- const cb = callbacks.get(entry.target);
- if (cb) {
- cb(entry);
+ const targetCallbacks = callbacks.get(entry.target);
+ if (targetCallbacks) {
+ // A callback may unsubscribe while dispatch is in progress.
+ for (const cb of [...targetCallbacks.keys()]) {
+ cb(entry);
+ }
}
}
});
@@ -53,38 +59,78 @@ function getObserver(): ResizeObserver | null {
* synthetic entry) so callers don't need separate initial-measurement
* logic. Subsequent callbacks fire on actual resizes.
*
- * Call `unobserveResize` when the element unmounts or observation is
- * no longer needed. The shared observer is destroyed when the last
- * element is unobserved.
+ * Returns an unsubscribe function that removes only this registration, leaving
+ * every other observer of the same element intact — prefer it over
+ * `unobserveResize(element)`, which drops them all. The shared observer is
+ * destroyed when the last element is unobserved.
*
* @example
* ```
- * observeResize(element, (entry) => {
+ * const unsubscribe = observeResize(element, (entry) => {
* console.log(entry.contentBoxSize);
* });
*
* // Cleanup:
- * unobserveResize(element);
+ * unsubscribe();
* ```
*/
export function observeResize(
element: Element,
callback: ResizeCallback,
-): void {
- callbacks.set(element, callback);
+): () => void {
+ const existing = callbacks.get(element);
+ if (existing) {
+ existing.set(callback, (existing.get(callback) ?? 0) + 1);
+ } else {
+ callbacks.set(element, new Map([[callback, 1]]));
+ }
getObserver()?.observe(element);
// Fire once immediately so callers get an initial measurement
// without duplicating their logic outside the observer path.
const entry: Partial<ResizeObserverEntry> = {target: element};
callback(entry as ResizeObserverEntry);
+
+ let isSubscribed = true;
+ return () => {
+ if (!isSubscribed) {
+ return;
+ }
+ isSubscribed = false;
+ unobserveResize(element, callback);
+ };
}
/**
- * Stop observing an element. If no elements remain, the shared
- * observer is disconnected and released for garbage collection.
+ * Stop observing an element.
+ *
+ * Pass the callback to remove only that registration — the unsubscribe returned
+ * by `observeResize` does this for you. Omitting it removes EVERY callback on
+ * the element, which silences peers that are still mounted, so it is only
+ * correct for a caller that owns the element outright.
+ *
+ * If no elements remain, the shared observer is disconnected and released for
+ * garbage collection.
*/
-export function unobserveResize(element: Element): void {
+export function unobserveResize(
+ element: Element,
+ callback?: ResizeCallback,
+): void {
+ const targetCallbacks = callbacks.get(element);
+ if (callback != null) {
+ const registrationCount = targetCallbacks?.get(callback);
+ if (targetCallbacks == null || registrationCount == null) {
+ return;
+ }
+ if (registrationCount > 1) {
+ targetCallbacks.set(callback, registrationCount - 1);
+ return;
+ }
+ targetCallbacks.delete(callback);
+ if (targetCallbacks.size > 0) {
+ return;
+ }
+ }
callbacks.delete(element);
if (observer) {
observer.unobserve(element);