Compare commits

...

3 Commits

Author SHA1 Message Date
hamid zarghami 22d15f9a13 progressbar uploading
deploy to danak / build_and_deploy (push) Has been cancelled
2026-07-01 16:27:21 +03:30
hamid zarghami bbb797cc62 border z-index than paper 2026-07-01 16:21:43 +03:30
hamid zarghami 4af7181384 fix animation 2026-07-01 16:17:03 +03:30
11 changed files with 163 additions and 41 deletions
+12
View File
@@ -2,6 +2,7 @@ import { CloseCircle, DocumentUpload, Gallery } from 'iconsax-react'
import { type FC, useCallback, useEffect, useState } from 'react'
import { useDropzone } from 'react-dropzone';
import { clx } from '../helpers/utils';
import UploadProgressBar from './UploadProgressBar';
type Props = {
label: string;
@@ -15,6 +16,8 @@ type Props = {
/** نمایش وضعیت بارگذاری داخل باکس آپلود */
isLoading?: boolean,
loadingLabel?: string,
/** درصد پیشرفت آپلود (۰ تا ۱۰۰) */
uploadProgress?: number,
/** بدون پیش‌نمایش زیر باکس (مثلاً گالری جداگانه دارد) */
hidePreview?: boolean,
}
@@ -77,8 +80,16 @@ const UploadBoxDraggble: FC<Props> = (props: Props) => {
}, [props.coverUrl])
const showProgressOnly = props.isLoading && props.uploadProgress !== undefined;
return (
<div>
{showProgressOnly ? (
<UploadProgressBar
progress={props.uploadProgress!}
label={props.loadingLabel ?? `در حال آپلود... ${props.uploadProgress}٪`}
/>
) : (
<div
{...getRootProps()}
className={clx(
@@ -114,6 +125,7 @@ const UploadBoxDraggble: FC<Props> = (props: Props) => {
</>
)}
</div>
)}
{
!props.hidePreview && (files.length > 0 || perviews.length > 0) ? (
+26
View File
@@ -0,0 +1,26 @@
import { type FC } from "react";
type UploadProgressBarProps = {
progress: number;
label?: string;
};
const UploadProgressBar: FC<UploadProgressBarProps> = ({ progress, label }) => {
const clampedProgress = Math.min(100, Math.max(0, progress));
return (
<div className="flex w-full flex-col items-center gap-2 py-2">
<div className="h-1.5 w-full overflow-hidden rounded-full bg-gray-200">
<div
className="h-full rounded-full bg-black transition-all duration-200"
style={{ width: `${clampedProgress}%` }}
/>
</div>
<div className="text-description text-xs">
{label ?? `${clampedProgress}٪`}
</div>
</div>
);
};
export default UploadProgressBar;
+12
View File
@@ -1,12 +1,14 @@
import { type FC } from "react";
import { DocumentUpload, VideoSquare } from "iconsax-react";
import { clx } from "@/helpers/utils";
import UploadProgressBar from "@/components/UploadProgressBar";
type VideoUploadZoneProps = {
getRootProps: () => React.HTMLAttributes<HTMLDivElement>;
getInputProps: () => React.InputHTMLAttributes<HTMLInputElement>;
isLoading?: boolean;
loadingLabel?: string;
uploadProgress?: number;
};
const VideoUploadZone: FC<VideoUploadZoneProps> = ({
@@ -14,7 +16,17 @@ const VideoUploadZone: FC<VideoUploadZoneProps> = ({
getInputProps,
isLoading = false,
loadingLabel = "در حال آپلود...",
uploadProgress,
}) => {
if (isLoading && uploadProgress !== undefined) {
return (
<UploadProgressBar
progress={uploadProgress}
label={`${loadingLabel} ${uploadProgress}٪`}
/>
);
}
return (
<div
{...getRootProps()}
@@ -72,7 +72,7 @@ const SettingsPanel = () => {
if (!file) return
try {
const result = await uploadFile(file)
const result = await uploadFile({ file })
const imageUrl = result?.data?.url
if (!imageUrl) return
@@ -28,7 +28,7 @@ const AudioInput: FC = () => {
try {
for (const file of acceptedFiles) {
try {
const result = await uploadFile(file);
const result = await uploadFile({ file });
const audioUrl = result?.data?.url;
if (!audioUrl) continue;
const audioId = `audio-${Date.now()}-${Math.random()}`;
@@ -10,14 +10,23 @@ const ImageGallery: FC = () => {
const { gallery, addGalleryItem, removeGalleryItem } = useEditorStore();
const { mutateAsync: uploadFile } = useSingleUpload();
const [isUploading, setIsUploading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const handleFileChange = async (files: File[]) => {
if (files.length === 0) return;
setIsUploading(true);
setUploadProgress(0);
try {
for (const file of files) {
const result = await uploadFile(file);
for (let i = 0; i < files.length; i++) {
const file = files[i];
const result = await uploadFile({
file,
onProgress: (fileProgress) => {
const overall = Math.round(((i + fileProgress / 100) / files.length) * 100);
setUploadProgress(overall);
},
});
const imageUrl = result?.data?.url;
if (!imageUrl) continue;
@@ -33,6 +42,7 @@ const ImageGallery: FC = () => {
// TODO: show error toast
} finally {
setIsUploading(false);
setUploadProgress(0);
}
};
@@ -54,6 +64,7 @@ const ImageGallery: FC = () => {
isMultiple={true}
hidePreview
isLoading={isUploading}
uploadProgress={isUploading ? uploadProgress : undefined}
/>
{gallery.length === 0 && !isUploading && (
@@ -10,16 +10,27 @@ const VideoInput: FC = () => {
useEditorStore();
const { mutateAsync: uploadFile } = useSingleUpload();
const [isUploading, setIsUploading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const onDrop = useCallback(
async (acceptedFiles: File[]) => {
if (acceptedFiles.length === 0) return;
setIsUploading(true);
setUploadProgress(0);
try {
for (const file of acceptedFiles) {
for (let i = 0; i < acceptedFiles.length; i++) {
const file = acceptedFiles[i];
try {
const result = await uploadFile(file);
const result = await uploadFile({
file,
onProgress: (fileProgress) => {
const overall = Math.round(
((i + fileProgress / 100) / acceptedFiles.length) * 100
);
setUploadProgress(overall);
},
});
const videoUrl = result?.data?.url;
if (!videoUrl) continue;
const videoId = `video-${Date.now()}-${Math.random()}`;
@@ -41,6 +52,7 @@ const VideoInput: FC = () => {
}
} finally {
setIsUploading(false);
setUploadProgress(0);
}
},
[addObject, setSelectedObjectId, setTool, uploadFile]
@@ -71,6 +83,7 @@ const VideoInput: FC = () => {
getRootProps={getRootProps}
getInputProps={getInputProps}
isLoading={isUploading}
uploadProgress={isUploading ? uploadProgress : undefined}
/>
{videoObjects.length > 0 && (
+7 -1
View File
@@ -1,9 +1,15 @@
import { useMutation } from "@tanstack/react-query";
import * as api from "../service/UploaderService";
export type SingleUploadParams = {
file: File;
onProgress?: (progress: number) => void;
};
export const useSingleUpload = () => {
return useMutation({
mutationFn: api.singleUpload,
mutationFn: ({ file, onProgress }: SingleUploadParams) =>
api.singleUpload(file, onProgress),
});
};
+10 -2
View File
@@ -5,13 +5,21 @@ import type {
} from "../types/Types";
export const singleUpload = async (
file: File
file: File,
onProgress?: (progress: number) => void
): Promise<SingleUploadResponse> => {
const formData = new FormData();
formData.append("file", file);
const { data } = await axios.post<SingleUploadResponse>(
`/admin/single-file`,
formData
formData,
{
onUploadProgress: (event) => {
if (event.total) {
onProgress?.(Math.round((event.loaded / event.total) * 100));
}
},
}
);
return data;
};
+52 -17
View File
@@ -6,6 +6,7 @@ import { useIsBrowserFullscreen } from "@/pages/viewer/hooks/useIsBrowserFullscr
import { useViewerViewport } from "@/pages/viewer/hooks/useViewerViewport";
import { isLegacyIOSSafari } from "@/pages/viewer/utils/isLegacyIOSSafari";
import { resolvePageBackground } from "@/pages/viewer/utils/pageBackground";
import { getVisiblePageIndices } from "@/pages/viewer/utils/visiblePageIndices";
import { toggleViewerFullscreen } from "@/pages/viewer/utils/viewerFullscreen";
import { ArrowLeft2, ArrowRight2, Maximize4, Pause, Play, RowVertical } from "iconsax-react";
import { type FC, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
@@ -130,6 +131,8 @@ const BookViewer: FC<BookViewerProps> = ({ pages, catalogSize, documentSettings
const [isAutoPlayActive, setIsAutoPlayActive] = useState(false);
const [startPage, setStartPage] = useState(0);
const [magnifierEnabled, setMagnifierEnabled] = useState(false);
/** در حالت read خط وسط روی شکاف جلد دیده می‌شود؛ هنگام ورق‌زدن باید زیر ورق باشد */
const [isBookFlipping, setIsBookFlipping] = useState(false);
const isDesktop = useIsDesktop();
const legacyIOS = useLegacyIOSSafari();
const isBrowserFullscreen = useIsBrowserFullscreen();
@@ -222,22 +225,44 @@ const BookViewer: FC<BookViewerProps> = ({ pages, catalogSize, documentSettings
const flipKey = `${usePortrait ? "portrait" : "spread"}-${pagePixelWidth}-${pagePixelHeight}-${flipIndexCount}`;
const {
scheduleEntranceForSpread,
scheduleEntranceForIndices,
getEntrancePhase,
reset: resetEntrance,
} = useBookEntranceController({
pages,
portrait: usePortrait,
showCover: hasMultiplePages,
});
} = useBookEntranceController({ pages });
/**
* ایندکس‌های منطقیِ صفحات قابل‌مشاهده در اسپرد جاری را برمی‌گرداند.
* جفت‌سازی (کدام دو صفحه با هم دیده می‌شوند) باید در فضای نمایشیِ کتاب
* (flip index) انجام شود، نه فضای منطقی: در کتاب RTL این دو فضا برعکس
* هم‌اند، پس مثلاً «ایندکس منطقی + ۱» لزوماً هم‌صفحه‌ی واقعی نیست.
*/
const getVisibleLogicalIndices = useCallback(
(flipIdx: number): number[] => {
const displayIndices = getVisiblePageIndices(flipIdx, flipIndexCount, {
portrait: usePortrait,
showCover: hasMultiplePages,
});
const seen = new Set<number>();
const result: number[] = [];
for (const di of displayIndices) {
const logical = toLogicalIndex(di);
if (logical >= 0 && logical < pages.length && !seen.has(logical)) {
seen.add(logical);
result.push(logical);
}
}
return result;
},
[flipIndexCount, usePortrait, hasMultiplePages, toLogicalIndex, pages.length],
);
const commitEntranceAtCurrentSpread = useCallback(() => {
const api = bookRef.current?.pageFlip();
const idx = api?.getCurrentPageIndex?.();
if (typeof idx !== "number" || flipIndexCount <= 0) return;
const flipIdx = Math.max(0, Math.min(idx, flipIndexCount - 1));
scheduleEntranceForSpread(toLogicalIndex(flipIdx));
}, [flipIndexCount, scheduleEntranceForSpread, toLogicalIndex]);
scheduleEntranceForIndices(getVisibleLogicalIndices(flipIdx));
}, [flipIndexCount, scheduleEntranceForIndices, getVisibleLogicalIndices]);
useEffect(() => {
resetEntrance();
@@ -359,17 +384,21 @@ const BookViewer: FC<BookViewerProps> = ({ pages, catalogSize, documentSettings
setCurrentPage(logicalIdx);
lastFlipPageRef.current = logicalIdx;
// اولین اسپرد قبل از onChangeState('read') هم باید انیمیشن ورود بگیرد
scheduleEntranceForSpread(logicalIdx);
scheduleEntranceForIndices(getVisibleLogicalIndices(flipIdx));
},
[flipIndexCount, scheduleEntranceForSpread, toLogicalIndex],
[flipIndexCount, scheduleEntranceForIndices, getVisibleLogicalIndices, toLogicalIndex],
);
/** بعد از اتمام انیمیشن ورق، ایندکس واقعی کتاب را می‌گیریم و انیمیشن ورود را یک‌بار شروع می‌کنیم */
const handleChangeState = useCallback(
(e: PageFlipStateEvent) => {
if (e.data !== "read") return;
syncPageIndexFromBook();
commitEntranceAtCurrentSpread();
if (e.data === "read") {
setIsBookFlipping(false);
syncPageIndexFromBook();
commitEntranceAtCurrentSpread();
return;
}
setIsBookFlipping(true);
},
[syncPageIndexFromBook, commitEntranceAtCurrentSpread],
);
@@ -429,9 +458,9 @@ const BookViewer: FC<BookViewerProps> = ({ pages, catalogSize, documentSettings
const flipIdx = toFlipIndex(logicalIdx);
pageFlipAPI.turnToPage(flipIdx);
lastFlipPageRef.current = logicalIdx;
scheduleEntranceForSpread(logicalIdx);
scheduleEntranceForIndices(getVisibleLogicalIndices(flipIdx));
},
[pages.length, scheduleEntranceForSpread, toFlipIndex],
[pages.length, scheduleEntranceForIndices, getVisibleLogicalIndices, toFlipIndex],
);
const handleLinkClick = useCallback(
@@ -504,7 +533,10 @@ const BookViewer: FC<BookViewerProps> = ({ pages, catalogSize, documentSettings
{/* Border و Shadow عمودی در وسط (فقط حالت دوصفحه‌ای دسکتاپ) */}
{!usePortrait && (
<div
className="hidden md:block absolute inset-y-0 left-1/2 -translate-x-1/2 w-px border-r border-gray-300 pointer-events-none z-50"
className={clx(
"hidden md:block absolute inset-y-0 left-1/2 -translate-x-1/2 w-px border-r border-gray-300 pointer-events-none transition-none",
isBookFlipping ? "z-0" : "z-50",
)}
style={{
boxShadow: "-5px 0 15px rgba(0, 0, 0, 0.15), 5px 0 15px rgba(0, 0, 0, 0.15)",
}}
@@ -517,7 +549,10 @@ const BookViewer: FC<BookViewerProps> = ({ pages, catalogSize, documentSettings
<div
ref={flipbookWrapperRef}
dir="ltr"
className="max-w-full flex justify-center shrink-0 rounded-sm"
className={clx(
"max-w-full flex justify-center shrink-0 rounded-sm",
isBookFlipping && "relative z-10",
)}
style={{
cursor: magnifierEnabled ? "zoom-in" : undefined,
overflow: "hidden",
@@ -3,7 +3,6 @@ import {
ENTRANCE_ANIMATION_BASE_DELAY_MS,
MAX_ENTRANCE_DELAY_MS,
} from "@/shared/entranceAnimation";
import { getVisiblePageIndices } from "@/pages/viewer/utils/visiblePageIndices";
/** حداکثر زمان پخش انیمیشن ورود (برای برداشتن حالت play) */
const MAX_ENTRANCE_PLAY_MS =
@@ -18,15 +17,18 @@ type PageRef = { id: number };
type Options = {
pages: PageRef[];
portrait: boolean;
showCover: boolean;
};
/**
* کنترل یک‌بار پخش انیمیشن ورود هر صفحه — state در والد نگه‌داری می‌شود
* تا با remount شدن BookPage هنگام ورق‌خوردن دوباره اجرا نشود.
*
* محاسبهٔ اینکه «کدام صفحات منطقی در اسپرد جاری قابل‌مشاهده‌اند» بر عهدهٔ صدا‌زننده
* (BookViewer) است: در کتاب RTL، ایندکس نمایشی (flip index) و ایندکس منطقی صفحه
* برعکس هم می‌شوند، پس جفت‌سازی باید در فضای نمایشی انجام و سپس به منطقی تبدیل شود.
* اینجا فقط لیست ایندکس‌های منطقیِ از قبل‌محاسبه‌شده را می‌گیرد.
*/
export function useBookEntranceController({ pages, portrait, showCover }: Options) {
export function useBookEntranceController({ pages }: Options) {
const playedPageIdsRef = useRef(new Set<number>());
const [playingPageIds, setPlayingPageIds] = useState<ReadonlySet<number>>(() => new Set());
const playTimersRef = useRef<Map<number, ReturnType<typeof setTimeout>>>(new Map());
@@ -49,20 +51,17 @@ export function useBookEntranceController({ pages, portrait, showCover }: Option
});
}, [clearPlayTimer]);
const scheduleEntranceForSpread = useCallback(
(currentIndex: number) => {
const indices = getVisiblePageIndices(currentIndex, pages.length, {
portrait,
showCover,
});
const scheduleEntranceForIndices = useCallback(
(visibleLogicalIndices: number[]) => {
const visibleIds = new Set(
indices.map((i) => pages[i]?.id).filter((id): id is number => id != null),
visibleLogicalIndices
.map((i) => pages[i]?.id)
.filter((id): id is number => id != null),
);
const newlyPlaying: number[] = [];
for (const i of indices) {
for (const i of visibleLogicalIndices) {
const page = pages[i];
if (!page) continue;
if (playedPageIdsRef.current.has(page.id)) continue;
@@ -96,7 +95,7 @@ export function useBookEntranceController({ pages, portrait, showCover }: Option
);
}
},
[pages, portrait, showCover, clearPlayTimer, finishPlaying],
[pages, clearPlayTimer, finishPlaying],
);
const getEntrancePhase = useCallback(
@@ -117,7 +116,7 @@ export function useBookEntranceController({ pages, portrait, showCover }: Option
}, [clearPlayTimer]);
return {
scheduleEntranceForSpread,
scheduleEntranceForIndices,
getEntrancePhase,
reset,
};