Files
suwayomi-material-you-webui/src/modules/manga/components/MangaGrid.tsx
T

389 lines
13 KiB
TypeScript
Raw Normal View History

/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
2021-01-26 23:32:12 +03:30
* 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/.
*/
2021-01-26 23:32:12 +03:30
2024-07-12 23:12:11 +02:00
import React, {
ForwardedRef,
forwardRef,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
2024-09-14 03:01:07 +02:00
import Grid, { Grid2TypeMap as GridTypeMap } from '@mui/material/Grid2';
import Box, { BoxProps } from '@mui/material/Box';
import { GridItemProps, GridStateSnapshot, VirtuosoGrid } from 'react-virtuoso';
import { useLocation } from 'react-router-dom';
2024-04-29 15:00:37 +02:00
import { useTranslation } from 'react-i18next';
2024-10-05 16:09:34 +02:00
import { EmptyViewAbsoluteCentered } from '@/modules/core/components/placeholder/EmptyViewAbsoluteCentered.tsx';
import { LoadingPlaceholder } from '@/modules/core/components/placeholder/LoadingPlaceholder.tsx';
2024-10-05 19:21:26 +02:00
import { MangaCard } from '@/modules/manga/components/cards/MangaCard.tsx';
2024-10-05 19:33:09 +02:00
import { GridLayout } from '@/modules/library/contexts/LibraryOptionsContext.tsx';
2024-10-05 16:09:34 +02:00
import { useLocalStorage, useSessionStorage } from '@/modules/core/hooks/useStorage.tsx';
2024-10-05 19:24:45 +02:00
import { SelectableCollectionReturnType } from '@/modules/collection/hooks/useSelectableCollection.ts';
2024-10-05 16:09:34 +02:00
import { DEFAULT_FULL_FAB_HEIGHT } from '@/modules/core/components/buttons/StyledFab.tsx';
import { AppStorage } from '@/lib/AppStorage.ts';
2024-10-05 19:21:26 +02:00
import { MangaCardProps } from '@/modules/manga/MangaCard.types.tsx';
2024-07-08 18:02:50 +02:00
import { MangaType } from '@/lib/graphql/generated/graphql.ts';
2024-10-05 16:09:34 +02:00
import { useResizeObserver } from '@/modules/core/hooks/useResizeObserver.tsx';
import { useNavBarContext } from '@/components/context/NavbarContext.tsx';
2023-06-17 16:50:17 +02:00
const GridContainer = React.forwardRef<HTMLDivElement, GridTypeMap['props']>(({ children, ...props }, ref) => (
2024-09-14 03:01:07 +02:00
<Grid {...props} ref={ref} container spacing={1}>
2023-06-17 16:50:17 +02:00
{children}
</Grid>
));
2023-06-17 20:53:08 +02:00
const GridItemContainerWithDimension = (
dimensions: number,
itemWidth: number,
gridLayout?: GridLayout,
maxColumns: number = 12,
) => {
const itemsPerRow = Math.ceil(dimensions / itemWidth);
const columnsPerItem = gridLayout === GridLayout.List ? maxColumns : maxColumns / itemsPerRow;
2023-06-17 16:50:17 +02:00
2024-03-31 23:34:40 +02:00
// MUI GridProps and Virtuoso GridItemProps use different types for the "ref" prop which conflict with each other
return ({ children, ...itemProps }: GridTypeMap['props'] & Omit<Partial<GridItemProps>, 'ref'>) => (
2024-09-14 03:01:07 +02:00
<Grid {...itemProps} size={columnsPerItem}>
2023-06-17 20:53:08 +02:00
{children}
</Grid>
);
};
2023-06-17 16:50:17 +02:00
2024-07-08 18:02:50 +02:00
type TManga = MangaCardProps['manga'];
2023-12-25 21:37:45 +01:00
const createMangaCard = (
2024-07-08 18:02:50 +02:00
manga: TManga,
2023-12-25 21:37:45 +01:00
gridLayout?: GridLayout,
inLibraryIndicator?: boolean,
isSelectModeActive: boolean = false,
2024-07-08 18:02:50 +02:00
selectedMangaIds?: MangaType['id'][],
2023-12-25 21:37:45 +01:00
handleSelection?: DefaultGridProps['handleSelection'],
2024-01-26 20:50:51 +01:00
mode?: MangaCardProps['mode'],
2023-12-25 21:37:45 +01:00
) => (
<MangaCard
key={manga.id}
manga={manga}
gridLayout={gridLayout}
inLibraryIndicator={inLibraryIndicator}
selected={isSelectModeActive ? selectedMangaIds?.includes(manga.id) : null}
handleSelection={handleSelection}
2024-01-26 20:50:51 +01:00
mode={mode}
2023-12-25 21:37:45 +01:00
/>
2023-06-17 16:50:17 +02:00
);
2024-01-26 20:50:51 +01:00
type DefaultGridProps = Pick<MangaCardProps, 'mode'> & {
2023-06-17 16:50:17 +02:00
isLoading: boolean;
2024-07-08 18:02:50 +02:00
mangas: TManga[];
2023-06-17 16:50:17 +02:00
inLibraryIndicator?: boolean;
GridItemContainer: (props: GridTypeMap['props'] & Partial<GridItemProps>) => JSX.Element;
gridLayout?: GridLayout;
2023-12-25 21:37:45 +01:00
isSelectModeActive?: boolean;
2024-07-08 18:02:50 +02:00
selectedMangaIds?: Required<MangaType['id']>[];
handleSelection?: SelectableCollectionReturnType<MangaType['id']>['handleSelection'];
2023-06-17 16:50:17 +02:00
};
const HorizontalGrid = forwardRef(
(
{
isLoading,
mangas,
inLibraryIndicator,
GridItemContainer,
gridLayout,
isSelectModeActive,
selectedMangaIds,
handleSelection,
mode,
}: DefaultGridProps,
ref: ForwardedRef<HTMLDivElement | null>,
) => (
<Grid
ref={ref}
container
spacing={1}
2024-09-14 03:01:07 +02:00
sx={{
width: '100%',
overflowX: 'auto',
display: '-webkit-inline-box',
flexWrap: 'nowrap',
}}
>
{isLoading ? (
<LoadingPlaceholder />
) : (
mangas.map((manga) => (
<GridItemContainer key={manga.id}>
{createMangaCard(
manga,
gridLayout,
inLibraryIndicator,
isSelectModeActive,
selectedMangaIds,
handleSelection,
mode,
)}
</GridItemContainer>
))
)}
</Grid>
),
2023-06-17 16:50:17 +02:00
);
export const getGridSnapshotKey = (location: ReturnType<typeof useLocation>) =>
`MangaGrid-snapshot-location-${location.key}`;
const VerticalGrid = forwardRef(
(
{
isLoading,
mangas,
inLibraryIndicator,
GridItemContainer,
gridLayout,
hasNextPage,
loadMore,
isSelectModeActive,
selectedMangaIds,
handleSelection,
mode,
}: DefaultGridProps & {
hasNextPage: boolean;
loadMore: () => void;
},
ref: ForwardedRef<HTMLDivElement | null>,
) => {
const location = useLocation<{ snapshot?: GridStateSnapshot }>();
const snapshotSessionKey = getGridSnapshotKey(location);
const [snapshot] = useSessionStorage<GridStateSnapshot | undefined>(snapshotSessionKey, undefined);
2023-06-17 16:50:17 +02:00
const persistGridStateTimeout = useRef<NodeJS.Timeout | undefined>();
const persistGridState = (gridState: GridStateSnapshot) => {
const currentUrl = window.location.href;
clearTimeout(persistGridStateTimeout.current);
persistGridStateTimeout.current = setTimeout(() => {
const didLocationChange = currentUrl !== window.location.href;
if (didLocationChange) {
return;
2023-12-25 21:37:45 +01:00
}
AppStorage.session.setItem(snapshotSessionKey, gridState, false);
}, 250);
};
useEffect(() => clearTimeout(persistGridStateTimeout.current), [location.key, persistGridStateTimeout.current]);
return (
<>
<Box ref={ref}>
<VirtuosoGrid
useWindowScroll
overscan={window.innerHeight * 0.25}
totalCount={mangas.length}
components={{
List: GridContainer,
Item: GridItemContainer,
}}
restoreStateFrom={snapshot}
stateChanged={persistGridState}
endReached={() => loadMore()}
itemContent={(index) =>
createMangaCard(
mangas[index],
gridLayout,
inLibraryIndicator,
isSelectModeActive,
selectedMangaIds,
handleSelection,
mode,
)
}
/>
</Box>
{/* render div to prevent UI jumping around when showing/hiding loading placeholder */
/* eslint-disable-next-line no-nested-ternary */}
{isSelectModeActive && gridLayout === GridLayout.List ? (
<Box sx={{ paddingBottom: DEFAULT_FULL_FAB_HEIGHT }} />
) : // eslint-disable-next-line no-nested-ternary
isLoading ? (
<LoadingPlaceholder />
) : hasNextPage ? (
<div style={{ height: '75px' }} />
) : null}
</>
);
},
);
2021-01-20 15:26:52 +03:30
2024-04-27 22:29:23 +02:00
export interface IMangaGridProps
extends Omit<DefaultGridProps, 'GridItemContainer'>,
2024-04-29 15:29:33 +02:00
Partial<React.ComponentProps<typeof EmptyViewAbsoluteCentered>> {
2023-02-06 10:06:33 +01:00
hasNextPage: boolean;
2023-06-17 16:50:17 +02:00
loadMore: () => void;
horizontal?: boolean | undefined;
2023-02-06 10:06:33 +01:00
noFaces?: boolean | undefined;
2024-09-14 03:01:07 +02:00
gridWrapperProps?: Omit<BoxProps, 'ref'>;
2021-01-20 15:26:52 +03:30
}
2024-04-29 15:00:37 +02:00
export const MangaGrid: React.FC<IMangaGridProps> = ({
mangas,
isLoading,
message,
messageExtra,
hasNextPage,
loadMore,
gridLayout,
horizontal,
noFaces,
inLibraryIndicator,
isSelectModeActive,
selectedMangaIds,
handleSelection,
mode,
retry,
2024-09-14 03:01:07 +02:00
gridWrapperProps,
2024-04-29 15:00:37 +02:00
}) => {
const { t } = useTranslation();
2022-04-02 01:34:10 +01:00
const { navBarWidth } = useNavBarContext();
const gridRef = useRef<HTMLDivElement>(null);
const gridWrapperRef = useRef<HTMLDivElement>(null);
const [dimensions, setDimensions] = useState(
gridWrapperRef.current?.offsetWidth ?? Math.max(0, document.documentElement.offsetWidth - navBarWidth),
);
const [gridItemWidth] = useLocalStorage<number>('ItemWidth', 300);
2023-06-17 16:50:17 +02:00
const GridItemContainer = useMemo(
() => GridItemContainerWithDimension(dimensions, gridItemWidth, gridLayout),
2023-06-17 16:50:17 +02:00
[dimensions, gridItemWidth, gridLayout],
);
2022-04-02 01:34:10 +01:00
// always show vertical scrollbar to prevent https://github.com/Suwayomi/Suwayomi-WebUI/issues/758
useLayoutEffect(() => {
// in case "overflow" is currently set to "hidden" that (most likely) means that a MUI modal is open and locks the scrollbar
// once this modal is closed MUI restores the previous "overflow" value, thus, reverting the just set "overflow" value
let timeout: NodeJS.Timeout;
const changeStyle = (timeoutMS: number) => {
timeout = setTimeout(() => {
if (document.body.style.overflow.includes('hidden')) {
changeStyle(250);
return;
}
document.body.style.overflowY = gridLayout === GridLayout.List ? 'auto' : 'scroll';
}, timeoutMS);
};
changeStyle(0);
return () => {
clearTimeout(timeout);
};
}, [gridLayout]);
useLayoutEffect(
() => () => {
document.body.style.overflowY = 'auto';
},
[],
);
2024-07-23 00:56:16 +02:00
useResizeObserver(
gridWrapperRef,
useCallback(() => {
const getDimensions = () => {
const gridWidth = gridWrapperRef.current?.offsetWidth;
2022-04-02 01:34:10 +01:00
2024-07-23 00:56:16 +02:00
if (!gridWidth) {
return document.documentElement.offsetWidth - navBarWidth;
2024-07-23 00:56:16 +02:00
}
2022-04-02 01:34:10 +01:00
2024-07-23 00:56:16 +02:00
return gridWidth;
};
2023-06-17 16:50:17 +02:00
2024-07-23 00:56:16 +02:00
setDimensions(getDimensions());
}, [navBarWidth]),
2024-07-23 00:56:16 +02:00
);
2023-06-17 16:50:17 +02:00
2024-07-12 23:12:11 +02:00
useResizeObserver(
gridRef,
useCallback(
(entries, resizeObserver) => {
const gridHeight = entries[0].target.clientHeight;
const isScrollbarVisible = gridHeight > document.documentElement.clientHeight;
2024-07-12 23:12:11 +02:00
if (isLoading) {
return;
}
2024-07-12 23:12:11 +02:00
if (!gridHeight) {
return;
}
2024-07-12 23:12:11 +02:00
if (isScrollbarVisible) {
resizeObserver.disconnect();
return;
}
2024-07-12 23:12:11 +02:00
loadMore();
resizeObserver.disconnect();
2024-07-12 23:12:11 +02:00
},
[gridRef, loadMore, isLoading],
),
);
2023-06-17 16:50:17 +02:00
const hasNoItems = !isLoading && mangas.length === 0;
if (hasNoItems) {
2024-04-29 15:29:33 +02:00
return (
2024-04-29 15:00:37 +02:00
<EmptyViewAbsoluteCentered
noFaces={noFaces}
message={message ?? t('manga.error.label.no_mangas_found')}
messageExtra={messageExtra}
retry={retry}
/>
2024-04-29 15:29:33 +02:00
);
2021-01-20 15:26:52 +03:30
}
2021-01-22 21:11:00 +03:30
return (
2024-09-14 03:01:07 +02:00
<Box {...gridWrapperProps} ref={gridWrapperRef} sx={{ ...gridWrapperProps?.sx, overflow: 'hidden' }}>
2023-06-17 16:50:17 +02:00
{horizontal ? (
<HorizontalGrid
ref={gridRef}
2023-06-17 16:50:17 +02:00
isLoading={isLoading}
mangas={mangas}
inLibraryIndicator={inLibraryIndicator}
GridItemContainer={GridItemContainer}
gridLayout={gridLayout}
2023-12-25 21:37:45 +01:00
isSelectModeActive={isSelectModeActive}
selectedMangaIds={selectedMangaIds}
handleSelection={handleSelection}
2024-01-26 20:50:51 +01:00
mode={mode}
2023-06-17 16:50:17 +02:00
/>
) : (
<VerticalGrid
ref={gridRef}
2023-06-17 16:50:17 +02:00
isLoading={isLoading}
mangas={mangas}
inLibraryIndicator={inLibraryIndicator}
2023-06-17 16:50:17 +02:00
GridItemContainer={GridItemContainer}
hasNextPage={hasNextPage}
loadMore={loadMore}
gridLayout={gridLayout}
2023-12-25 21:37:45 +01:00
isSelectModeActive={isSelectModeActive}
selectedMangaIds={selectedMangaIds}
handleSelection={handleSelection}
2024-01-26 20:50:51 +01:00
mode={mode}
2023-06-17 16:50:17 +02:00
/>
)}
2024-09-14 03:01:07 +02:00
</Box>
2021-01-22 21:11:00 +03:30
);
2022-11-24 21:04:30 +01:00
};