Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import {
useEventCallback,
resolveShorthand,
} from '@fluentui/react-utilities';
import { useFluent_unstable } from '@fluentui/react-shared-contexts';
import type { ToastContainerProps, ToastContainerState } from './ToastContainer.types';
import { useToast } from '../../state';
import { Timer, TimerProps } from '../Timer/Timer';

const intentPolitenessMap = {
Expand Down Expand Up @@ -42,9 +42,30 @@ export const useToastContainer_unstable = (
timeout: timerTimeout,
politeness: desiredPoliteness,
intent = 'info',
pauseOnHover,
pauseOnWindowBlur,
...rest
} = props;
const { play, running, toastRef } = useToast<HTMLDivElement>({ ...props });
const toastRef = React.useRef<HTMLDivElement | null>(null);
const { targetDocument } = useFluent_unstable();
const [running, setRunning] = React.useState(false);
const pause = useEventCallback(() => setRunning(false));
const play = useEventCallback(() => setRunning(true));

React.useEffect(() => {
if (!targetDocument) {
return;
}

if (pauseOnWindowBlur) {
targetDocument.defaultView?.addEventListener('focus', play);
targetDocument.defaultView?.addEventListener('blur', pause);
return () => {
targetDocument.defaultView?.removeEventListener('focus', play);
targetDocument.defaultView?.removeEventListener('blur', pause);
};
}
}, [targetDocument, pause, play, pauseOnWindowBlur]);

React.useEffect(() => {
if (!visible) {
Expand Down Expand Up @@ -76,6 +97,16 @@ export const useToastContainer_unstable = (
userRootSlot?.onAnimationEnd?.(e);
});

const onMouseEnter = useEventCallback((e: React.MouseEvent<HTMLDivElement>) => {
pause();
userRootSlot?.onMouseEnter?.(e);
});

const onMouseLeave = useEventCallback((e: React.MouseEvent<HTMLDivElement>) => {
play();
userRootSlot?.onMouseEnter?.(e);
});

return {
components: {
timer: Timer,
Expand All @@ -91,6 +122,8 @@ export const useToastContainer_unstable = (
...rest,
...userRootSlot,
onAnimationEnd,
onMouseEnter,
onMouseLeave,
}),
timerTimeout,
transitionTimeout: 500,
Expand Down
1 change: 0 additions & 1 deletion packages/react-components/react-toast/src/state/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export * from './types';
export * from './useToaster';
export * from './useToast';
export * from './useToastController';
export { getPositionStyles } from './vanilla';
export { TOAST_POSITIONS } from './constants';
47 changes: 0 additions & 47 deletions packages/react-components/react-toast/src/state/useToast.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { EVENTS } from './constants';
import { Toast, ToastId } from './types';
import { useToaster } from './useToaster';
import { createToaster } from './vanilla/createToaster';
import { renderHook, act } from '@testing-library/react-hooks';

jest.mock('./vanilla/createToaster.ts');

type Toaster = ReturnType<typeof createToaster>;

describe('useToaster', () => {
const mockToaster = (options?: Partial<Toaster>): Toaster => {
const mock: Toaster = {
buildToast: jest.fn(),
dismissAllToasts: jest.fn(),
dismissToast: jest.fn(),
updateToast: jest.fn(),
isToastVisible: jest.fn(),
toasts: new Map<ToastId, Toast>(),
visibleToasts: new Set<ToastId>(),
...options,
};

(createToaster as jest.Mock).mockReturnValue(mock);
return mock;
};
beforeEach(() => {
mockToaster();
});

it('should register document event handlers', () => {
const toaster = mockToaster();
renderHook(() => useToaster());

const detail = { toasterId: undefined };
act(() => {
document.dispatchEvent(new CustomEvent(EVENTS.dismiss, { detail }));
document.dispatchEvent(new CustomEvent(EVENTS.update, { detail }));
document.dispatchEvent(new CustomEvent(EVENTS.dismissAll, { detail }));
document.dispatchEvent(new CustomEvent(EVENTS.show, { detail }));
});

expect(toaster.buildToast).toHaveBeenCalledTimes(1);
expect(toaster.updateToast).toHaveBeenCalledTimes(1);
expect(toaster.dismissAllToasts).toHaveBeenCalledTimes(1);
expect(toaster.dismissToast).toHaveBeenCalledTimes(1);
});

it('should respect toasterId for events', () => {
const toaster = mockToaster();
renderHook(() => useToaster({ toasterId: 'foo' }));

const detail = { toasterId: 'bar' };
act(() => {
document.dispatchEvent(new CustomEvent(EVENTS.dismiss, { detail }));
document.dispatchEvent(new CustomEvent(EVENTS.update, { detail }));
document.dispatchEvent(new CustomEvent(EVENTS.dismissAll, { detail }));
document.dispatchEvent(new CustomEvent(EVENTS.show, { detail }));
});

expect(toaster.buildToast).toHaveBeenCalledTimes(0);
expect(toaster.updateToast).toHaveBeenCalledTimes(0);
expect(toaster.dismissAllToasts).toHaveBeenCalledTimes(0);
expect(toaster.dismissToast).toHaveBeenCalledTimes(0);
});
});
75 changes: 65 additions & 10 deletions packages/react-components/react-toast/src/state/useToaster.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,79 @@
import * as React from 'react';
import { useForceUpdate } from '@fluentui/react-utilities';
import { useEventCallback, useForceUpdate } from '@fluentui/react-utilities';
import { useFluent_unstable as useFluent } from '@fluentui/react-shared-contexts';
import { Toaster } from './vanilla/toaster';
import { Toast, ToastPosition, ToasterOptions } from './types';
import { createToaster } from './vanilla';
import type {
CommonToastDetail,
ShowToastEventDetail,
Toast,
ToastListenerMap,
ToastPosition,
ToasterId,
ToasterOptions,
} from './types';
import { ToasterProps } from '../components/Toaster';
import { EVENTS } from './constants';

export function useToaster<TElement extends HTMLElement>(options: ToasterProps = {}) {
const forceRender = useForceUpdate();
const forceUpdate = useForceUpdate();
const toasterOptions = useToasterOptions(options);
const [toaster] = React.useState(() => new Toaster());
const [toaster] = React.useState(() => createToaster(toasterOptions));
const { targetDocument } = useFluent();

const isCorrectToaster = useEventCallback((toasterId: ToasterId | undefined) => {
return toasterId === toasterOptions.toasterId;
});

React.useEffect(() => {
if (targetDocument) {
toaster.connectToDOM(targetDocument, toasterOptions);
toaster.onUpdate = forceRender;
if (!targetDocument) {
return;
}

return () => toaster.disconnect();
}, [toaster, forceRender, toasterOptions, targetDocument]);
const addToastListener = <TType extends keyof ToastListenerMap>(
eventType: TType,
callback: ToastListenerMap[TType],
) => {
const listener: ToastListenerMap[TType] = (e: CustomEvent<CommonToastDetail>) => {
if (!isCorrectToaster(e.detail.toasterId)) {
return;
}

callback(e as CustomEvent<ShowToastEventDetail>);
forceUpdate();
};

targetDocument.addEventListener(eventType, listener as () => void);
return () => targetDocument.removeEventListener(eventType, listener as () => void);
};

const buildToast: ToastListenerMap[typeof EVENTS.show] = e => {
toaster.buildToast(e.detail, forceUpdate);
};

const dismissToast: ToastListenerMap[typeof EVENTS.dismiss] = e => {
toaster.dismissToast(e.detail.toastId);
};

const updateToast: ToastListenerMap[typeof EVENTS.update] = e => {
toaster.updateToast(e.detail);
};

const dismissAllToasts: ToastListenerMap[typeof EVENTS.dismissAll] = e => {
toaster.dismissAllToasts();
};

const cleanupBuildListener = addToastListener(EVENTS.show, buildToast);
const cleanupUpdateListener = addToastListener(EVENTS.update, updateToast);
const cleanupDismissListener = addToastListener(EVENTS.dismiss, dismissToast);
const cleanupDismissAllListener = addToastListener(EVENTS.dismissAll, dismissAllToasts);

return () => {
cleanupBuildListener();
cleanupDismissAllListener();
cleanupUpdateListener();
cleanupDismissListener();
};
}, [toaster, forceUpdate, targetDocument, isCorrectToaster]);

const toastsToRender = (() => {
if (!toaster) {
Expand Down
Loading