Add logic to have optional page specific back button logic
Makes it possible to trigger actions on back button click and optionally prevent the actual back navigation
This commit is contained in:
@@ -6,15 +6,44 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { createContext, useContext } from 'react';
|
||||
import { createContext, useCallback, useContext, useMemo, useRef } from 'react';
|
||||
import { useHistory } from '@/base/hooks/useHistory.ts';
|
||||
import { noOp } from '@/lib/HelperFunctions.ts';
|
||||
import { useForceUpdate } from '@mantine/hooks';
|
||||
|
||||
export const AppPageHistoryContext = createContext<string[]>([]);
|
||||
interface IAppPageHistoryContext {
|
||||
history: string[];
|
||||
onBack: () => Promise<boolean> | boolean;
|
||||
setOnBack: (subscriber: (() => Promise<boolean> | boolean) | null) => void;
|
||||
}
|
||||
|
||||
export const AppPageHistoryContext = createContext<IAppPageHistoryContext>({
|
||||
history: [],
|
||||
onBack: () => true,
|
||||
setOnBack: noOp,
|
||||
});
|
||||
|
||||
export const useAppPageHistoryContext = () => useContext(AppPageHistoryContext);
|
||||
|
||||
export const AppPageHistoryContextProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
const forceUpdate = useForceUpdate();
|
||||
const history = useHistory();
|
||||
|
||||
return <AppPageHistoryContext.Provider value={history}>{children}</AppPageHistoryContext.Provider>;
|
||||
const onBackRef = useRef<IAppPageHistoryContext['onBack']>(() => true);
|
||||
|
||||
const setOnBack = useCallback((callback: (() => Promise<boolean> | boolean) | null) => {
|
||||
onBackRef.current = callback ?? (() => true);
|
||||
forceUpdate();
|
||||
}, []);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
history,
|
||||
onBack: onBackRef.current,
|
||||
setOnBack,
|
||||
}),
|
||||
[history, onBackRef.current, setOnBack],
|
||||
);
|
||||
|
||||
return <AppPageHistoryContext.Provider value={value}>{children}</AppPageHistoryContext.Provider>;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user