Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(web): refactor assets hooks #719

Merged
merged 12 commits into from
Oct 12, 2023
79 changes: 12 additions & 67 deletions web/src/beta/components/fields/URLField/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ import React, { useCallback, useEffect, useState } from "react";
import Button from "@reearth/beta/components/Button";
import Property from "@reearth/beta/components/fields";
import TextInput from "@reearth/beta/components/fields/common/TextInput";
import useHooks from "@reearth/beta/features/Assets/AssetsQueriesHook/hooks";
import { FILE_FORMATS, IMAGE_FORMATS } from "@reearth/beta/features/Assets/constants";
import { Asset } from "@reearth/beta/features/Assets/types";
import { useManageAssets } from "@reearth/beta/features/Assets/useManageAssets/hooks";
import ChooseAssetModal from "@reearth/beta/features/Modals/ChooseAssetModal";
import AssetModal from "@reearth/beta/features/Modals/AssetModal";
import useFileUploaderHook from "@reearth/beta/hooks/useAssetUploader/hooks";
import { checkIfFileType } from "@reearth/beta/utils/util";
import { useT } from "@reearth/services/i18n";
import { useNotification, useWorkspace } from "@reearth/services/state";
Expand Down Expand Up @@ -50,62 +48,19 @@ const URLField: React.FC<Props> = ({ name, description, value, fileType, assetTy
},
[fileType, onChange, setNotification, t],
);

const {
assets,
isLoading,
hasMoreAssets,
searchTerm,
selectedAssets,
selectAsset,
handleGetMoreAssets,
handleFileSelect,
handleSortChange,
handleSearchTerm,
} = useHooks({ workspaceId: currentWorkspace?.id, onAssetSelect: handleChange });

const { localSearchTerm, wrapperRef, onScrollToBottom, handleSearchInputChange, handleSearch } =
useManageAssets({
selectedAssets,
searchTerm,
isLoading,
hasMoreAssets,
onGetMore: handleGetMoreAssets,
onSortChange: handleSortChange,
onSearch: handleSearchTerm,
});

const handleReset = useCallback(() => {
const selectedAsset = assets?.find(a => a.url === currentValue);
if (selectedAsset) {
selectAsset([selectedAsset]);
}
}, [currentValue, assets, selectAsset]);
const { handleFileUpload } = useFileUploaderHook({
workspaceId: currentWorkspace?.id,
onAssetSelect: handleChange,
});

useEffect(() => {
if (value) {
setCurrentValue(value);
}
}, [value]);

useEffect(() => {
handleReset();
}, [handleReset]);

const handleClose = useCallback(() => {
setOpen(false);
handleReset();
}, [handleReset]);

const handleClick = useCallback(() => setOpen(!open), [open]);

const handleSelect = useCallback(
(asset?: Asset) => {
if (!asset) return;
selectAsset(!selectedAssets.includes(asset) ? [asset] : []);
},
[selectedAssets, selectAsset],
);
const handleModalClose = useCallback(() => setOpen(false), []);

