2023-11-12 03:21:26 +01:00
|
|
|
/*
|
|
|
|
|
* Copyright (C) Contributors to the Suwayomi project
|
|
|
|
|
*
|
|
|
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
import { useLocation, useNavigate } from 'react-router-dom';
|
2024-12-25 23:23:47 +01:00
|
|
|
import { useCallback } from 'react';
|
2024-12-11 20:10:59 +01:00
|
|
|
import { AppRoutes } from '@/modules/core/AppRoute.constants.ts';
|
2025-01-21 20:26:03 +01:00
|
|
|
import { useAppPageHistoryContext } from '@/modules/core/contexts/AppPageHistoryContext.tsx';
|
2024-10-19 16:34:51 +02:00
|
|
|
|
|
|
|
|
const PAGES_TO_IGNORE: readonly RegExp[] = [/\/manga\/[0-9]+\/chapter\/[0-9]+/g];
|
2023-11-12 03:21:26 +01:00
|
|
|
|
|
|
|
|
export const useBackButton = () => {
|
|
|
|
|
const navigate = useNavigate();
|
|
|
|
|
const location = useLocation();
|
2025-01-21 20:26:03 +01:00
|
|
|
const history = useAppPageHistoryContext();
|
2023-11-12 03:21:26 +01:00
|
|
|
|
2024-12-25 23:23:47 +01:00
|
|
|
return useCallback(() => {
|
2024-03-04 20:40:14 +01:00
|
|
|
const isHistoryEmpty = !history.length;
|
|
|
|
|
const isLastPageInHistoryCurrentPage = history.length === 1 && history[0] === location.pathname;
|
2024-10-19 16:34:51 +02:00
|
|
|
const ignorePreviousPage = history.length && PAGES_TO_IGNORE.some((page) => !!history.slice(-2)[0].match(page));
|
2023-11-12 03:21:26 +01:00
|
|
|
|
2024-10-19 16:34:51 +02:00
|
|
|
const canNavigateBack = !ignorePreviousPage && !isHistoryEmpty && !isLastPageInHistoryCurrentPage;
|
2024-03-04 20:40:14 +01:00
|
|
|
if (canNavigateBack) {
|
|
|
|
|
navigate(-1);
|
2023-11-12 03:21:26 +01:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-18 01:04:16 +08:00
|
|
|
navigate(AppRoutes.library.path());
|
2024-12-25 23:23:47 +01:00
|
|
|
}, [history, location.pathname]);
|
2023-11-12 03:21:26 +01:00
|
|
|
};
|