diff --git a/packages/polaris-viz/CHANGELOG.md b/packages/polaris-viz/CHANGELOG.md index 557bd63f02..693d917b58 100644 --- a/packages/polaris-viz/CHANGELOG.md +++ b/packages/polaris-viz/CHANGELOG.md @@ -11,6 +11,10 @@ and adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). - Fixed the positioning of the `` for the Stacked Horizontal Chart when all values are negative. +### Changed + +- Allow `useWatchActiveSeries` to accept `null` as an `id` to disable attaching events. + ## [10.5.2] - 2024-02-22 ### Added diff --git a/packages/polaris-viz/src/hooks/tests/useWatchActiveSeries.test.tsx b/packages/polaris-viz/src/hooks/tests/useWatchActiveSeries.test.tsx new file mode 100644 index 0000000000..cac0513c40 --- /dev/null +++ b/packages/polaris-viz/src/hooks/tests/useWatchActiveSeries.test.tsx @@ -0,0 +1,44 @@ +import {mount} from '@shopify/react-testing'; + +import {useWatchActiveSeries} from '../useWatchActiveSeries'; + +describe('useWatchActiveSeries', () => { + const addEventListenerSpy = jest.fn((_) => {}); + + beforeEach(() => { + jest + .spyOn(window, 'addEventListener') + .mockImplementation(addEventListenerSpy); + }); + + afterEach(() => { + addEventListenerSpy.mockReset(); + }); + + it('attaches event listeners to window when id is passed', () => { + function MockComponent() { + useWatchActiveSeries('id', () => {}); + + return null; + } + + mount(); + + expect(addEventListenerSpy).toHaveBeenCalledWith( + 'id:color-vision-event:singleItem', + expect.any(Function), + ); + }); + + it('does not attach event listeners to window when id is null', () => { + function MockComponent() { + useWatchActiveSeries(null, () => {}); + + return null; + } + + mount(); + + expect(addEventListenerSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/polaris-viz/src/hooks/useWatchActiveSeries.ts b/packages/polaris-viz/src/hooks/useWatchActiveSeries.ts index 4a035314ae..3920fdcda5 100644 --- a/packages/polaris-viz/src/hooks/useWatchActiveSeries.ts +++ b/packages/polaris-viz/src/hooks/useWatchActiveSeries.ts @@ -7,12 +7,16 @@ import {getEventName} from './ColorVisionA11y'; import {useCallbackRef} from './useCallbackRef'; export function useWatchActiveSeries( - id: string, + id: string | null, onIndexChange: (event: ColorVisionEventReturn) => void, ) { const onIndexChangeCallback = useCallbackRef(onIndexChange); useEffect(() => { + if (id == null) { + return; + } + const eventName = getEventName(id, COLOR_VISION_SINGLE_ITEM); window.addEventListener(eventName, onIndexChangeCallback);