return (
<Property name={name} description={description}>
Expand All @@ -122,27 +77,17 @@ const URLField: React.FC<Props> = ({ name, description, value, fileType, assetTy
icon="uploadSimple"
text={t("Upload")}
iconPosition="left"
onClick={handleFileSelect}
onClick={handleFileUpload}
/>
</ButtonWrapper>
)}
{open && (
<ChooseAssetModal
<AssetModal
open={open}
onModalClose={handleModalClose}
assetType={assetType}
localSearchTerm={localSearchTerm}
selectedAssets={selectedAssets}
wrapperRef={wrapperRef}
assets={assets}
isLoading={isLoading}
hasMoreAssets={hasMoreAssets}
searchTerm={searchTerm}
onClose={handleClose}
handleSearch={handleSearch}
handleSearchInputChange={handleSearchInputChange}
onGetMore={handleGetMoreAssets}
onScrollToBottom={onScrollToBottom}
onSelectAsset={handleSelect}
currentWorkspace={currentWorkspace}
currentValue={currentValue}
onSelect={handleChange}
/>
)}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { useCallback, useState, useRef } from "react";
import useFileInput from "use-file-input";
import { useCallback, useState, useRef, useMemo, useEffect } from "react";

import { Asset, SortType } from "@reearth/beta/features/Assets/types";
import { autoFillPage, onScrollToBottom } from "@reearth/beta/utils/infinite-scroll";
import { useAssetsFetcher } from "@reearth/services/api";
import { Maybe, AssetSortType as GQLSortType } from "@reearth/services/gql";

import { FILE_FORMATS, IMAGE_FORMATS } from "../constants";
import { useT } from "@reearth/services/i18n";

const assetsPerPage = 20;

Expand Down Expand Up @@ -36,7 +35,6 @@ function pagination(

export default ({
workspaceId,
onAssetSelect,
}: {
workspaceId?: string;
onAssetSelect?: (inputValue?: string) => void;
Expand All @@ -46,7 +44,7 @@ export default ({
const [selectedAssets, selectAsset] = useState<Asset[]>([]);
const isGettingMore = useRef(false);

const { useAssetsQuery, useCreateAssets, useRemoveAssets } = useAssetsFetcher();
const { useAssetsQuery, useRemoveAssets } = useAssetsFetcher();

const { assets, hasMoreAssets, loading, isRefetching, endCursor, fetchMore } = useAssetsQuery({
teamId: workspaceId ?? "",
Expand All @@ -55,6 +53,24 @@ export default ({
keyword: searchTerm,
});

const t = useT();
const [deleteModalVisible, setDeleteModalVisible] = useState(false);
const [localSearchTerm, setLocalSearchTerm] = useState<string>(searchTerm ?? "");
const openDeleteModal = useCallback(() => setDeleteModalVisible(true), []);
const closeDeleteModal = useCallback(() => setDeleteModalVisible(false), []);
const wrapperRef = useRef<HTMLDivElement>(null);
const sortOptions: { key: string; label: string }[] = useMemo(
() => [
{ key: "date", label: t("Last Uploaded") },
{ key: "date-reverse", label: t("First Uploaded") },
{ key: "name", label: t("A To Z") },
{ key: "name-reverse", label: t("Z To A") },
{ key: "size", label: t("Size Small to Large") },
{ key: "size-reverse", label: t("Size Large to Small") },
],
[t],
);

const handleGetMoreAssets = useCallback(async () => {
if (hasMoreAssets && !isGettingMore.current) {
isGettingMore.current = true;
Expand All @@ -67,27 +83,6 @@ export default ({
}
}, [endCursor, sort, fetchMore, hasMoreAssets, isGettingMore]);

const handleAssetsCreate = useCallback(
async (files?: FileList) => {
if (!files) return;
const result = await useCreateAssets({ teamId: workspaceId ?? "", file: files });
const assetUrl = result?.data[0].data?.createAsset?.asset.url;

onAssetSelect?.(assetUrl);
},
[workspaceId, useCreateAssets, onAssetSelect],
);

const removeAssets = useCallback(
async (assetIds: string[]) => {
const { status } = await useRemoveAssets(assetIds);
if (status === "success") {
selectAsset([]);
}
},
[useRemoveAssets],
);

const handleSortChange = useCallback(
(type?: string, reverse?: boolean) => {
if (!type && reverse === undefined) return;
Expand All @@ -103,23 +98,63 @@ export default ({
setSearchTerm(term);
}, []);

const handleFileSelect = useFileInput(files => handleAssetsCreate?.(files), {
accept: IMAGE_FORMATS + "," + FILE_FORMATS,
multiple: true,
});
const handleRemove = useCallback(async () => {
if (selectedAssets?.length) {
const { status } = await useRemoveAssets(selectedAssets.map(a => a.id));
if (status === "success") {
selectAsset([]);
}
setDeleteModalVisible(false);
}
}, [selectedAssets, useRemoveAssets]);

const handleReverse = useCallback(() => {
handleSortChange?.(undefined, !sort?.reverse);
}, [handleSortChange, sort?.reverse]);

const handleSearchInputChange = useCallback(
(value: string) => {
setLocalSearchTerm(value);
},
[setLocalSearchTerm],
);
const handleSearch = useCallback(() => {
if (!localSearchTerm || localSearchTerm.length < 1) {
handleSearchTerm?.(undefined);
} else {
handleSearchTerm?.(localSearchTerm);
}
}, [localSearchTerm, handleSearchTerm]);

const isLoading = useMemo(() => {
return loading ?? isRefetching;
}, [isRefetching, loading]);

useEffect(() => {
if (wrapperRef.current && !isLoading && hasMoreAssets)
autoFillPage(wrapperRef, handleGetMoreAssets);
}, [handleGetMoreAssets, hasMoreAssets, isLoading]);

return {
wrapperRef,
assets,
isLoading: loading ?? isRefetching,
hasMoreAssets,
sortOptions,
sort,
searchTerm,
localSearchTerm,
isLoading,
hasMoreAssets,
selectedAssets,
deleteModalVisible,
closeDeleteModal,
selectAsset,
handleGetMoreAssets,
handleFileSelect,
removeAssets,
handleSortChange,
handleSearchTerm,
onScrollToBottom,
openDeleteModal,
handleRemove,
handleReverse,
handleSearchInputChange,
handleSearch,
};
};
108 changes: 0 additions & 108 deletions web/src/beta/features/Assets/useManageAssets/hooks.ts

This file was deleted.

Loading
Loading