diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/galleryImageClicked.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/galleryImageClicked.ts index 43f9355125..b52186d27f 100644 --- a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/galleryImageClicked.ts +++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/galleryImageClicked.ts @@ -1,10 +1,9 @@ import { createAction } from '@reduxjs/toolkit'; import type { AppStartListening } from 'app/store/middleware/listenerMiddleware'; -import { selectListImagesQueryArgs } from 'features/gallery/store/gallerySelectors'; +import { selectListImages2QueryArgs } from 'features/gallery/store/gallerySelectors'; import { imageToCompareChanged, selectionChanged } from 'features/gallery/store/gallerySlice'; import { imagesApi } from 'services/api/endpoints/images'; import type { ImageDTO } from 'services/api/types'; -import { imagesSelectors } from 'services/api/util'; export const galleryImageClicked = createAction<{ imageDTO: ImageDTO; @@ -31,16 +30,16 @@ export const addGalleryImageClickedListener = (startAppListening: AppStartListen effect: async (action, { dispatch, getState }) => { const { imageDTO, shiftKey, ctrlKey, metaKey, altKey } = action.payload; const state = getState(); - const queryArgs = selectListImagesQueryArgs(state); - const { data: listImagesData } = imagesApi.endpoints.listImages.select(queryArgs)(state); - - if (!listImagesData) { + const queryArgs = selectListImages2QueryArgs(state); + const queryResult = imagesApi.endpoints.listImages2.select(queryArgs)(state); + if (!queryResult.data) { // Should never happen if we have clicked a gallery image return; } - const imageDTOs = imagesSelectors.selectAll(listImagesData); + const imageDTOs = queryResult.data.items; const selection = state.gallery.selection; + console.log({ queryArgs, imageDTOs, selection }); if (altKey) { if (state.gallery.imageToCompare?.image_name === imageDTO.image_name) { diff --git a/invokeai/frontend/web/src/common/components/IAIDndImageIcon.tsx b/invokeai/frontend/web/src/common/components/IAIDndImageIcon.tsx index 650a0b6a14..e2efec5eb7 100644 --- a/invokeai/frontend/web/src/common/components/IAIDndImageIcon.tsx +++ b/invokeai/frontend/web/src/common/components/IAIDndImageIcon.tsx @@ -1,49 +1,40 @@ -import type { SystemStyleObject } from '@invoke-ai/ui-library'; +import type { IconButtonProps, SystemStyleObject } from '@invoke-ai/ui-library'; import { IconButton } from '@invoke-ai/ui-library'; -import type { MouseEvent, ReactElement } from 'react'; -import { memo, useMemo } from 'react'; +import type { MouseEvent } from 'react'; +import { memo } from 'react'; -type Props = { +const sx: SystemStyleObject = { + minW: 0, + svg: { + transitionProperty: 'common', + transitionDuration: 'normal', + fill: 'base.100', + _hover: { fill: 'base.50' }, + filter: 'drop-shadow(0px 0px 0.1rem var(--invoke-colors-base-800))', + }, +}; + +type Props = Omit & { onClick: (event: MouseEvent) => void; tooltip: string; - icon?: ReactElement; - styleOverrides?: SystemStyleObject; }; const IAIDndImageIcon = (props: Props) => { - const { onClick, tooltip, icon, styleOverrides } = props; - - const sx = useMemo( - () => ({ - position: 'absolute', - top: 1, - insetInlineEnd: 1, - p: 0, - minW: 0, - svg: { - transitionProperty: 'common', - transitionDuration: 'normal', - fill: 'base.100', - _hover: { fill: 'base.50' }, - filter: 'drop-shadow(0px 0px 0.1rem var(--invoke-colors-base-800))', - }, - ...styleOverrides, - }), - [styleOverrides] - ); + const { onClick, tooltip, icon, ...rest } = props; return ( ); }; +// export default IAIDndImageIcon; export default memo(IAIDndImageIcon); diff --git a/invokeai/frontend/web/src/features/controlAdapters/components/ControlAdapterImagePreview.tsx b/invokeai/frontend/web/src/features/controlAdapters/components/ControlAdapterImagePreview.tsx index bf1c7dce9f..b585bd1d57 100644 --- a/invokeai/frontend/web/src/features/controlAdapters/components/ControlAdapterImagePreview.tsx +++ b/invokeai/frontend/web/src/features/controlAdapters/components/ControlAdapterImagePreview.tsx @@ -1,4 +1,3 @@ -import type { SystemStyleObject } from '@invoke-ai/ui-library'; import { Box, Flex, Spinner } from '@invoke-ai/ui-library'; import { skipToken } from '@reduxjs/toolkit/query'; import { createMemoizedSelector } from 'app/store/createMemoizedSelector'; @@ -185,7 +184,7 @@ const ControlAdapterImagePreview = ({ isSmall, id }: Props) => { /> - <> + : undefined} @@ -195,15 +194,13 @@ const ControlAdapterImagePreview = ({ isSmall, id }: Props) => { onClick={handleSaveControlImage} icon={controlImage ? : undefined} tooltip={t('controlnet.saveControlImage')} - styleOverrides={saveControlImageStyleOverrides} /> : undefined} tooltip={t('controlnet.setControlImageDimensions')} - styleOverrides={setControlImageDimensionsStyleOverrides} /> - + {pendingControlImages.includes(id) && ( { }; export default memo(ControlAdapterImagePreview); - -const saveControlImageStyleOverrides: SystemStyleObject = { mt: 6 }; -const setControlImageDimensionsStyleOverrides: SystemStyleObject = { mt: 12 }; diff --git a/invokeai/frontend/web/src/features/controlLayers/components/ControlAndIPAdapter/ControlAdapterImagePreview.tsx b/invokeai/frontend/web/src/features/controlLayers/components/ControlAndIPAdapter/ControlAdapterImagePreview.tsx index 4d93eb12ec..c7faade4fa 100644 --- a/invokeai/frontend/web/src/features/controlLayers/components/ControlAndIPAdapter/ControlAdapterImagePreview.tsx +++ b/invokeai/frontend/web/src/features/controlLayers/components/ControlAndIPAdapter/ControlAdapterImagePreview.tsx @@ -1,4 +1,3 @@ -import type { SystemStyleObject } from '@invoke-ai/ui-library'; import { Box, Flex, Spinner, useShiftModifier } from '@invoke-ai/ui-library'; import { skipToken } from '@reduxjs/toolkit/query'; import { useAppDispatch, useAppSelector } from 'app/store/storeHooks'; @@ -180,13 +179,13 @@ export const ControlAdapterImagePreview = memo( onClick={handleSaveControlImage} icon={controlImage ? : undefined} tooltip={t('controlnet.saveControlImage')} - styleOverrides={saveControlImageStyleOverrides} + mt={6} /> : undefined} tooltip={shift ? t('controlnet.setControlImageDimensionsForce') : t('controlnet.setControlImageDimensions')} - styleOverrides={setControlImageDimensionsStyleOverrides} + mt={12} /> @@ -212,6 +211,3 @@ export const ControlAdapterImagePreview = memo( ); ControlAdapterImagePreview.displayName = 'ControlAdapterImagePreview'; - -const saveControlImageStyleOverrides: SystemStyleObject = { mt: 6 }; -const setControlImageDimensionsStyleOverrides: SystemStyleObject = { mt: 12 }; diff --git a/invokeai/frontend/web/src/features/controlLayers/components/ControlAndIPAdapter/IPAdapterImagePreview.tsx b/invokeai/frontend/web/src/features/controlLayers/components/ControlAndIPAdapter/IPAdapterImagePreview.tsx index 93d493bcbc..da93ccef09 100644 --- a/invokeai/frontend/web/src/features/controlLayers/components/ControlAndIPAdapter/IPAdapterImagePreview.tsx +++ b/invokeai/frontend/web/src/features/controlLayers/components/ControlAndIPAdapter/IPAdapterImagePreview.tsx @@ -1,4 +1,3 @@ -import type { SystemStyleObject } from '@invoke-ai/ui-library'; import { Flex, useShiftModifier } from '@invoke-ai/ui-library'; import { skipToken } from '@reduxjs/toolkit/query'; import { useAppDispatch, useAppSelector } from 'app/store/storeHooks'; @@ -100,7 +99,7 @@ export const IPAdapterImagePreview = memo( onClick={handleSetControlImageToDimensions} icon={controlImage ? : undefined} tooltip={shift ? t('controlnet.setControlImageDimensionsForce') : t('controlnet.setControlImageDimensions')} - styleOverrides={setControlImageDimensionsStyleOverrides} + mt={6} /> @@ -109,5 +108,3 @@ export const IPAdapterImagePreview = memo( ); IPAdapterImagePreview.displayName = 'IPAdapterImagePreview'; - -const setControlImageDimensionsStyleOverrides: SystemStyleObject = { mt: 6 }; diff --git a/invokeai/frontend/web/src/features/controlLayers/components/IILayer/InitialImagePreview.tsx b/invokeai/frontend/web/src/features/controlLayers/components/IILayer/InitialImagePreview.tsx index 9053c0c123..e3896c7df1 100644 --- a/invokeai/frontend/web/src/features/controlLayers/components/IILayer/InitialImagePreview.tsx +++ b/invokeai/frontend/web/src/features/controlLayers/components/IILayer/InitialImagePreview.tsx @@ -1,4 +1,3 @@ -import type { SystemStyleObject } from '@invoke-ai/ui-library'; import { Flex, useShiftModifier } from '@invoke-ai/ui-library'; import { skipToken } from '@reduxjs/toolkit/query'; import { useAppDispatch, useAppSelector } from 'app/store/storeHooks'; @@ -86,7 +85,6 @@ export const InitialImagePreview = memo(({ image, onChangeImage, droppableData, imageDTO={imageDTO} postUploadAction={postUploadAction} /> - <> : undefined} tooltip={shift ? t('controlnet.setControlImageDimensionsForce') : t('controlnet.setControlImageDimensions')} - styleOverrides={useSizeStyleOverrides} + mt={6} /> @@ -105,5 +103,3 @@ export const InitialImagePreview = memo(({ image, onChangeImage, droppableData, }); InitialImagePreview.displayName = 'InitialImagePreview'; - -const useSizeStyleOverrides: SystemStyleObject = { mt: 6 }; diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImage.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImage.tsx index e5e216c97c..341fcb85e5 100644 --- a/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImage.tsx +++ b/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImage.tsx @@ -5,10 +5,10 @@ import { $customStarUI } from 'app/store/nanostores/customStarUI'; import { useAppDispatch, useAppSelector } from 'app/store/storeHooks'; import IAIDndImage from 'common/components/IAIDndImage'; import IAIDndImageIcon from 'common/components/IAIDndImageIcon'; -import IAIFillSkeleton from 'common/components/IAIFillSkeleton'; import { imagesToDeleteSelected } from 'features/deleteImageModal/store/slice'; import type { GallerySelectionDraggableData, ImageDraggableData, TypesafeDraggableData } from 'features/dnd/types'; import { getGalleryImageDataTestId } from 'features/gallery/components/ImageGrid/getGalleryImageDataTestId'; +import { imageItemContainerTestId } from 'features/gallery/components/ImageGrid/ImageGridItemContainer'; import { useMultiselect } from 'features/gallery/hooks/useMultiselect'; import { useScrollIntoView } from 'features/gallery/hooks/useScrollIntoView'; import { imageToCompareChanged, isImageViewerOpenChanged } from 'features/gallery/store/gallerySlice'; @@ -16,13 +16,10 @@ import type { MouseEvent } from 'react'; import { memo, useCallback, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { PiStarBold, PiStarFill, PiTrashSimpleFill } from 'react-icons/pi'; -import { useGetImageDTOQuery, useStarImagesMutation, useUnstarImagesMutation } from 'services/api/endpoints/images'; +import { useStarImagesMutation, useUnstarImagesMutation } from 'services/api/endpoints/images'; +import type { ImageDTO } from 'services/api/types'; const imageSx: SystemStyleObject = { w: 'full', h: 'full' }; -const imageIconStyleOverrides: SystemStyleObject = { - bottom: 2, - top: 'auto', -}; const boxSx: SystemStyleObject = { containerType: 'inline-size', }; @@ -34,24 +31,22 @@ const badgeSx: SystemStyleObject = { }; interface HoverableImageProps { - imageName: string; + imageDTO: ImageDTO; index: number; } -const GalleryImage = (props: HoverableImageProps) => { +const GalleryImage = ({ index, imageDTO }: HoverableImageProps) => { const dispatch = useAppDispatch(); - const { imageName } = props; - const { currentData: imageDTO } = useGetImageDTOQuery(imageName); const shift = useShiftModifier(); const { t } = useTranslation(); const selectedBoardId = useAppSelector((s) => s.gallery.selectedBoardId); const alwaysShowImageSizeBadge = useAppSelector((s) => s.gallery.alwaysShowImageSizeBadge); - const isSelectedForCompare = useAppSelector((s) => s.gallery.imageToCompare?.image_name === imageName); + const isSelectedForCompare = useAppSelector((s) => s.gallery.imageToCompare?.image_name === imageDTO.image_name); const { handleClick, isSelected, areMultiplesSelected } = useMultiselect(imageDTO); const customStarUi = useStore($customStarUI); - const imageContainerRef = useScrollIntoView(isSelected, props.index, areMultiplesSelected); + const imageContainerRef = useScrollIntoView(isSelected, index, areMultiplesSelected); const handleDelete = useCallback( (e: MouseEvent) => { @@ -114,32 +109,28 @@ const GalleryImage = (props: HoverableImageProps) => { }, []); const starIcon = useMemo(() => { - if (imageDTO?.starred) { + if (imageDTO.starred) { return customStarUi ? customStarUi.on.icon : ; } - if (!imageDTO?.starred && isHovered) { + if (!imageDTO.starred && isHovered) { return customStarUi ? customStarUi.off.icon : ; } - }, [imageDTO?.starred, isHovered, customStarUi]); + }, [imageDTO.starred, isHovered, customStarUi]); const starTooltip = useMemo(() => { - if (imageDTO?.starred) { + if (imageDTO.starred) { return customStarUi ? customStarUi.off.text : 'Unstar'; } - if (!imageDTO?.starred) { + if (!imageDTO.starred) { return customStarUi ? customStarUi.on.text : 'Star'; } return ''; - }, [imageDTO?.starred, customStarUi]); + }, [imageDTO.starred, customStarUi]); - const dataTestId = useMemo(() => getGalleryImageDataTestId(imageDTO?.image_name), [imageDTO?.image_name]); - - if (!imageDTO) { - return ; - } + const dataTestId = useMemo(() => getGalleryImageDataTestId(imageDTO.image_name), [imageDTO.image_name]); return ( - + { pointerEvents="none" >{`${imageDTO.width}x${imageDTO.height}`} )} - + {isHovered && shift && ( } - tooltip={t('gallery.deleteImage', { count: 1 })} - styleOverrides={imageIconStyleOverrides} + tooltip={t('gallery.deleteImage_one')} + position="absolute" + bottom={1} + insetInlineEnd={1} /> )} diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImageGrid.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImageGrid.tsx index 608205c894..ddedfb6db0 100644 --- a/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImageGrid.tsx +++ b/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImageGrid.tsx @@ -1,120 +1,41 @@ -import { Box, Button, Flex } from '@invoke-ai/ui-library'; -import type { EntityId } from '@reduxjs/toolkit'; +import { Box, Flex, Grid, IconButton } from '@invoke-ai/ui-library'; +import { EMPTY_ARRAY } from 'app/store/constants'; import { useAppSelector } from 'app/store/storeHooks'; import { IAINoContentFallback } from 'common/components/IAIImageFallback'; -import { overlayScrollbarsParams } from 'common/components/OverlayScrollbars/constants'; -import { virtuosoGridRefs } from 'features/gallery/components/ImageGrid/types'; import { useGalleryHotkeys } from 'features/gallery/hooks/useGalleryHotkeys'; -import { useGalleryImages } from 'features/gallery/hooks/useGalleryImages'; -import { useOverlayScrollbars } from 'overlayscrollbars-react'; -import type { CSSProperties } from 'react'; -import { memo, useCallback, useEffect, useRef, useState } from 'react'; +import { useGalleryPagination } from 'features/gallery/hooks/useGalleryImages'; +import { selectListImages2QueryArgs } from 'features/gallery/store/gallerySelectors'; +import { memo } from 'react'; import { useTranslation } from 'react-i18next'; -import { PiImageBold, PiWarningCircleBold } from 'react-icons/pi'; -import type { GridComponents, ItemContent, ListRange, VirtuosoGridHandle } from 'react-virtuoso'; -import { VirtuosoGrid } from 'react-virtuoso'; -import { useBoardTotal } from 'services/api/hooks/useBoardTotal'; +import { + PiCaretDoubleLeftBold, + PiCaretDoubleRightBold, + PiCaretLeftBold, + PiCaretRightBold, + PiImageBold, + PiWarningCircleBold, +} from 'react-icons/pi'; +import { useListImages2Query } from 'services/api/endpoints/images'; +import type { ImageDTO } from 'services/api/types'; import GalleryImage from './GalleryImage'; -import ImageGridItemContainer from './ImageGridItemContainer'; -import ImageGridListContainer from './ImageGridListContainer'; -const components: GridComponents = { - Item: ImageGridItemContainer, - List: ImageGridListContainer, -}; - -const virtuosoStyles: CSSProperties = { height: '100%' }; +export const imageListContainerTestId = 'image-list-container'; +export const imageItemContainerTestId = 'image-item-container'; const GalleryImageGrid = () => { - const { t } = useTranslation(); - const rootRef = useRef(null); - const [scroller, setScroller] = useState(null); - const [initialize, osInstance] = useOverlayScrollbars(overlayScrollbarsParams); - const selectedBoardId = useAppSelector((s) => s.gallery.selectedBoardId); - const { currentViewTotal } = useBoardTotal(selectedBoardId); - const virtuosoRangeRef = useRef(null); - const virtuosoRef = useRef(null); - const { - areMoreImagesAvailable, - handleLoadMoreImages, - queryResult: { currentData, isFetching, isSuccess, isError }, - } = useGalleryImages(); useGalleryHotkeys(); - const itemContentFunc: ItemContent = useCallback( - (index, imageName) => , - [] - ); - - useEffect(() => { - // Initialize the gallery's custom scrollbar - const { current: root } = rootRef; - if (scroller && root) { - initialize({ - target: root, - elements: { - viewport: scroller, - }, - }); - } - return () => osInstance()?.destroy(); - }, [scroller, initialize, osInstance]); - - const onRangeChanged = useCallback((range: ListRange) => { - virtuosoRangeRef.current = range; - }, []); - - useEffect(() => { - virtuosoGridRefs.set({ rootRef, virtuosoRangeRef, virtuosoRef }); - return () => { - virtuosoGridRefs.set({}); - }; - }, []); - - if (!currentData) { - return ( - - - - ); - } - - if (isSuccess && currentData?.ids.length === 0) { - return ( - - - - ); - } - - if (isSuccess && currentData) { - return ( - <> - - - - - - ); - } + const { t } = useTranslation(); + const galleryImageMinimumWidth = useAppSelector((s) => s.gallery.galleryImageMinimumWidth); + const queryArgs = useAppSelector(selectListImages2QueryArgs); + const { imageDTOs, isLoading, isSuccess, isError } = useListImages2Query(queryArgs, { + selectFromResult: ({ data, isLoading, isSuccess, isError }) => ({ + imageDTOs: data?.items ?? EMPTY_ARRAY, + isLoading, + isSuccess, + isError, + }), + }); if (isError) { return ( @@ -124,7 +45,63 @@ const GalleryImageGrid = () => { ); } - return null; + if (isLoading) { + return ( + + + + ); + } + + if (imageDTOs.length === 0) { + return ( + + + + ); + } + + return ( + <> + + + {imageDTOs.map((imageDTO, index) => ( + + ))} + + + + + ); }; export default memo(GalleryImageGrid); + +const GalleryImageContainer = memo(({ imageDTO, index }: { imageDTO: ImageDTO; index: number }) => { + return ( + + + + ); +}); + +GalleryImageContainer.displayName = 'GalleryImageContainer'; + +const GalleryPagination = memo(() => { + const { first, prev, next, last, isFirstEnabled, isPrevEnabled, isNextEnabled, isLastEnabled } = + useGalleryPagination(); + return ( + + } onClick={first} isDisabled={!isFirstEnabled} /> + } onClick={prev} isDisabled={!isPrevEnabled} /> + } onClick={next} isDisabled={!isNextEnabled} /> + } onClick={last} isDisabled={!isLastEnabled} /> + + ); +}); + +GalleryPagination.displayName = 'GalleryPagination'; diff --git a/invokeai/frontend/web/src/features/gallery/components/NextPrevImageButtons.tsx b/invokeai/frontend/web/src/features/gallery/components/NextPrevImageButtons.tsx index 19368455e3..22592f90fc 100644 --- a/invokeai/frontend/web/src/features/gallery/components/NextPrevImageButtons.tsx +++ b/invokeai/frontend/web/src/features/gallery/components/NextPrevImageButtons.tsx @@ -1,6 +1,6 @@ import type { ChakraProps } from '@invoke-ai/ui-library'; import { Box, Flex, IconButton, Spinner } from '@invoke-ai/ui-library'; -import { useGalleryImages } from 'features/gallery/hooks/useGalleryImages'; +import { useGalleryImages, useGalleryPagination } from 'features/gallery/hooks/useGalleryImages'; import { useGalleryNavigation } from 'features/gallery/hooks/useGalleryNavigation'; import { memo } from 'react'; import { useTranslation } from 'react-i18next'; @@ -15,12 +15,9 @@ const NextPrevImageButtons = () => { const { t } = useTranslation(); const { prevImage, nextImage, isOnFirstImage, isOnLastImage } = useGalleryNavigation(); + const { isFetching } = useGalleryImages().queryResult; - const { - areMoreImagesAvailable, - handleLoadMoreImages, - queryResult: { isFetching }, - } = useGalleryImages(); + const { isNextEnabled, next } = useGalleryPagination(); return ( @@ -47,17 +44,17 @@ const NextPrevImageButtons = () => { sx={nextPrevButtonStyles} /> )} - {isOnLastImage && areMoreImagesAvailable && !isFetching && ( + {isOnLastImage && isNextEnabled && !isFetching && ( } variant="unstyled" - onClick={handleLoadMoreImages} + onClick={next} boxSize={16} sx={nextPrevButtonStyles} /> )} - {isOnLastImage && areMoreImagesAvailable && isFetching && ( + {isOnLastImage && isNextEnabled && isFetching && ( diff --git a/invokeai/frontend/web/src/features/gallery/hooks/useGalleryHotkeys.ts b/invokeai/frontend/web/src/features/gallery/hooks/useGalleryHotkeys.ts index 931d93272b..b280f8f9cd 100644 --- a/invokeai/frontend/web/src/features/gallery/hooks/useGalleryHotkeys.ts +++ b/invokeai/frontend/web/src/features/gallery/hooks/useGalleryHotkeys.ts @@ -1,10 +1,13 @@ import { useAppSelector } from 'app/store/storeHooks'; import { isStagingSelector } from 'features/canvas/store/canvasSelectors'; -import { useGalleryImages } from 'features/gallery/hooks/useGalleryImages'; -import { useGalleryNavigation } from 'features/gallery/hooks/useGalleryNavigation'; +import { useGalleryPagination } from 'features/gallery/hooks/useGalleryImages'; +import { selectListImages2QueryArgs } from 'features/gallery/store/gallerySelectors'; import { activeTabNameSelector } from 'features/ui/store/uiSelectors'; import { useMemo } from 'react'; import { useHotkeys } from 'react-hotkeys-hook'; +import { useListImages2Query } from 'services/api/endpoints/images'; + +import { useGalleryNavigation } from './useGalleryNavigation'; /** * Registers gallery hotkeys. This hook is a singleton. @@ -17,21 +20,30 @@ export const useGalleryHotkeys = () => { return activeTabName !== 'canvas' || !isStaging; }, [activeTabName, isStaging]); - const { - areMoreImagesAvailable, - handleLoadMoreImages, - queryResult: { isFetching }, - } = useGalleryImages(); + const { next, prev, isNextEnabled, isPrevEnabled } = useGalleryPagination(); + const queryArgs = useAppSelector(selectListImages2QueryArgs); + const queryResult = useListImages2Query(queryArgs); - const { handleLeftImage, handleRightImage, handleUpImage, handleDownImage, isOnLastImage, areImagesBelowCurrent } = - useGalleryNavigation(); + const { + handleLeftImage, + handleRightImage, + handleUpImage, + handleDownImage, + areImagesBelowCurrent, + isOnFirstImageOfView, + isOnLastImageOfView, + } = useGalleryNavigation(); useHotkeys( ['left', 'alt+left'], (e) => { + if (isOnFirstImageOfView && isPrevEnabled && !queryResult.isFetching) { + prev(); + return; + } canNavigateGallery && handleLeftImage(e.altKey); }, - [handleLeftImage, canNavigateGallery] + [handleLeftImage, canNavigateGallery, isOnFirstImageOfView] ); useHotkeys( @@ -40,15 +52,15 @@ export const useGalleryHotkeys = () => { if (!canNavigateGallery) { return; } - if (isOnLastImage && areMoreImagesAvailable && !isFetching) { - handleLoadMoreImages(); + if (isOnLastImageOfView && isNextEnabled && !queryResult.isFetching) { + next(); return; } - if (!isOnLastImage) { + if (!isOnLastImageOfView) { handleRightImage(e.altKey); } }, - [isOnLastImage, areMoreImagesAvailable, handleLoadMoreImages, isFetching, handleRightImage, canNavigateGallery] + [isOnLastImageOfView, next, isNextEnabled, queryResult.isFetching, handleRightImage, canNavigateGallery] ); useHotkeys( @@ -63,13 +75,13 @@ export const useGalleryHotkeys = () => { useHotkeys( ['down', 'alt+down'], (e) => { - if (!areImagesBelowCurrent && areMoreImagesAvailable && !isFetching) { - handleLoadMoreImages(); + if (!areImagesBelowCurrent && isNextEnabled && !queryResult.isFetching) { + next(); return; } handleDownImage(e.altKey); }, { preventDefault: true }, - [areImagesBelowCurrent, areMoreImagesAvailable, handleLoadMoreImages, isFetching, handleDownImage] + [areImagesBelowCurrent, next, isNextEnabled, queryResult.isFetching, handleDownImage] ); }; diff --git a/invokeai/frontend/web/src/features/gallery/hooks/useGalleryImages.ts b/invokeai/frontend/web/src/features/gallery/hooks/useGalleryImages.ts index b3310d5e34..6e84a6bfd9 100644 --- a/invokeai/frontend/web/src/features/gallery/hooks/useGalleryImages.ts +++ b/invokeai/frontend/web/src/features/gallery/hooks/useGalleryImages.ts @@ -1,38 +1,120 @@ +import { EMPTY_ARRAY } from 'app/store/constants'; import { useAppDispatch, useAppSelector } from 'app/store/storeHooks'; -import { selectListImagesQueryArgs } from 'features/gallery/store/gallerySelectors'; -import { moreImagesLoaded } from 'features/gallery/store/gallerySlice'; +import { selectListImages2QueryArgs } from 'features/gallery/store/gallerySelectors'; +import { offsetChanged } from 'features/gallery/store/gallerySlice'; import { useCallback, useMemo } from 'react'; import { useGetBoardAssetsTotalQuery, useGetBoardImagesTotalQuery } from 'services/api/endpoints/boards'; -import { useListImagesQuery } from 'services/api/endpoints/images'; +import { useListImages2Query } from 'services/api/endpoints/images'; + +const LIMIT = 20; -/** - * Provides access to the gallery images and a way to imperatively fetch more. - */ export const useGalleryImages = () => { - const dispatch = useAppDispatch(); - const galleryView = useAppSelector((s) => s.gallery.galleryView); - const queryArgs = useAppSelector(selectListImagesQueryArgs); - const queryResult = useListImagesQuery(queryArgs); - const selectedBoardId = useAppSelector((s) => s.gallery.selectedBoardId); - const { data: assetsTotal } = useGetBoardAssetsTotalQuery(selectedBoardId); - const { data: imagesTotal } = useGetBoardImagesTotalQuery(selectedBoardId); - const currentViewTotal = useMemo( - () => (galleryView === 'images' ? imagesTotal?.total : assetsTotal?.total), - [assetsTotal?.total, galleryView, imagesTotal?.total] - ); - const areMoreImagesAvailable = useMemo(() => { - if (!currentViewTotal || !queryResult.data) { - return false; - } - return queryResult.data.ids.length < currentViewTotal; - }, [queryResult.data, currentViewTotal]); - const handleLoadMoreImages = useCallback(() => { - dispatch(moreImagesLoaded()); - }, [dispatch]); - + const queryArgs = useAppSelector(selectListImages2QueryArgs); + const queryResult = useListImages2Query(queryArgs); + const imageDTOs = useMemo(() => queryResult.data?.items ?? EMPTY_ARRAY, [queryResult.data]); return { - areMoreImagesAvailable, - handleLoadMoreImages, + imageDTOs, queryResult, }; }; + +export const useGalleryPagination = () => { + const dispatch = useAppDispatch(); + const offset = useAppSelector((s) => s.gallery.offset); + const galleryView = useAppSelector((s) => s.gallery.galleryView); + const selectedBoardId = useAppSelector((s) => s.gallery.selectedBoardId); + const queryArgs = useAppSelector(selectListImages2QueryArgs); + const { count } = useListImages2Query(queryArgs, { + selectFromResult: ({ data }) => ({ count: data?.items.length ?? 0 }), + }); + const { data: assetsTotal } = useGetBoardAssetsTotalQuery(selectedBoardId); + const { data: imagesTotal } = useGetBoardImagesTotalQuery(selectedBoardId); + const total = useMemo(() => { + if (galleryView === 'images') { + return imagesTotal?.total ?? 0; + } else { + return assetsTotal?.total ?? 0; + } + }, [assetsTotal?.total, galleryView, imagesTotal?.total]); + const page = useMemo(() => Math.floor(offset / LIMIT), [offset]); + const pages = useMemo(() => Math.floor(total / LIMIT), [total]); + const isNextEnabled = useMemo(() => { + if (!count) { + return false; + } + return page < pages; + }, [count, page, pages]); + const isPrevEnabled = useMemo(() => { + if (!count) { + return false; + } + return offset > 0; + }, [count, offset]); + const next = useCallback(() => { + dispatch(offsetChanged(offset + LIMIT)); + }, [dispatch, offset]); + const prev = useCallback(() => { + dispatch(offsetChanged(Math.max(offset - LIMIT, 0))); + }, [dispatch, offset]); + const goToPage = useCallback( + (page: number) => { + const p = Math.max(0, Math.min(page, pages - 1)); + dispatch(offsetChanged(p)); + }, + [dispatch, pages] + ); + const first = useCallback(() => { + dispatch(offsetChanged(0)); + }, [dispatch]); + const last = useCallback(() => { + dispatch(offsetChanged(pages * LIMIT)); + }, [dispatch, pages]); + // calculate the page buttons to display - current page with 3 around it + const pageButtons = useMemo(() => { + const buttons = []; + const start = Math.max(0, page - 3); + const end = Math.min(pages, start + 6); + for (let i = start; i < end; i++) { + buttons.push(i); + } + return buttons; + }, [page, pages]); + const isFirstEnabled = useMemo(() => page > 0, [page]); + const isLastEnabled = useMemo(() => page < pages - 1, [page, pages]); + + const api = useMemo( + () => ({ + count, + total, + page, + pages, + isNextEnabled, + isPrevEnabled, + next, + prev, + goToPage, + first, + last, + pageButtons, + isFirstEnabled, + isLastEnabled, + }), + [ + count, + total, + page, + pages, + isNextEnabled, + isPrevEnabled, + next, + prev, + goToPage, + first, + last, + pageButtons, + isFirstEnabled, + isLastEnabled, + ] + ); + return api; +}; diff --git a/invokeai/frontend/web/src/features/gallery/hooks/useGalleryNavigation.ts b/invokeai/frontend/web/src/features/gallery/hooks/useGalleryNavigation.ts index ce6b152577..ad9a2b48f4 100644 --- a/invokeai/frontend/web/src/features/gallery/hooks/useGalleryNavigation.ts +++ b/invokeai/frontend/web/src/features/gallery/hooks/useGalleryNavigation.ts @@ -11,7 +11,6 @@ import { getScrollToIndexAlign } from 'features/gallery/util/getScrollToIndexAli import { clamp } from 'lodash-es'; import { useCallback, useMemo } from 'react'; import type { ImageDTO } from 'services/api/types'; -import { imagesSelectors } from 'services/api/util'; /** * This hook is used to navigate the gallery using the arrow keys. @@ -29,12 +28,13 @@ import { imagesSelectors } from 'services/api/util'; */ const getImagesPerRow = (): number => { const widthOfGalleryImage = - document.querySelector(`[data-testid="${imageItemContainerTestId}"]`)?.getBoundingClientRect().width ?? 1; + document.querySelector(`.${imageItemContainerTestId}`)?.getBoundingClientRect().width ?? 1; const widthOfGalleryGrid = document.querySelector(`[data-testid="${imageListContainerTestId}"]`)?.getBoundingClientRect().width ?? 0; const imagesPerRow = Math.round(widthOfGalleryGrid / widthOfGalleryImage); + console.log({ widthOfGalleryImage, widthOfGalleryGrid, imagesPerRow }); return imagesPerRow; }; @@ -86,6 +86,7 @@ const getUpImage = (images: ImageDTO[], currentIndex: number) => { const isOnFirstRow = currentIndex < imagesPerRow; const index = isOnFirstRow ? currentIndex : clamp(currentIndex - imagesPerRow, 0, images.length - 1); const image = images[index]; + console.log({ imagesPerRow, isOnFirstRow }); return { index, image }; }; @@ -115,6 +116,8 @@ type UseGalleryNavigationReturn = { isOnFirstImage: boolean; isOnLastImage: boolean; areImagesBelowCurrent: boolean; + isOnFirstImageOfView: boolean; + isOnLastImageOfView: boolean; }; /** @@ -134,23 +137,19 @@ export const useGalleryNavigation = (): UseGalleryNavigationReturn => { return lastSelected; } }); - const { - queryResult: { data }, - } = useGalleryImages(); - const loadedImagesCount = useMemo(() => data?.ids.length ?? 0, [data?.ids.length]); + const { imageDTOs } = useGalleryImages(); + const loadedImagesCount = useMemo(() => imageDTOs.length, [imageDTOs.length]); const lastSelectedImageIndex = useMemo(() => { - if (!data || !lastSelectedImage) { + if (imageDTOs.length === 0 || !lastSelectedImage) { return 0; } - return imagesSelectors.selectAll(data).findIndex((i) => i.image_name === lastSelectedImage.image_name); - }, [lastSelectedImage, data]); + return imageDTOs.findIndex((i) => i.image_name === lastSelectedImage.image_name); + }, [imageDTOs, lastSelectedImage]); const handleNavigation = useCallback( (direction: 'left' | 'right' | 'up' | 'down', alt?: boolean) => { - if (!data) { - return; - } - const { index, image } = getImageFuncs[direction](imagesSelectors.selectAll(data), lastSelectedImageIndex); + const { index, image } = getImageFuncs[direction](imageDTOs, lastSelectedImageIndex); + console.log({ direction, index, image, imageDTOs, lastSelectedImageIndex }); if (!image || index === lastSelectedImageIndex) { return; } @@ -161,7 +160,7 @@ export const useGalleryNavigation = (): UseGalleryNavigationReturn => { } scrollToImage(image.image_name, index); }, - [data, lastSelectedImageIndex, dispatch] + [imageDTOs, lastSelectedImageIndex, dispatch] ); const isOnFirstImage = useMemo(() => lastSelectedImageIndex === 0, [lastSelectedImageIndex]); @@ -176,6 +175,14 @@ export const useGalleryNavigation = (): UseGalleryNavigationReturn => { return lastSelectedImageIndex + imagesPerRow < loadedImagesCount; }, [lastSelectedImageIndex, loadedImagesCount]); + const isOnFirstImageOfView = useMemo(() => { + return lastSelectedImageIndex === 0; + }, [lastSelectedImageIndex]); + + const isOnLastImageOfView = useMemo(() => { + return lastSelectedImageIndex === loadedImagesCount - 1; + }, [lastSelectedImageIndex, loadedImagesCount]); + const handleLeftImage = useCallback( (alt?: boolean) => { handleNavigation('left', alt); @@ -222,5 +229,7 @@ export const useGalleryNavigation = (): UseGalleryNavigationReturn => { areImagesBelowCurrent, nextImage, prevImage, + isOnFirstImageOfView, + isOnLastImageOfView, }; }; diff --git a/invokeai/frontend/web/src/features/gallery/hooks/useMultiselect.ts b/invokeai/frontend/web/src/features/gallery/hooks/useMultiselect.ts index 5f7c5e4da8..784359bf95 100644 --- a/invokeai/frontend/web/src/features/gallery/hooks/useMultiselect.ts +++ b/invokeai/frontend/web/src/features/gallery/hooks/useMultiselect.ts @@ -43,9 +43,14 @@ export const useMultiselect = (imageDTO?: ImageDTO) => { [dispatch, imageDTO, isMultiSelectEnabled] ); - return { - areMultiplesSelected, - isSelected, - handleClick, - }; + const api = useMemo( + () => ({ + areMultiplesSelected, + isSelected, + handleClick, + }), + [areMultiplesSelected, isSelected, handleClick] + ); + + return api; }; diff --git a/invokeai/frontend/web/src/features/gallery/store/gallerySelectors.ts b/invokeai/frontend/web/src/features/gallery/store/gallerySelectors.ts index 1c64fc7809..ae799621d7 100644 --- a/invokeai/frontend/web/src/features/gallery/store/gallerySelectors.ts +++ b/invokeai/frontend/web/src/features/gallery/store/gallerySelectors.ts @@ -18,3 +18,14 @@ export const selectListImagesQueryArgs = createMemoizedSelector( is_intermediate: false, }) ); + +export const selectListImages2QueryArgs = createMemoizedSelector( + selectGallerySlice, + (gallery): ListImagesArgs => ({ + board_id: gallery.selectedBoardId, + categories: gallery.galleryView === 'images' ? IMAGE_CATEGORIES : ASSETS_CATEGORIES, + offset: gallery.offset, + limit: gallery.limit, + is_intermediate: false, + }) +); diff --git a/invokeai/frontend/web/src/features/gallery/store/gallerySlice.ts b/invokeai/frontend/web/src/features/gallery/store/gallerySlice.ts index b1b673d10c..d0043313c3 100644 --- a/invokeai/frontend/web/src/features/gallery/store/gallerySlice.ts +++ b/invokeai/frontend/web/src/features/gallery/store/gallerySlice.ts @@ -19,7 +19,7 @@ const initialGalleryState: GalleryState = { selectedBoardId: 'none', galleryView: 'images', boardSearchText: '', - limit: INITIAL_IMAGE_LIMIT, + limit: 20, offset: 0, isImageViewerOpen: true, imageToCompare: null, @@ -114,6 +114,9 @@ export const gallerySlice = createSlice({ comparisonFitChanged: (state, action: PayloadAction<'contain' | 'fill'>) => { state.comparisonFit = action.payload; }, + offsetChanged: (state, action: PayloadAction) => { + state.offset = action.payload; + }, }, extraReducers: (builder) => { builder.addMatcher(isAnyBoardDeleted, (state, action) => { @@ -157,6 +160,7 @@ export const { comparedImagesSwapped, comparisonFitChanged, comparisonModeCycled, + offsetChanged, } = gallerySlice.actions; const isAnyBoardDeleted = isAnyOf( diff --git a/invokeai/frontend/web/src/services/api/endpoints/images.ts b/invokeai/frontend/web/src/services/api/endpoints/images.ts index c9052a607d..054d290cb9 100644 --- a/invokeai/frontend/web/src/services/api/endpoints/images.ts +++ b/invokeai/frontend/web/src/services/api/endpoints/images.ts @@ -14,6 +14,7 @@ import type { ImageCategory, ImageDTO, ListImagesArgs, + ListImagesResponse, OffsetPaginatedResults_ImageDTO_, PostUploadAction, } from 'services/api/types'; @@ -50,6 +51,14 @@ export const imagesApi = api.injectEndpoints({ /** * Image Queries */ + listImages2: build.query({ + query: (queryArgs) => ({ + // Use the helper to create the URL. + url: getListImagesUrl(queryArgs), + method: 'GET', + }), + providesTags: ['FetchOnReconnect'], + }), listImages: build.query, ListImagesArgs>({ query: (queryArgs) => ({ // Use the helper to create the URL. @@ -1304,6 +1313,7 @@ export const imagesApi = api.injectEndpoints({ export const { useGetIntermediatesCountQuery, useListImagesQuery, + useListImages2Query, useGetImageDTOQuery, useGetImageMetadataQuery, useGetImageWorkflowQuery, diff --git a/invokeai/frontend/web/src/services/api/types.ts b/invokeai/frontend/web/src/services/api/types.ts index 90ddf3cca1..50c63fd806 100644 --- a/invokeai/frontend/web/src/services/api/types.ts +++ b/invokeai/frontend/web/src/services/api/types.ts @@ -7,6 +7,7 @@ export type S = components['schemas']; export type ImageCache = EntityState; export type ListImagesArgs = NonNullable; +export type ListImagesResponse = paths['/api/v1/images/']['get']['responses']['200']['content']['application/json']; export type DeleteBoardResult = paths['/api/v1/boards/{board_id}']['delete']['responses']['200']['content']['application/json'];