@atlaskit/navigation-system
Version:
The latest navigation system for Atlassian apps.
73 lines • 3.17 kB
JavaScript
import { useEffect, useRef } from 'react';
import usePreviousValue from '@atlaskit/ds-lib/use-previous-value';
/**
* Calls the `onExpand` and `onCollapse` callbacks as required.
* This is used for both user-provided callbacks, as well as internal callbacks to respond to visibility state changes.
*/
export function useSideNavVisibilityCallbacks({
onExpand,
onCollapse,
isExpandedOnDesktop,
isExpandedOnMobile,
lastTrigger
}) {
// Wrapping in refs so we can call them in `useEffect` without changes to them triggering the `useEffect`
const onExpandRef = useRef(onExpand);
const onCollapseRef = useRef(onCollapse);
useEffect(() => {
onExpandRef.current = onExpand;
onCollapseRef.current = onCollapse;
}, [onExpand, onCollapse]);
const previousIsExpandedOnDesktop = usePreviousValue(isExpandedOnDesktop);
useEffect(() => {
if (previousIsExpandedOnDesktop === undefined || previousIsExpandedOnDesktop === isExpandedOnDesktop) {
/**
* The previous value is `undefined` on initialization, so if it is `undefined` then the value hasn't changed.
*
* The previous value can be equal to the current one if the component re-renders due to something else changing.
*
* In both cases the value hasn't changed and we don't want to notify consumers.
*/
return;
}
if (isExpandedOnDesktop) {
var _onExpandRef$current;
(_onExpandRef$current = onExpandRef.current) === null || _onExpandRef$current === void 0 ? void 0 : _onExpandRef$current.call(onExpandRef, {
screen: 'desktop',
trigger: lastTrigger
});
} else {
var _onCollapseRef$curren;
(_onCollapseRef$curren = onCollapseRef.current) === null || _onCollapseRef$curren === void 0 ? void 0 : _onCollapseRef$curren.call(onCollapseRef, {
screen: 'desktop',
trigger: lastTrigger
});
}
}, [previousIsExpandedOnDesktop, isExpandedOnDesktop, lastTrigger]);
const previousIsExpandedOnMobile = usePreviousValue(isExpandedOnMobile);
useEffect(() => {
if (previousIsExpandedOnMobile === undefined || previousIsExpandedOnMobile === isExpandedOnMobile) {
/**
* The previous value is `undefined` on initialization, so if it is `undefined` then the value hasn't changed.
*
* The previous value can be equal to the current one if the component re-renders due to something else changing.
*
* In both cases the value hasn't changed and we don't want to notify consumers.
*/
return;
}
if (isExpandedOnMobile) {
var _onExpandRef$current2;
(_onExpandRef$current2 = onExpandRef.current) === null || _onExpandRef$current2 === void 0 ? void 0 : _onExpandRef$current2.call(onExpandRef, {
screen: 'mobile',
trigger: lastTrigger
});
} else {
var _onCollapseRef$curren2;
(_onCollapseRef$curren2 = onCollapseRef.current) === null || _onCollapseRef$curren2 === void 0 ? void 0 : _onCollapseRef$curren2.call(onCollapseRef, {
screen: 'mobile',
trigger: lastTrigger
});
}
}, [previousIsExpandedOnMobile, isExpandedOnMobile, lastTrigger]);
}