import { client } from '@/ui/api/client' import { Button } from '@/ui/components/ui/button' import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, } from '@/ui/components/ui/dialog' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { Input } from '@/ui/components/ui/input' import { Label } from '@/ui/components/ui/label' import { ScrollArea } from '@/ui/components/ui/scroll-area' import { Slider } from '@/ui/components/ui/slider' import { m } from '@/ui/paraglide/messages.js' import { useTeamContextStore } from '@/ui/stores/team-context' import { WatermarkBlock, WatermarkBlockImage, WatermarkBlockText, WatermarkConfigSpec, WatermarkTemplateInfo, } from '@shumai/dtos' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { Check, ChevronLeft, ChevronRight, FolderOpen, Image as ImageIcon, LayoutGrid, Loader2, Plus, Save, Trash2, Type, Upload, X, } from 'lucide-react' import React, { useCallback, useEffect, useRef, useState } from 'react' import { toast } from 'sonner' function AspectIcon({ ratio }: { ratio: string }) { switch (ratio) { case '16:9': return ( ) case '9:16': return ( ) case '4:3': return ( ) case '3:4': return ( ) case '1:1': return default: return ( ) } } function generateUniqueId(): string { return Math.random().toString(36).substring(2, 9) } function createDefaultTextBlock(): WatermarkBlockText { return { id: generateUniqueId(), type: 'text', text: 'CONFIDENTIAL', x: 0.5, y: 0.5, // size is a FRACTION (0..1) of the canvas width size: 0.05, color: '#999999', opacity: 0.5, rotation: -30, } } function createDefaultImageBlock(): WatermarkBlockImage { return { id: generateUniqueId(), type: 'image', imageAssetKey: '', x: 0.5, y: 0.5, // size is a FRACTION (0..1) of the canvas width size: 0.15, opacity: 0.5, rotation: 0, } } const PRESET_BACKGROUND_OPTIONS = [ { id: 'dark', label: 'Dark Slate', bg: '#1e293b', dot: '#475569' }, { id: 'black', label: 'Black', bg: '#000000', dot: '#404040' }, { id: 'gray', label: 'Slate Gray', bg: '#64748b', dot: '#cbd5e1' }, { id: 'white', label: 'White', bg: '#ffffff', dot: '#94a3b8' }, { id: 'green', label: 'Chroma Green', bg: '#059669', dot: '#047857' }, ] // Numeric ratios for the preview aspect-ratio toggle. Used to compute the // fitted canvas size ("contain" fit) so the preview canvas always keeps the // selected aspect ratio strictly, no matter the window dimensions. const ASPECT_RATIOS = { '16:9': 16 / 9, '9:16': 9 / 16, '4:3': 4 / 3, '3:4': 3 / 4, '1:1': 1, } interface WatermarkEditorDialogProps { open: boolean onOpenChange: (open: boolean) => void initialConfig?: WatermarkConfigSpec | null shareId: string teamId?: string | null onSaveSuccess?: () => void } export function WatermarkEditorDialog({ open, onOpenChange, initialConfig, shareId, teamId, onSaveSuccess, }: WatermarkEditorDialogProps) { const queryClient = useQueryClient() const [blocks, setBlocks] = useState([]) const [selectedBlockId, setSelectedBlockId] = useState(null) const [loadedTemplateId, setLoadedTemplateId] = useState(null) const [aspectRatio, setAspectRatio] = useState<'16:9' | '9:16' | '4:3' | '3:4' | '1:1'>('16:9') const [bgColor, setBgColor] = useState('grid') // Save template dialog modal state const [isSaveTemplateOpen, setIsSaveTemplateOpen] = useState(false) const [saveTemplateMode, setSaveTemplateMode] = useState<'new' | 'overwrite'>('new') const [templateName, setTemplateName] = useState('') const [targetOverwriteTemplateId, setTargetOverwriteTemplateId] = useState(null) const canvasRef = useRef(null) const canvasFrameRef = useRef(null) // Fitted size (px) of the preview canvas: the largest box with the selected // aspect ratio that fully fits inside the measured frame ("contain" fit). // This keeps the aspect ratio strict regardless of window dimensions — // relying on CSS alone (e.g. `aspect-[16/9] w-full max-h-full`) breaks the // ratio as soon as the frame is wide-and-short (or tall-and-narrow), because // `w-full` pins the width while `max-h-full` clamps the height. const [canvasSize, setCanvasSize] = useState({ w: 0, h: 0 }) const [isDragging, setIsDragging] = useState(false) // Measure the preview canvas frame and compute the fitted canvas size so // (a) block sizes (stored as a fraction of the canvas width) render at the // correct pixel size inside the preview, and (b) the canvas strictly keeps // the selected aspect ratio while fully fitting inside the frame. // // This is attached via a ref callback instead of a useEffect([open]): // the Radix Dialog defers mounting its content to a later commit, so the // frame element does not exist yet when a [open]-keyed effect first runs — // canvasSize stays 0 and every block silently falls back to the hardcoded // 640px width (`block.size * (canvasSize.w || 640)`), making the preview // render ~72% of the real watermark size. The ref callback fires exactly // when the node mounts, regardless of dialog mount timing, and re-runs when // `aspectRatio` changes so the fit is recomputed on ratio switch. // // clientWidth/clientHeight (padding-box) are measured instead of // getBoundingClientRect() because the latter includes ancestor CSS // transforms (the dialog's zoom-in-95 open animation), which would skew it. const setCanvasFrameRef = useCallback( (el: HTMLDivElement | null) => { canvasFrameRef.current = el if (!el) return const update = () => { const frameW = el.clientWidth const frameH = el.clientHeight if (frameW <= 0 || frameH <= 0) return const ratio = ASPECT_RATIOS[aspectRatio] // "contain" fit: largest box with the given ratio inside the frame let w = frameW let h = w / ratio if (h > frameH) { h = frameH w = h * ratio } setCanvasSize({ w: Math.round(w), h: Math.round(h) }) } update() const observer = new ResizeObserver(update) observer.observe(el) return () => { observer.disconnect() canvasFrameRef.current = null } }, [aspectRatio], ) const contextTeamId = useTeamContextStore((s) => s.teamId) const activeTeamId = teamId || contextTeamId const [isUploadingImage, setIsUploadingImage] = useState(false) const [localImagePreviews, setLocalImagePreviews] = useState>({}) const fileInputRef = useRef(null) const $uploadFile = client.api.teams[':teamId'].files.$post const handleImageFileChange = async (e: React.ChangeEvent, blockId: string) => { const file = e.target.files?.[0] if (!file) return if (file.size > 1 * 1024 * 1024) { toast.error(m.file_exceeds_1mb_limit()) if (fileInputRef.current) fileInputRef.current.value = '' return } if (!activeTeamId) { toast.error(m.failed_upload_file()) return } setIsUploadingImage(true) const localUrl = URL.createObjectURL(file) setLocalImagePreviews((prev) => ({ ...prev, [blockId]: localUrl })) try { const res = await $uploadFile({ param: { teamId: activeTeamId }, form: { file }, }) if (!res.ok) throw new Error(m.failed_upload_file()) const data = await res.json() handleUpdateBlock(blockId, { imageAssetKey: data.key, imageAssetUrl: data.url, }) } catch (err: unknown) { const message = err instanceof Error ? err.message : m.failed_upload_file() toast.error(message) } finally { setIsUploadingImage(false) if (fileInputRef.current) fileInputRef.current.value = '' } } // Initialize blocks from initialConfig or default useEffect(() => { if (open) { if (initialConfig?.blocks && initialConfig.blocks.length > 0) { setBlocks(initialConfig.blocks) setSelectedBlockId(initialConfig.blocks[0].id) } else { const defaultBlock = createDefaultTextBlock() setBlocks([defaultBlock]) setSelectedBlockId(defaultBlock.id) } setLoadedTemplateId(null) } }, [open, initialConfig]) // Fetch watermark templates const { data: templates = [] } = useQuery({ queryKey: ['watermark-templates', teamId], queryFn: async () => { const res = await client.api['watermark-templates'].$get({ query: teamId ? { teamId } : {}, }) if (!res.ok) return [] return await res.json() }, enabled: open, }) // Save watermark to sharelink mutation const $updateWatermark = client.api.shares[':shareId'].watermark.$put const { mutate: saveWatermark, isPending: isSavingWatermark } = useMutation({ mutationFn: async (config: WatermarkConfigSpec) => { const res = await $updateWatermark({ param: { shareId }, json: { enabled: true, config, }, }) if (!res.ok) { const err = await res.json().catch(() => null) throw new Error((err as { error?: string })?.error || m.failed_update()) } return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['share', shareId] }) queryClient.invalidateQueries({ queryKey: ['shares'] }) toast.success(m.watermark_updated()) onOpenChange(false) onSaveSuccess?.() }, onError: (err: Error) => { toast.error(err.message || m.failed_update()) }, }) // Template mutations const $createTemplate = client.api['watermark-templates'].$post const { mutate: createTemplate, isPending: isCreatingTemplate } = useMutation({ mutationFn: async ({ name, config }: { name: string; config: WatermarkConfigSpec }) => { const res = await $createTemplate({ json: { name, teamId: teamId || undefined, config, }, }) if (!res.ok) throw new Error(m.failed_update()) return await res.json() }, onSuccess: (data: WatermarkTemplateInfo) => { queryClient.invalidateQueries({ queryKey: ['watermark-templates'] }) setLoadedTemplateId(data.id) setIsSaveTemplateOpen(false) toast.success(m.template_saved()) }, onError: () => { toast.error(m.failed_update()) }, }) const $updateTemplate = client.api['watermark-templates'][':templateId'].$put const { mutate: updateTemplate, isPending: isUpdatingTemplate } = useMutation({ mutationFn: async ({ templateId, config, }: { templateId: string config: WatermarkConfigSpec }) => { const res = await $updateTemplate({ param: { templateId }, json: { config }, }) if (!res.ok) throw new Error(m.failed_update()) return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['watermark-templates'] }) setIsSaveTemplateOpen(false) toast.success(m.template_updated()) }, onError: () => { toast.error(m.failed_update()) }, }) const $deleteTemplate = client.api['watermark-templates'][':templateId'].$delete const { mutate: deleteTemplate } = useMutation({ mutationFn: async (templateId: string) => { const res = await $deleteTemplate({ param: { templateId }, }) if (!res.ok) throw new Error(m.failed_to_delete()) }, onSuccess: (_, templateId) => { queryClient.invalidateQueries({ queryKey: ['watermark-templates'] }) if (loadedTemplateId === templateId) { setLoadedTemplateId(null) } toast.success(m.template_deleted()) }, onError: () => { toast.error(m.failed_to_delete()) }, }) // Selected block helper const selectedIndex = blocks.findIndex((b) => b.id === selectedBlockId) const selectedBlock = selectedIndex >= 0 ? blocks[selectedIndex] : null // Add block const handleAddTextBlock = () => { const newBlock = createDefaultTextBlock() setBlocks((prev) => [...prev, newBlock]) setSelectedBlockId(newBlock.id) } const handleAddImageBlock = () => { const newBlock = createDefaultImageBlock() setBlocks((prev) => [...prev, newBlock]) setSelectedBlockId(newBlock.id) } // Delete block const handleDeleteBlock = (id: string | null) => { if (!id) return setBlocks((prev) => { const next = prev.filter((b) => b.id !== id) if (selectedBlockId === id) { setSelectedBlockId(next.length > 0 ? next[Math.max(0, selectedIndex - 1)].id : null) } return next }) } // Update specific block property const handleUpdateBlock = (id: string, updates: Partial) => { setBlocks((prev) => prev.map((b) => (b.id === id ? ({ ...b, ...updates } as WatermarkBlock) : b)), ) } // Navigation helpers const handlePrevBlock = () => { if (blocks.length === 0) return const prevIdx = (selectedIndex - 1 + blocks.length) % blocks.length setSelectedBlockId(blocks[prevIdx].id) } const handleNextBlock = () => { if (blocks.length === 0) return const nextIdx = (selectedIndex + 1) % blocks.length setSelectedBlockId(blocks[nextIdx].id) } // Canvas Drag & Drop handlers const handleMouseDownCanvasBlock = (e: React.MouseEvent, id: string) => { e.stopPropagation() setSelectedBlockId(id) setIsDragging(true) } const handleMouseMove = useCallback( (e: MouseEvent) => { if (!isDragging || !selectedBlockId || !canvasRef.current) return const rect = canvasRef.current.getBoundingClientRect() const rawX = (e.clientX - rect.left) / rect.width const rawY = (e.clientY - rect.top) / rect.height const clampedX = Math.max(0, Math.min(1, Math.round(rawX * 100) / 100)) const clampedY = Math.max(0, Math.min(1, Math.round(rawY * 100) / 100)) handleUpdateBlock(selectedBlockId, { x: clampedX, y: clampedY }) }, [isDragging, selectedBlockId], ) const handleMouseUp = useCallback(() => { setIsDragging(false) }, []) useEffect(() => { if (isDragging) { window.addEventListener('mousemove', handleMouseMove) window.addEventListener('mouseup', handleMouseUp) } return () => { window.removeEventListener('mousemove', handleMouseMove) window.removeEventListener('mouseup', handleMouseUp) } }, [isDragging, handleMouseMove, handleMouseUp]) // Keyboard shortcut for deleting block useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { if (!open || !selectedBlockId) return const targetTag = (e.target as HTMLElement)?.tagName?.toLowerCase() if (targetTag === 'input' || targetTag === 'textarea' || targetTag === 'select') return if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault() handleDeleteBlock(selectedBlockId) } } window.addEventListener('keydown', handleKeyDown) return () => window.removeEventListener('keydown', handleKeyDown) }, [open, selectedBlockId, selectedIndex]) // Load template const handleSelectTemplate = (tpl: WatermarkTemplateInfo) => { if (tpl.config?.blocks && tpl.config.blocks.length > 0) { const clonedBlocks = tpl.config.blocks.map((b) => ({ ...b, id: generateUniqueId(), })) setBlocks(clonedBlocks) setSelectedBlockId(clonedBlocks[0].id) setLoadedTemplateId(tpl.id) } } const handleSaveWatermark = () => { if (blocks.length === 0) { toast.error(m.no_watermark_blocks()) return } saveWatermark({ blocks }) } const handleConfirmSaveTemplate = () => { if (saveTemplateMode === 'new') { if (!templateName.trim()) { toast.error(m.enter_template_name()) return } createTemplate({ name: templateName.trim(), config: { blocks } }) } else { const targetId = targetOverwriteTemplateId || loadedTemplateId if (!targetId) { toast.error(m.select_template_to_overwrite()) return } updateTemplate({ templateId: targetId, config: { blocks } }) } } return ( <> e.preventDefault()} > {/* Header */}
{m.watermark_editor()}
{/* Templates Dropdown Menu */} {m.load_template()} {templates.length === 0 ? (
{m.no_templates_found()}
) : ( templates.map((tpl) => ( handleSelectTemplate(tpl)} className="flex items-center justify-between text-xs cursor-pointer" > {tpl.name} {loadedTemplateId === tpl.id && ( )} )) )} { setSaveTemplateMode('new') setTemplateName('') setIsSaveTemplateOpen(true) }} className="text-xs gap-2 cursor-pointer" > {m.create_new_template()} {templates.length > 0 && ( { setSaveTemplateMode('overwrite') setTargetOverwriteTemplateId(loadedTemplateId || templates[0].id) setIsSaveTemplateOpen(true) }} className="text-xs gap-2 cursor-pointer" > {m.overwrite_existing_template()} )}
{/* Main 2-Column Content Area */}
{/* Left Preview Column (2/3 width) */}
{/* Single Row Controls Header */}
{/* Aspect Ratio Toggles */}
{(['16:9', '9:16', '4:3', '3:4', '1:1'] as const).map((ratio) => ( ))}
{/* 5 Predefined Background Color Swatches */}
{PRESET_BACKGROUND_OPTIONS.map((color) => (
{/* Canvas Frame */}
{(() => { const activeBg = PRESET_BACKGROUND_OPTIONS.find((b) => b.id === bgColor) || PRESET_BACKGROUND_OPTIONS[0] const hasFittedSize = canvasSize.w > 0 && canvasSize.h > 0 return (
setSelectedBlockId(null)} style={{ backgroundColor: activeBg.bg, backgroundImage: `radial-gradient(${activeBg.dot} 1px, transparent 1px)`, backgroundSize: '16px 16px', // Explicit fitted size keeps the aspect ratio strict. // The aspect-* classes below remain as a first-paint // fallback for the moment before the frame is measured // by the ResizeObserver above. ...(hasFittedSize ? { width: canvasSize.w, height: canvasSize.h } : {}), }} className={cn( 'relative rounded-lg border border-border overflow-hidden shadow-inner transition-all', aspectRatio === '16:9' && 'aspect-[16/9] w-full max-h-full', aspectRatio === '9:16' && 'aspect-[9/16] h-full max-w-full', aspectRatio === '4:3' && 'aspect-[4/3] w-full max-h-full', aspectRatio === '3:4' && 'aspect-[3/4] h-full max-w-full', aspectRatio === '1:1' && 'aspect-square h-full max-w-full', )} > {/* Render Blocks */} {blocks.map((block) => { const isSelected = block.id === selectedBlockId // Preview scale: size is a fraction of the canvas width, so // multiply by the measured preview box width (fallback 640px). const blockSizePx = block.size * (canvasSize.w || 640) return (
handleMouseDownCanvasBlock(e, block.id)} onClick={(e) => { e.stopPropagation() setSelectedBlockId(block.id) }} style={{ left: `${block.x * 100}%`, top: `${block.y * 100}%`, transform: `translate(-50%, -50%) rotate(${block.rotation}deg)`, opacity: block.opacity, }} className={cn( 'absolute cursor-move select-none transition-shadow rounded p-1.5 flex items-center justify-center', isSelected ? 'ring-2 ring-primary ring-offset-2 ring-offset-background/80 bg-primary/10' : 'hover:ring-1 hover:ring-muted-foreground/50', )} > {block.type === 'text' ? ( {block.text || 'Text'} ) : (
{localImagePreviews[block.id] || (block as WatermarkBlockImage).imageAssetUrl ? ( Watermark logo ) : ( )}
)}
) })}
) })()}
{/* Right Configuration Column (1/3 width) */}
{/* Right Column Header */}
{m.watermark()}
{/* Block Selector Navigation Row */}
{blocks.map((b, idx) => ( setSelectedBlockId(b.id)} className="text-xs flex items-center justify-between cursor-pointer" > {b.type === 'text' ? ( ) : ( )} {b.type === 'text' ? b.text || 'Text' : (b as WatermarkBlockImage).imageAssetKey || 'Image'} #{idx + 1} ))}
{selectedBlock && ( )} {m.add_text_block()} {m.add_image_block()}
{/* Property Controls */} {/* min-h-0 lets the ScrollArea shrink to the column's remaining height instead of growing to its content height (flex items default to min-height:auto), which would overflow the column and collapse the scrollable range to ~0. */} {selectedBlock ? (
{/* Block Type Badge */}
{selectedBlock.type === 'text' ? ( ) : ( )} {selectedBlock.type === 'text' ? m.add_text_block() : m.add_image_block()} ID: {selectedBlock.id.slice(0, 6)}
{/* Text specific fields */} {selectedBlock.type === 'text' && (
handleUpdateBlock(selectedBlock.id, { text: e.target.value }) } className="text-xs h-8" />
)} {/* Image specific fields */} {selectedBlock.type === 'image' && (
{(selectedBlock as WatermarkBlockImage).imageAssetKey && ( )}
handleImageFileChange(e, selectedBlock.id)} />
fileInputRef.current?.click()} className="relative aspect-square w-full rounded-xl border border-dashed border-border flex items-center justify-center cursor-pointer overflow-hidden group shadow-inner bg-muted/20 hover:border-primary/50 hover:bg-muted/40 transition-all p-2" > {isUploadingImage && (
{m.uploading()}
)} {localImagePreviews[selectedBlock.id] || (selectedBlock as WatermarkBlockImage).imageAssetUrl ? ( <> Uploaded logo preview
{m.upload_image()}
) : (

{m.upload_watermark_image()}

{m.upload_watermark_image_hint()}

)}
)} {/* Size Control (fraction 0..1 of canvas width, shown as %) */}
{Math.round(selectedBlock.size * 100)}%
handleUpdateBlock(selectedBlock.id, { size: val }) } className="flex-1" /> handleUpdateBlock(selectedBlock.id, { size: Math.min(1, Math.max(0.001, Number(e.target.value) / 100)), }) } className="w-16 h-7 text-xs font-mono text-right" />
{/* Color Control for Text */} {selectedBlock.type === 'text' && (
{(selectedBlock as WatermarkBlockText).color}
handleUpdateBlock(selectedBlock.id, { color: e.target.value }) } className="w-8 h-8 rounded border border-border cursor-pointer bg-transparent p-0" /> handleUpdateBlock(selectedBlock.id, { color: e.target.value }) } className="flex-1 h-8 text-xs font-mono" />
{[ '#FFFFFF', '#000000', '#999999', '#EF4444', '#3B82F6', '#10B981', '#F59E0B', ].map((hex) => (
)} {/* Opacity Control */}
{Math.round(selectedBlock.opacity * 100)}%
handleUpdateBlock(selectedBlock.id, { opacity: val }) } />
{/* Rotation Control */}
{selectedBlock.rotation}°
handleUpdateBlock(selectedBlock.id, { rotation: val }) } />
{[-45, -30, 0, 30, 45].map((deg) => ( ))}
{/* Position X Control */}
{Math.round(selectedBlock.x * 100)}%
handleUpdateBlock(selectedBlock.id, { x: val })} />
{/* Position Y Control */}
{Math.round(selectedBlock.y * 100)}%
handleUpdateBlock(selectedBlock.id, { y: val })} />
) : (

{m.select_block_to_edit()}

)}
{/* Save Template Mini Modal */} {saveTemplateMode === 'new' ? m.create_new_template() : m.overwrite_existing_template()}
{saveTemplateMode === 'new' ? (
setTemplateName(e.target.value)} placeholder={m.enter_template_name()} className="text-xs" />
) : (
)}
) } function cn(...classes: (string | boolean | undefined | null)[]) { return classes.filter(Boolean).join(' ') }