Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 | 44x 44x 44x 44x 30x 30x 30x 30x 30x 30x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 1x 30x 1x 1x 1x 1x 1x 1x 1x 30x 1x 1x 30x 3x 2x 44x 44x 6x 10x 44x 44x 44x 18x 18x 18x 18x 9x 44x 18x 18x 18x 44x 31x 31x 31x 31x 31x 31x 31x 5x 14x 14x 31x 31x 24x 24x 31x 31x 9x 9x 31x 6x 25x 1x 24x 36x 18x 18x 18x 18x 1210x 1210x 1210x 1210x 1210x 1210x 1210x 1210x 1210x 1210x 1210x 1210x 1210x 9x 1x 1x 8x 1210x 2x 2x 2x 1210x 1x 1x 1x 1x 1x 1210x 1210x 2x 2x 1210x 2x 1210x 1x 1210x 1210x 1x 1x 1x 1x 1x 1x 1x 1x 1210x 1210x 1210x 1210x 1x 2x 1x 1x | import {
AcceptAllowedImagesTypes,
MAX_UPLOAD_SIZE,
useDropzoneUpload,
} from "@hooks/upload-api/uploadHooks";
import { Box, CircularProgress, Stack } from "@mui/material";
import { CheckIcon, PlusIcon, TrashIcon } from "@phosphor-icons/react";
import { useSignals } from "@preact/signals-react/runtime";
import {
MediaItem,
ResizeType,
} from "@sections/PayBuilder/provider/provider.type";
import HFGiveSelect from "@shared/HFInputs/HFGiveSelect/HFGiveSelect";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import GivePopup from "@shared/Popup/GivePopup";
import { useAppTheme } from "@theme/v2/Provider";
import { forwardRef, useCallback, useMemo, useRef, useState } from "react";
import { Cropper, ReactCropperElement } from "react-cropper";
import Buttons from "./components/Buttons";
import CropButtons from "./components/CropButtons";
import { HeroImage } from "@sections/PayBuilder/components/products/Hero/HeroImage";
import RotateLeft from "@assets/iconsV2/RotateLeft";
import { useInfiniteQuery, useMutation, useQueryClient } from "react-query";
import { customInstance } from "@services/api";
import { useGetCurrentMerchantId } from "@hooks/common";
import { VirtuosoGrid } from "react-virtuoso";
import GiveUploadArea from "@shared/FileUpload/GiveUploadArea";
import { useImageSource } from "@sections/PayBuilder/Forms/About/utils";
import { showMessage } from "@common/Toast";
import FooterLeft from "@sections/PayBuilder/Forms/About/components/FooterLeft";
import { QKEY_GET_IMG } from "@constants/queryKeys";
import { useCheckDocumentProcessing } from "@redux/slices/uploadProgressSlice";
import GiveText from "@shared/Text/GiveText";
import useFetchImage from "@hooks/useFetchImage";
import { useAppSelector } from "@redux/hooks";
import { selectSelectedAccount } from "@redux/slices/auth/accounts";
import VideoUploadTab from "./VideoUploadTab";
import NewImageModalTabs, { ImageModalTabs } from "./NewImageModalTabs";
import { FormProvider, useForm } from "react-hook-form";
import * as Yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { YOUTUBE_REGEX } from "@sections/PayBuilder/utils";
import { UploadDocumentTypes } from "@redux/slices/uploadProgressSlice/types";
export const MIN_ZOOM = 0;
export const MAX_ZOOM = 100;
interface StateType {
zoom: number;
rotation: number;
croppedAreaPixels: null;
file: null;
}
const initialState: StateType = {
zoom: 0,
rotation: 0,
croppedAreaPixels: null,
file: null,
};
interface ImageEditorProps {
mediaItem: MediaItem | null;
custom: {
zoom: number;
rotation: number;
};
setCustomize: React.Dispatch<React.SetStateAction<StateType>>;
cropperRef: React.RefObject<ReactCropperElement>;
resizeType: ResizeType;
setResizeType: React.Dispatch<React.SetStateAction<ResizeType>>;
initiateDelete: (item: MediaItem) => void;
isLogo: boolean;
}
const ImageEditor = ({
mediaItem,
custom: { zoom, rotation },
setCustomize,
cropperRef,
resizeType,
setResizeType,
initiateDelete,
isLogo,
}: ImageEditorProps) => {
const { isLoading, data: imageSource } = useImageSource(mediaItem, {
rotation: rotation,
});
const { palette } = useAppTheme();
const isMaxZoom = zoom >= MAX_ZOOM;
const isMinZoom = zoom <= MIN_ZOOM;
const isCrop = resizeType === "crop";
const handleZoom = (v?: boolean) => {
const step = 10;
let newZoom = zoom;
if (v) {
newZoom = Math.min(zoom + step, MAX_ZOOM);
} else {
newZoom = Math.max(zoom - step, MIN_ZOOM);
}
setCustomize((prev) => ({
...prev,
zoom: newZoom,
}));
Eif (cropperRef.current?.cropper) {
const relativeZoom = newZoom / 100;
cropperRef.current.cropper.reset();
if (relativeZoom > 0) {
cropperRef.current.cropper.zoom(relativeZoom);
}
}
};
const handleUpdateSlider = (v: Event, z: number | number[]) => {
const value = Array.isArray(z) ? z[0] : z;
setCustomize((prev) => ({
...prev,
zoom: value,
}));
Eif (cropperRef.current?.cropper) {
const relativeZoom = value / 100;
cropperRef.current.cropper.reset();
Eif (relativeZoom > 0) {
cropperRef.current.cropper.zoom(relativeZoom);
}
}
};
const onRotate = () => {
const newRotation = (rotation - 90 + 360) % 360;
setCustomize((prev) => ({
...prev,
rotation: newRotation,
zoom: 0,
}));
};
return (
<>
{(resizeType === "fit" ||
resizeType === "fill" ||
resizeType === "original") && (
<Box
sx={{
opacity: isLoading ? 0.6 : 1,
}}
>
<HeroImage
isLoading={isLoading}
src={imageSource}
canvasData={{
resizeType: resizeType === "original" ? "fit" : resizeType,
}}
/>
</Box>
)}
{resizeType === "crop" && (
<Cropper
zoomOnWheel={false}
src={imageSource}
style={{ height: 400, width: "100%" }}
aspectRatio={16 / 9}
guides={false}
viewMode={1}
ref={cropperRef}
/>
)}
<Stack my="24px" justifyContent="space-between" flexDirection="row">
<Stack gap="20px" alignItems="center" flexDirection="row">
<HFGiveSelect
sx={{
width: "160px",
flex: 1,
}}
options={[
{ label: "Crop", value: "crop" },
...(!isLogo ? [{ label: "Scale to Fit", value: "fit" }] : []),
...(!isLogo ? [{ label: "Scale to Fill", value: "fill" }] : []),
...(isLogo ? [{ label: "Original", value: "original" }] : []),
]}
name={resizeType}
value={resizeType as any}
defaultValue={resizeType}
onChange={(e) => {
setResizeType(e.target.value as ResizeType);
}}
/>
{isCrop && (
<CropButtons
handleUpdateSlider={handleUpdateSlider}
isMinZoom={isMinZoom}
isMaxZoom={isMaxZoom}
handleZoom={handleZoom}
zoomValue={zoom}
/>
)}
</Stack>
<Stack gap="12px" alignItems="center" flexDirection="row">
<GiveIconButton
data-testid="image-editor-rotate"
CustomIcon={<RotateLeft fill={palette.text.primary} />}
color={palette.icon?.["icon-primary"]}
size="small"
variant="ghost"
onClick={onRotate}
/>
<GiveIconButton
data-testid="image-editor-delete"
Icon={TrashIcon}
color={palette.primitive?.error[50]}
size="small"
variant="ghost"
onClick={() => {
initiateDelete(mediaItem as MediaItem);
}}
/>
</Stack>
</Stack>
</>
);
};
const MAX_PER_PAGE = 20;
interface ListProps {
style?: React.CSSProperties;
children?: React.ReactNode;
[key: string]: any;
}
interface ItemProps {
children?: React.ReactNode;
[key: string]: any;
}
const gridComponents = {
List: forwardRef<
HTMLDivElement,
ListProps & { context?: { showTabs: boolean; selectedItem: boolean } }
>(({ style, children, context, ...props }, ref) => (
<div
ref={ref}
{...props}
style={{
display: "flex",
flexWrap: "wrap",
overflowY: "hidden",
marginTop: !context?.selectedItem && context?.showTabs ? 24 : 82,
gap: "32px",
...style,
}}
>
{children}
</div>
)),
Scroller: forwardRef<HTMLDivElement, ListProps>(
({ style, children, ...props }, ref) => (
<div
ref={ref}
{...props}
style={{
marginBottom: 12,
...style,
}}
>
{children}
</div>
),
),
Item: ({ children, ...props }: ItemProps) => children,
};
gridComponents.List.displayName = "List";
gridComponents.Scroller.displayName = "Scroller";
interface ImageItemProps {
item: MediaItem;
onClick: (item: MediaItem) => void;
selectedID: number;
}
const ImageItem = ({ item, onClick, selectedID }: ImageItemProps) => {
const { palette } = useAppTheme();
const baseImageUrl = item?.URL ? item.URL + "/small" : "";
const { data: imageUrl, isLoading, isError } = useFetchImage(baseImageUrl);
return (
<Box
sx={{
display: "flex",
boxSizing: "border-box",
alignItems: "center",
justifyContent: "center",
height: 114,
width: 114,
borderRadius: 2,
overflow: "hidden",
}}
>
<Box
sx={{
display: "flex",
flex: "none",
transitionDuration: "100ms",
alignItems: "center",
justifyContent: "center",
backgroundColor: palette.surface?.secondary,
overflow: "hidden",
filter: selectedID === item.id ? "brightness(0.6)" : undefined,
"&:hover": {
cursor: "pointer",
filter: "brightness(0.6)",
},
position: "relative",
height: "100%",
width: "100%",
}}
onClick={() => onClick(item)}
>
{isLoading && (
<CircularProgress sx={{ color: palette.text.tertiary }} size={24} />
)}
{isError && !isLoading && (
<GiveText color="secondary" variant="bodyXS">
Unable to load
</GiveText>
)}
{imageUrl && !isError && (
<img
src={imageUrl}
alt="Media item"
style={{
height: 114,
borderRadius: 2,
width: 114,
objectFit: "cover",
}}
/>
)}
</Box>
{selectedID === item.id && (
<CheckIcon
size={32}
weight="bold"
color="white"
style={{ position: "absolute", pointerEvents: "none" }}
/>
)}
</Box>
);
};
const UploadItem = () => {
const { handleDirectUpload } = useDropzoneUpload();
const isConvertingDocument = useCheckDocumentProcessing(
UploadDocumentTypes.imageModal,
);
return (
<GiveUploadArea
disabled={isConvertingDocument}
documentType={UploadDocumentTypes.imageModal}
accept={AcceptAllowedImagesTypes}
maxSizeInBytes={MAX_UPLOAD_SIZE.value}
uploadFunction={(f: File | File[]) => {
handleDirectUpload(f as File);
}}
customElement={<PlusIcon size={24} />}
sx={{
height: 114,
width: 114,
}}
/>
);
};
interface ImageSelectorProps {
handleSelectItem: (item: MediaItem | null) => void;
selectedImage: MediaItem;
selectedItem: any;
showTabs: boolean | undefined;
}
const ImageSelector = ({
handleSelectItem,
selectedImage,
selectedItem,
showTabs,
}: ImageSelectorProps) => {
const { merchantId } = useGetCurrentMerchantId();
const isConvertingDocument = useCheckDocumentProcessing(
UploadDocumentTypes.imageModal,
);
//
const selectedUser = useAppSelector(selectSelectedAccount);
const { img } = useGetCurrentMerchantId();
const merchantImage = (img || selectedUser?.img)?.replace("/thumb", "");
const merchantMedia = merchantImage ? [{ URL: merchantImage, id: 0 }] : [];
//
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, status } =
useInfiniteQuery(
["get-all-media-items"],
async ({ pageParam = 1 }) => {
return customInstance({
url: `/accounts/${merchantId}/media-items?max=${MAX_PER_PAGE}&page=${pageParam}&sort=-createdAt`,
});
},
{
getNextPageParam: (lastPage, allPages) => {
Iif (lastPage?.data?.length === MAX_PER_PAGE) {
return allPages?.length + 1;
}
return undefined;
},
},
);
const allItems = useMemo(() => {
if (!data) return merchantMedia;
return [
...data.pages.flatMap((page) => page?.data || []),
...merchantMedia,
];
}, [data, merchantMedia]);
const loadMore = useCallback(() => {
if (hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
}, [fetchNextPage, hasNextPage, isFetchingNextPage]);
const onClick = (item: MediaItem) => {
Iif (isConvertingDocument) return;
handleSelectItem(item);
};
if (status === "loading") {
return (
<div style={{ paddingTop: "100px", paddingBottom: "24px" }}>
Loading media items...
</div>
);
}
if (status === "error") {
return <div>Error loading media items. Please try again later.</div>;
}
return (
<>
<VirtuosoGrid
style={{ height: 500 }}
totalCount={allItems.length + 1} // +1 for upload button
components={gridComponents}
context={{
showTabs: showTabs,
selectedItem: !!selectedItem,
}}
itemContent={(index) => {
if (index === 0) {
return <UploadItem />;
}
const itemIndex = index - 1;
const item = allItems[itemIndex];
return (
<ImageItem
item={item}
onClick={onClick}
selectedID={selectedImage.id}
/>
);
}}
endReached={loadMore}
overscan={200}
/>
</>
);
};
interface IImageModal {
open: boolean;
onClose: () => void;
handleSelect: (item?: MediaItem, shouldClose?: boolean) => void;
selectedImage: MediaItem;
isLogo?: boolean;
noEditing?: boolean;
defaultTitle?: string;
showTabs?: boolean;
handleSaveVideo?: (url: string) => void;
}
function ImageModalNew({
open,
onClose,
handleSelect,
selectedImage,
isLogo = false,
noEditing = false,
defaultTitle = "Media Library",
showTabs,
handleSaveVideo,
}: IImageModal) {
useSignals();
const schema = Yup.object().shape({
videoURL: Yup.string().matches(
YOUTUBE_REGEX,
"Please enter a valid Youtube URL",
),
});
const methods = useForm<any>({
mode: "onChange",
resolver: yupResolver(schema),
defaultValues: {
videoURL: "",
},
});
const {
formState: { isValid },
} = methods;
const [selectedItem, setSelectedItem] = useState<MediaItem | null>(null);
const isConvertingDocument = useCheckDocumentProcessing(
UploadDocumentTypes.imageModal,
);
const [resizeType, setResizeType] = useState<ResizeType>(
isLogo ? "original" : "fill",
);
const [mediaItemToDelete, setMediaItemToDelete] = useState<MediaItem | null>(
null,
);
const [custom, setCustomize] = useState<StateType>(initialState);
const [selectedTab, setSelectedTab] = useState(ImageModalTabs.IMAGE);
/* In addition to checking if youtube URL is valid regex, we should also check
if URL is valid (video exists and is not private / deleted).
*/
const [isExistingVideoURL, setIsExistingVideoURL] = useState(true);
const cropperRef = useRef<ReactCropperElement>(null);
const handleSelectItem = (item: MediaItem | null) => {
if (noEditing) {
item && handleSelect(item);
return;
}
setSelectedItem(item);
};
const reset = () => {
setSelectedItem(null);
setResizeType(isLogo ? "original" : "fill");
setCustomize(initialState);
};
const onCrop = () => {
Iif (!selectedItem) return;
const cropData = cropperRef?.current?.cropper.getData() || {};
const finalItem: MediaItem = {
...selectedItem,
...cropData,
rotate: custom.rotation,
scaleX: custom.zoom,
scaleY: custom.zoom,
resizeType,
};
handleSelect(finalItem);
onClose?.();
};
const { merchantId } = useGetCurrentMerchantId();
const handleCloseDelete = () => {
Iif (isConvertingDocument) return;
setMediaItemToDelete(null);
};
const initiateDelete = (item: MediaItem) => {
setMediaItemToDelete(item);
};
const { mutateAsync, isLoading: isDeleteLoading } = useMutation(
(data: { id?: number }) => {
return customInstance({
url: `/accounts/${merchantId}/media-items/${data.id}`,
method: "DELETE",
});
},
);
const QueryClient = useQueryClient();
const handleDelete = async (item: MediaItem) => {
await mutateAsync(item);
showMessage("Success", "Image has been successfully deleted");
QueryClient.invalidateQueries(["get-all-media-items"]);
QueryClient.invalidateQueries([QKEY_GET_IMG]);
Eif (item.id === selectedItem?.id)
handleSelect(
{ URL: "", accountID: 0, createdAt: 0, id: 0, label: "", updatedAt: 0 },
false,
);
handleCloseDelete();
reset();
};
const content = (
<>
{selectedItem && (
<ImageEditor
mediaItem={selectedItem}
custom={custom}
setCustomize={setCustomize}
cropperRef={cropperRef}
resizeType={resizeType}
setResizeType={setResizeType}
initiateDelete={initiateDelete}
isLogo={isLogo}
/>
)}
{!selectedItem && (
<ImageSelector
selectedItem={selectedItem}
showTabs={showTabs}
handleSelectItem={handleSelectItem}
selectedImage={selectedImage}
/>
)}
</>
);
const isImageTabView = selectedTab === ImageModalTabs.IMAGE;
const isVideoTabView = selectedTab === ImageModalTabs.VIDEO;
return (
<>
<GiveBaseModal
title={selectedItem ? "Edit Image" : defaultTitle}
open={open}
onClose={isConvertingDocument ? () => null : onClose}
TransitionProps={{
onExited: reset,
}}
showFooter={Boolean(selectedItem || isVideoTabView)}
footerLeftContent={
isImageTabView && <FooterLeft handleResetSelected={() => reset()} />
}
hideScrollBar
buttons={
<Buttons
getCropData={onCrop}
handleCancel={() => {
if (!isConvertingDocument) onClose?.();
}}
isVideoTab={isVideoTabView}
isSubmitVideoButtonDisabled={!isValid || !isExistingVideoURL}
onSaveVideoClick={() => {
handleSaveVideo?.(methods.watch("videoURL"));
}}
/>
}
customContentPadding={
selectedItem
? "84px 20px 94px 20px"
: showTabs
? "84px 20px 0px 20px"
: "0px 20px 0px 20px"
}
>
<FormProvider {...methods}>
{showTabs && !selectedItem && (
<NewImageModalTabs
selectedTab={selectedTab}
setSelectedTab={setSelectedTab}
/>
)}
{isImageTabView ? (
content
) : (
<VideoUploadTab setIsExistingVideoURL={setIsExistingVideoURL} />
)}
</FormProvider>
<GivePopup
open={Boolean(mediaItemToDelete)}
description={
"Are you sure you want to delete this image? It will also be removed from the image library."
}
onClose={handleCloseDelete}
title="Remove Image"
type="destructive"
buttons={[
{
label: "Cancel",
onClick: handleCloseDelete,
variant: "ghost",
disabled: isDeleteLoading || isConvertingDocument,
},
{
label: "Yes, Remove",
onClick: () =>
mediaItemToDelete && handleDelete(mediaItemToDelete),
variant: "filled",
color: "destructive",
disabled: isDeleteLoading || isConvertingDocument,
},
]}
/>
</GiveBaseModal>
</>
);
}
export default ImageModalNew;
|