gallery:
deploy to danak / build_and_deploy (push) Has been cancelled

This commit is contained in:
hamid zarghami
2026-05-25 09:35:57 +03:30
parent cbdc7edbf5
commit 83b2fd809c
19 changed files with 413 additions and 163 deletions
+47 -18
View File
@@ -11,7 +11,12 @@ type Props = {
preview?: string[],
onChangePreview?: (preview: string[]) => void,
getCover?: (url: string) => void,
coverUrl?: string
coverUrl?: string,
/** نمایش وضعیت بارگذاری داخل باکس آپلود */
isLoading?: boolean,
loadingLabel?: string,
/** بدون پیش‌نمایش زیر باکس (مثلاً گالری جداگانه دارد) */
hidePreview?: boolean,
}
const UploadBoxDraggble: FC<Props> = (props: Props) => {
@@ -21,6 +26,10 @@ const UploadBoxDraggble: FC<Props> = (props: Props) => {
const [cover, setCover] = useState<string>(props.coverUrl ?? "");
const onDrop = useCallback((acceptedFiles: File[]) => {
if (props.hidePreview) {
props.onChange(acceptedFiles);
return;
}
// وقتی parent با preview و onChangePreview مدیریت می‌کند، فقط onChange بزن تا فقط یک ردیف (perviews) نمایش داده شود
if (props.preview !== undefined && props.onChangePreview) {
props.onChange(acceptedFiles);
@@ -36,7 +45,10 @@ const UploadBoxDraggble: FC<Props> = (props: Props) => {
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [files]);
const { getRootProps, getInputProps } = useDropzone({ onDrop })
const { getRootProps, getInputProps } = useDropzone({
onDrop,
disabled: props.isLoading,
})
const handleDelete = (index: number) => {
const array = [...files]
@@ -67,27 +79,44 @@ const UploadBoxDraggble: FC<Props> = (props: Props) => {
return (
<div>
<div {...getRootProps()} className='w-full py-8 border border-dashed border-description flex flex-col justify-center items-center gap-4 rounded-2xl'>
<div
{...getRootProps()}
className={clx(
'relative w-full py-8 border border-dashed border-description flex flex-col justify-center items-center gap-4 rounded-2xl',
props.isLoading && 'pointer-events-none opacity-80',
)}
>
<input {...getInputProps()} />
<Gallery
className='size-8'
color='#8C90A3'
/>
<div className='text-description text-xs'>
{props.label}
</div>
{props.isLoading ? (
<>
<span className="h-8 w-8 animate-spin rounded-full border-2 border-gray-300 border-t-black" />
<div className="text-description text-xs">
{props.loadingLabel ?? 'در حال آپلود...'}
</div>
</>
) : (
<>
<Gallery
className='size-8'
color='#8C90A3'
/>
<div className='text-description text-xs'>
{props.label}
</div>
<div className='flex items-center gap-2'>
<DocumentUpload
className='size-4'
color='black'
/>
<div className='text-xs'>آپلود</div>
</div>
<div className='flex items-center gap-2'>
<DocumentUpload
className='size-4'
color='black'
/>
<div className='text-xs'>آپلود</div>
</div>
</>
)}
</div>
{
files.length > 0 || perviews.length > 0 ? (
!props.hidePreview && (files.length > 0 || perviews.length > 0) ? (
<div className='mt-4 flex gap-4 items-center'>
{
perviews && perviews.map((item, index) => {
+4 -4
View File
@@ -25,7 +25,7 @@ const Editor: FC = () => {
const [isInitialContentReady, setIsInitialContentReady] = useState(false)
const loadedCatalogIdRef = useRef<string | null>(null)
const skipNextAutosaveRef = useRef(true)
const { loadPages, resetEditor, pages, documentSettings, objects, currentPageId } = useEditorStore()
const { loadPages, resetEditor, pages, documentSettings, gallery, objects, currentPageId } = useEditorStore()
const { data, isFetched } = useGetCatalogById(id!)
const { scheduleUpdate, cancelPendingUpdate, isSaving } = useUpdateCatalog()
@@ -50,7 +50,7 @@ const Editor: FC = () => {
if (Array.isArray(json)) {
loadPages(json)
} else if (json?.pages) {
loadPages(json.pages, json.documentSettings)
loadPages(json.pages, json.documentSettings, json.gallery)
} else {
console.error('Invalid catalog content JSON: missing pages')
return
@@ -85,11 +85,11 @@ const Editor: FC = () => {
scheduleUpdate({
id,
content: JSON.stringify({ pages: pagesToSave, documentSettings }),
content: JSON.stringify({ pages: pagesToSave, documentSettings, gallery }),
})
// عمداً scheduleUpdate را در وابستگی‌ها نیاوردیم تا از لوپ ذخیره‌سازی جلوگیری شود
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id, isInitialContentReady, pages, documentSettings, objects, currentPageId])
}, [id, isInitialContentReady, pages, documentSettings, gallery, objects, currentPageId])
return (
+55 -14
View File
@@ -24,10 +24,15 @@ import EditorCanvasToolbar from "./EditorCanvasToolbar";
import { createScopedId } from "../store/editorStore.helpers";
import { getKonvaGradientProps } from "../utils/gradient";
import { STICKER_DRAG_MIME } from "../types/IconTypes";
import { GALLERY_DRAG_MIME } from "../types/GalleryTypes";
import {
createStickerObject,
scaleStickerDimensions,
} from "../utils/stickerUtils";
import {
createImageObject,
scaleImageDimensions,
} from "../utils/imageUtils";
type EditorCanvasProps = {
catalogSize?: string;
@@ -369,35 +374,69 @@ const EditorCanvas = ({ catalogSize }: EditorCanvasProps) => {
const scaledW = stageSize.width * finalScale;
const scaledH = stageSize.height * finalScale;
const handleStickerDragOver = (e: React.DragEvent) => {
if (!e.dataTransfer.types.includes(STICKER_DRAG_MIME)) return;
const SIDEBAR_DRAG_MIMES = [STICKER_DRAG_MIME, GALLERY_DRAG_MIME];
const handleSidebarDragOver = (e: React.DragEvent) => {
if (!SIDEBAR_DRAG_MIMES.some((mime) => e.dataTransfer.types.includes(mime))) return;
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
};
const placeStickerAt = (imageUrl: string, stageX: number, stageY: number, width: number, height: number) => {
const sticker = createStickerObject(imageUrl, stageX, stageY, width, height);
addObject(sticker);
setSelectedObjectId(sticker.id);
const placeObjectAt = (
imageUrl: string,
stageX: number,
stageY: number,
width: number,
height: number,
type: "sticker" | "image",
) => {
const object =
type === "sticker"
? createStickerObject(
imageUrl,
stageX,
stageY,
width,
height,
stageSize.width,
stageSize.height,
)
: createImageObject(
imageUrl,
stageX,
stageY,
width,
height,
stageSize.width,
stageSize.height,
);
addObject(object);
setSelectedObjectId(object.id);
setTool("select");
};
const handleStickerDrop = (e: React.DragEvent) => {
const imageUrl = e.dataTransfer.getData(STICKER_DRAG_MIME);
if (!imageUrl || !stageWrapRef.current) return;
const handleSidebarDrop = (e: React.DragEvent) => {
const stickerUrl = e.dataTransfer.getData(STICKER_DRAG_MIME);
const galleryUrl = e.dataTransfer.getData(GALLERY_DRAG_MIME);
const imageUrl = stickerUrl || galleryUrl;
const dropType = stickerUrl ? "sticker" : galleryUrl ? "image" : null;
if (!imageUrl || !dropType || !stageWrapRef.current) return;
e.preventDefault();
const rect = stageWrapRef.current.getBoundingClientRect();
const stageX = (e.clientX - rect.left) / finalScale;
const stageY = (e.clientY - rect.top) / finalScale;
const scaleFn =
dropType === "sticker" ? scaleStickerDimensions : scaleImageDimensions;
const img = new Image();
img.onload = () => {
const { width, height } = scaleStickerDimensions(img.naturalWidth, img.naturalHeight);
placeStickerAt(imageUrl, stageX, stageY, width, height);
const { width, height } = scaleFn(img.naturalWidth, img.naturalHeight);
placeObjectAt(imageUrl, stageX, stageY, width, height, dropType);
};
img.onerror = () => {
placeStickerAt(imageUrl, stageX, stageY, 100, 100);
placeObjectAt(imageUrl, stageX, stageY, 100, 100, dropType);
};
img.src = imageUrl;
};
@@ -454,8 +493,8 @@ const EditorCanvas = ({ catalogSize }: EditorCanvasProps) => {
<div
ref={stageWrapRef}
className="shadow-lg"
onDragOver={handleStickerDragOver}
onDrop={handleStickerDrop}
onDragOver={handleSidebarDragOver}
onDrop={handleSidebarDrop}
>
<Stage
ref={stageRef}
@@ -510,6 +549,8 @@ const EditorCanvas = ({ catalogSize }: EditorCanvasProps) => {
onCellDblClick={handleCellDblClick}
onGroup={handleGroupWithMask}
onUngroup={handleUngroupFromMask}
stageWidth={stageSize.width}
stageHeight={stageSize.height}
/>
<GuidesLayer
guides={guides}
@@ -28,6 +28,8 @@ type ObjectRendererProps = {
onCellDblClick?: (tableId: string, cellId: string, x: number, y: number, width: number, height: number, text: string) => void;
selectedCellId?: string | null;
allObjects?: EditorObject[];
stageWidth?: number;
stageHeight?: number;
};
const ObjectRenderer = ({
@@ -42,6 +44,8 @@ const ObjectRenderer = ({
onCellDblClick,
selectedCellId,
allObjects = [],
stageWidth,
stageHeight,
}: ObjectRendererProps) => {
const groupRef = useRef<Konva.Group>(null);
@@ -110,6 +114,8 @@ const ObjectRenderer = ({
onUpdate,
// اگر mask اعمال شده، shape را غیر draggable کن (Group drag می‌شود)
draggable: shouldApplyMask ? false : draggable,
stageWidth,
stageHeight,
};
const renderMaskShape = (mask: EditorObject) => {
@@ -31,6 +31,8 @@ interface ObjectsLayerProps {
) => void;
onGroup: (objectId: string, maskId: string) => void;
onUngroup: (groupId: string) => void;
stageWidth: number;
stageHeight: number;
}
const ObjectsLayer = ({
@@ -51,6 +53,8 @@ const ObjectsLayer = ({
onCellDblClick,
onGroup,
onUngroup,
stageWidth,
stageHeight,
}: ObjectsLayerProps) => {
return (
<Layer ref={layerRef}>
@@ -71,6 +75,8 @@ const ObjectsLayer = ({
onCellDblClick={onCellDblClick}
selectedCellId={selectedCellId}
allObjects={objects}
stageWidth={stageWidth}
stageHeight={stageHeight}
/>
))}
{/* Render non-grouped objects */}
@@ -90,6 +96,8 @@ const ObjectsLayer = ({
onCellDblClick={onCellDblClick}
selectedCellId={selectedCellId}
allObjects={objects}
stageWidth={stageWidth}
stageHeight={stageHeight}
/>
))}
{/* Render objects inside groups - they should not be interactive */}
@@ -115,6 +123,8 @@ const ObjectsLayer = ({
onCellDblClick={onCellDblClick}
selectedCellId={selectedCellId}
allObjects={objects}
stageWidth={stageWidth}
stageHeight={stageHeight}
/>
</Group>
);
@@ -10,9 +10,15 @@ export const useSelectionHandlers = () => {
removeFromSelection,
setSelectedTableId,
setSelectedCellId,
tool,
setTool,
} = useEditorStore();
const handleSelect = (id: string, _node: Konva.Node, e?: Konva.KonvaEventObject<MouseEvent>) => {
if (tool !== "select") {
setTool("select");
}
const obj = objects.find((o) => o.id === id);
const isMultiSelect = e?.evt?.metaKey || e?.evt?.ctrlKey || e?.evt?.shiftKey;
@@ -1,7 +1,6 @@
import { useEditorStore, type ToolType } from "@/pages/editor/store/editorStore";
import { useSingleUpload } from "@/pages/uploader/hooks/useUploaderData";
import { type ToolType } from "@/pages/editor/store/editorStore";
import {
ImageUpload,
ImageGallery,
VideoInput,
LinkInput,
SelectInstruction,
@@ -18,39 +17,8 @@ type ToolInstructionsProps = {
};
const ToolInstructions = ({ tool }: ToolInstructionsProps) => {
const { addObject, setSelectedObjectId, setTool } = useEditorStore();
const { mutateAsync: uploadFile } = useSingleUpload();
const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
try {
const result = await uploadFile(file);
const imageUrl = result?.data?.url;
if (!imageUrl) return;
const img = new Image();
img.onload = () => {
const newImage = {
id: `image-${Date.now()}`,
type: "image" as ToolType,
x: 100,
y: 100,
width: img.width,
height: img.height,
imageUrl,
};
addObject(newImage);
setSelectedObjectId(newImage.id);
setTool("select");
};
img.src = imageUrl;
} catch {
// TODO: show error toast
}
};
if (tool === "image") {
return <ImageUpload onImageUpload={handleImageUpload} />;
return <ImageGallery />;
}
if (tool === "video") {
@@ -18,7 +18,7 @@ const tools: Array<{ icon: (color: string, variant?: "Bold" | "Outline" | "Broke
{ icon: (color, variant) => <Shapes size={20} color={color} variant={variant} />, tool: "rectangle", label: "مستطیل" },
{ icon: (color, variant) => <Text size={20} color={color} variant={variant} />, tool: "text", label: "متن" },
{ icon: (color, variant) => <Grid8 size={20} color={color} variant={variant} />, tool: "grid", label: "گرید" },
{ icon: (color, variant) => <Gallery size={20} color={color} variant={variant} />, tool: "image", label: "تصویر" },
{ icon: (color, variant) => <Gallery size={20} color={color} variant={variant} />, tool: "image", label: "گالری" },
{ icon: (color, variant) => <Link2 size={20} color={color} variant={variant} />, tool: "link", label: "لینک" },
{ icon: (color, variant) => <VideoSquare size={20} color={color} variant={variant} />, tool: "video", label: "ویدیو" },
{ icon: (color, variant) => <ArrowLeft size={20} color={color} variant={variant} />, tool: "arrow", label: "پیکان" },
@@ -0,0 +1,105 @@
import { type FC, useState } from "react";
import { Trash } from "iconsax-react";
import UploadBoxDraggble from "@/components/UploadBoxDraggble";
import { useEditorStore } from "@/pages/editor/store/editorStore";
import { useSingleUpload } from "@/pages/uploader/hooks/useUploaderData";
import { createScopedId } from "@/pages/editor/store/editorStore.helpers";
import { GALLERY_DRAG_MIME } from "@/pages/editor/types/GalleryTypes";
const ImageGallery: FC = () => {
const { gallery, addGalleryItem, removeGalleryItem } = useEditorStore();
const { mutateAsync: uploadFile } = useSingleUpload();
const [isUploading, setIsUploading] = useState(false);
const handleFileChange = async (files: File[]) => {
if (files.length === 0) return;
setIsUploading(true);
try {
for (const file of files) {
const result = await uploadFile(file);
const imageUrl = result?.data?.url;
if (!imageUrl) continue;
const dimensions = await loadImageDimensions(imageUrl);
addGalleryItem({
id: createScopedId("gallery"),
url: imageUrl,
width: dimensions.width,
height: dimensions.height,
});
}
} catch {
// TODO: show error toast
} finally {
setIsUploading(false);
}
};
const handleDragStart = (e: React.DragEvent<HTMLImageElement>, url: string) => {
e.dataTransfer.setData(GALLERY_DRAG_MIME, url);
e.dataTransfer.effectAllowed = "copy";
};
return (
<div className="space-y-3">
<div className="text-base font-bold">گالری</div>
<p className="text-sm text-gray-600">
تصویر را آپلود کنید، سپس از گالری بکشید و روی صفحه رها کنید
</p>
<UploadBoxDraggble
label="تصویر مورد نظر را آپلود کنید"
onChange={handleFileChange}
isMultiple={true}
hidePreview
isLoading={isUploading}
/>
{gallery.length === 0 && !isUploading && (
<p className="text-sm text-gray-500">گالری خالی است</p>
)}
{gallery.length > 0 && (
<div className="grid grid-cols-3 gap-2 max-h-[320px] overflow-y-auto">
{gallery.map((item) => (
<div
key={item.id}
className="group relative flex aspect-square items-center justify-center rounded-lg border border-gray-200 bg-gray-50 p-1 hover:border-blue-300 hover:bg-blue-50 transition-colors"
>
<img
src={item.url}
alt=""
draggable
onDragStart={(e) => handleDragStart(e, item.url)}
className="max-h-full max-w-full object-contain cursor-grab active:cursor-grabbing"
/>
<button
type="button"
onClick={() => removeGalleryItem(item.id)}
className="absolute -left-1 -top-1 hidden size-5 items-center justify-center rounded-full bg-white shadow group-hover:flex"
title="حذف از گالری"
>
<Trash size={12} color="#ef4444" variant="Bold" />
</button>
</div>
))}
</div>
)}
</div>
);
};
const loadImageDimensions = (url: string): Promise<{ width: number; height: number }> =>
new Promise((resolve) => {
const img = new Image();
img.onload = () => {
resolve({ width: img.naturalWidth, height: img.naturalHeight });
};
img.onerror = () => {
resolve({ width: 100, height: 100 });
};
img.src = url;
});
export default ImageGallery;
@@ -1,67 +1 @@
import { type FC, useState, useRef } from "react";
import UploadBoxDraggble from "@/components/UploadBoxDraggble";
type ImageUploadProps = {
onImageUpload: (e: React.ChangeEvent<HTMLInputElement>) => void;
};
const ImageUpload: FC<ImageUploadProps> = ({ onImageUpload }) => {
const [uploadedImages, setUploadedImages] = useState<string[]>([]);
const previousFilesCountRef = useRef<number>(0);
const handleFileChange = (files: File[]) => {
// Update ref to track current files count
if (files.length > previousFilesCountRef.current) {
// Process only new files
const newFiles = files.slice(previousFilesCountRef.current);
newFiles.forEach((file) => {
const reader = new FileReader();
reader.onload = (event) => {
const imageUrl = event.target?.result as string;
setUploadedImages((prev) => [...prev, imageUrl]);
// Create a synthetic event for onImageUpload
const syntheticEvent = {
target: {
files: [file],
},
} as unknown as React.ChangeEvent<HTMLInputElement>;
onImageUpload(syntheticEvent);
};
reader.readAsDataURL(file);
});
}
// Always update ref to track current files count
previousFilesCountRef.current = files.length;
};
const handlePreviewChange = (previews: string[]) => {
setUploadedImages(previews);
// Update ref when previews change (e.g., when files are deleted)
previousFilesCountRef.current = previews.length;
};
return (
<div>
<div className="text-base font-bold mb-4">تصویر</div>
<UploadBoxDraggble
label="تصویر مورد نظر را آپلود کنید"
onChange={handleFileChange}
isMultiple={true}
preview={uploadedImages}
onChangePreview={handlePreviewChange}
/>
{uploadedImages.length > 0 && (
<div className="mt-4 text-description text-xs">
تصویر های آپلود شده
</div>
)}
</div>
);
};
export default ImageUpload;
export { default } from "./ImageGallery";
@@ -1,3 +1,4 @@
export { default as ImageGallery } from "./ImageGallery";
export { default as ImageUpload } from "./ImageUpload";
export { default as DocumentUpload } from "./DocumentUpload";
export { default as VideoInput } from "./VideoInput";
@@ -3,6 +3,7 @@ import { Image as KonvaImage } from "react-konva";
import Konva from "konva";
import useImage from "use-image";
import type { ShapeProps } from "./types";
import { clampPositionToStage } from "../../utils/stageBounds";
const ImageObject = ({
obj,
@@ -10,6 +11,8 @@ const ImageObject = ({
onSelect,
onUpdate,
draggable,
stageWidth,
stageHeight,
}: ShapeProps) => {
const [image] = useImage(obj.imageUrl || "");
const shapeRef = useRef<Konva.Image>(null);
@@ -18,32 +21,58 @@ const ImageObject = ({
if (!image) return null;
const width = obj.width || image.width;
const height = obj.height || image.height;
const hasStageBounds = stageWidth != null && stageHeight != null;
return (
<KonvaImage
ref={shapeRef}
id={obj.id}
name="canvas-object"
x={obj.x}
y={obj.y}
image={image}
width={obj.width || image.width}
height={obj.height || image.height}
// اگر draggable=false باشد، یعنی mask اعمال شده و نباید stroke نمایش داده شود (Group stroke دارد)
stroke={isSelected && draggable ? "#3b82f6" : undefined}
strokeWidth={isSelected && draggable ? 3 : 0}
width={width}
height={height}
stroke={isSelected ? "#3b82f6" : undefined}
strokeWidth={isSelected ? 3 : 0}
rotation={obj.rotation || 0}
draggable={draggable}
onClick={draggable ? (e) => {
// فقط وقتی mask اعمال نشده onClick handler را فعال کن
dragBoundFunc={
draggable && hasStageBounds
? (pos) =>
clampPositionToStage(
pos.x,
pos.y,
width,
height,
stageWidth!,
stageHeight!,
)
: undefined
}
onClick={(e) => {
if (shapeRef.current) {
onSelect(obj.id, shapeRef.current, e);
}
} : undefined}
}}
onDragEnd={(e) => {
const node = e.target;
onUpdate(obj.id, {
x: node.x(),
y: node.y(),
});
let x = node.x();
let y = node.y();
if (hasStageBounds) {
({ x, y } = clampPositionToStage(
x,
y,
width,
height,
stageWidth!,
stageHeight!,
));
node.position({ x, y });
}
onUpdate(obj.id, { x, y });
}}
/>
);
@@ -8,6 +8,8 @@ export type ShapeProps = {
onSelect: (id: string, node: Konva.Node, e?: Konva.KonvaEventObject<MouseEvent>) => void;
onUpdate: (id: string, updates: Partial<EditorObject>) => void;
draggable: boolean;
stageWidth?: number;
stageHeight?: number;
};
export type TextShapeProps = ShapeProps & {
+18 -1
View File
@@ -19,6 +19,7 @@ import type {
TableData,
ToolType,
DocumentSettings,
GalleryItem,
} from "./editorStore.types";
const MAX_OBJECT_HISTORY = 50;
@@ -56,6 +57,7 @@ export type {
TableData,
ToolType,
DocumentSettings,
GalleryItem,
DisplayStyle,
BackgroundType,
EntranceAnimationType,
@@ -149,6 +151,7 @@ type EditorStoreType = {
loadPages: (
pages: Page[],
documentSettings?: Partial<DocumentSettings>,
gallery?: GalleryItem[],
) => void;
resetEditor: () => void;
clipboardObjects: EditorObject[];
@@ -166,6 +169,10 @@ type EditorStoreType = {
updateCurrentPageBackground: (
updates: Partial<PageBackgroundSettings>,
) => void;
gallery: GalleryItem[];
addGalleryItem: (item: GalleryItem) => void;
removeGalleryItem: (id: string) => void;
setGallery: (items: GalleryItem[]) => void;
};
const DEFAULT_DOCUMENT_SETTINGS: DocumentSettings = {
@@ -245,6 +252,14 @@ export const useEditorStore = create<EditorStoreType>((set, get) => {
),
};
}),
gallery: [],
addGalleryItem: (item) =>
set((state) => ({ gallery: [...state.gallery, item] })),
removeGalleryItem: (id) =>
set((state) => ({
gallery: state.gallery.filter((item) => item.id !== id),
})),
setGallery: (items) => set({ gallery: items }),
tool: "select",
setTool: (tool) =>
set((state) => ({
@@ -999,9 +1014,10 @@ export const useEditorStore = create<EditorStoreType>((set, get) => {
objectHistoryPast: [],
objectHistoryFuture: [],
documentSettings: { ...DEFAULT_DOCUMENT_SETTINGS },
gallery: [],
});
},
loadPages: (pages, documentSettings) => {
loadPages: (pages, documentSettings, gallery) => {
if (pages.length === 0) return;
const fallbackSettings = documentSettings ?? {};
const normalizedPages = pages.map((page) => ({
@@ -1036,6 +1052,7 @@ export const useEditorStore = create<EditorStoreType>((set, get) => {
...(documentSettings && {
documentSettings: { ...currentSettings, ...documentSettings },
}),
...(gallery !== undefined && { gallery }),
});
},
};
@@ -120,3 +120,11 @@ export type DocumentSettings = {
backgroundGradient?: LinearGradient;
backgroundImageUrl: string;
};
/** تصویر آپلودشده در گالری کاتالوگ (مشترک بین همهٔ صفحات) */
export type GalleryItem = {
id: string;
url: string;
width?: number;
height?: number;
};
+1
View File
@@ -0,0 +1 @@
export const GALLERY_DRAG_MIME = "application/x-dpage-gallery";
+51
View File
@@ -0,0 +1,51 @@
import type { ToolType } from "../store/editorStore.types";
import { clampPositionToStage, fitSizeToStage } from "./stageBounds";
const IMAGE_MAX_SIZE = 400;
export const scaleImageDimensions = (
naturalWidth: number,
naturalHeight: number,
maxSize = IMAGE_MAX_SIZE,
) => {
let width = naturalWidth;
let height = naturalHeight;
if (width > maxSize || height > maxSize) {
const ratio = Math.min(maxSize / width, maxSize / height);
width = Math.round(width * ratio);
height = Math.round(height * ratio);
}
return { width, height };
};
export const createImageObject = (
imageUrl: string,
centerX: number,
centerY: number,
width: number,
height: number,
stageWidth?: number,
stageHeight?: number,
) => {
let w = width;
let h = height;
if (stageWidth && stageHeight) {
({ width: w, height: h } = fitSizeToStage(w, h, stageWidth, stageHeight));
}
let x = Math.round(centerX - w / 2);
let y = Math.round(centerY - h / 2);
if (stageWidth && stageHeight) {
({ x, y } = clampPositionToStage(x, y, w, h, stageWidth, stageHeight));
}
return {
id: `image-${Date.now()}`,
type: "image" as ToolType,
x,
y,
width: w,
height: h,
imageUrl,
};
};
+27
View File
@@ -0,0 +1,27 @@
export const fitSizeToStage = (
width: number,
height: number,
stageWidth: number,
stageHeight: number,
) => {
if (width <= stageWidth && height <= stageHeight) {
return { width, height };
}
const ratio = Math.min(stageWidth / width, stageHeight / height);
return {
width: Math.round(width * ratio),
height: Math.round(height * ratio),
};
};
export const clampPositionToStage = (
x: number,
y: number,
width: number,
height: number,
stageWidth: number,
stageHeight: number,
) => ({
x: Math.max(0, Math.min(stageWidth - width, Math.round(x))),
y: Math.max(0, Math.min(stageHeight - height, Math.round(y))),
});
+26 -11
View File
@@ -1,4 +1,5 @@
import type { ToolType } from "../store/editorStore.types";
import { clampPositionToStage, fitSizeToStage } from "./stageBounds";
const STICKER_MAX_SIZE = 120;
@@ -21,16 +22,30 @@ export const scaleStickerDimensions = (
export const createStickerObject = (
imageUrl: string,
x: number,
y: number,
centerX: number,
centerY: number,
width: number,
height: number,
) => ({
id: `sticker-${Date.now()}`,
type: "sticker" as ToolType,
x: Math.round(x - width / 2),
y: Math.round(y - height / 2),
width,
height,
imageUrl,
});
stageWidth?: number,
stageHeight?: number,
) => {
let w = width;
let h = height;
if (stageWidth && stageHeight) {
({ width: w, height: h } = fitSizeToStage(w, h, stageWidth, stageHeight));
}
let x = Math.round(centerX - w / 2);
let y = Math.round(centerY - h / 2);
if (stageWidth && stageHeight) {
({ x, y } = clampPositionToStage(x, y, w, h, stageWidth, stageHeight));
}
return {
id: `sticker-${Date.now()}`,
type: "sticker" as ToolType,
x,
y,
width: w,
height: h,
imageUrl,
};
};