Files
shumai/packages/webui/components/watermark-editor-dialog.tsx
T
Yiling-J 03aea2cb36 feat(sharelink): add sharelink watermark support (#270)
* feat(sharelink): add sharelink watermark support

* fix(sharelink): harden watermark feature against races, crashes, and tenant leaks

Addresses review findings on the sharelink watermark feature:

- fix(watermark): read back sharelink via transaction client so the
  updateShareLinkWatermark response reflects the just-committed state
  (global-client reads on a pooled connection miss uncommitted changes)
- fix(watermark): use prisma upsert on the config hash instead of
  find-then-create to avoid P2002 races on concurrent enables
- fix(watermark): resolve nested symlinks when walking the share tree and
  batch the walk level-by-level instead of one query per node
- fix(watermark): keep watermark tasks in flight from being purged by
  orphan-config GC (avoids FK violations in completing activities)
- fix(transcode): re-transcode stale 'processing' watermark rows instead
  of silently skipping (crash recovery); downscale embedded block images;
  use pino structured logging; drop unused any casts
- fix(api): scope watermark-template list/create to the caller's teams,
  reject teamless template creation, and make teamless templates
  read-only; validate watermark config required when enabling (400);
  map sharelink-not-found to 404
- fix(api): resolve symlink target ids once in public share children
  endpoint instead of twice per item
- refactor(db): dedicated WatermarkFileStatus enum (migration included)
- test: activity unit tests (init crash recovery, image + video transcode
  paths), concurrent upsert, nested-symlink resolution, API scoping and
  validation, e2e video watermark path

* refactor(transcode): move sharp usage out of watermark activity into transcodeService

The transcode package does not declare sharp as a dependency (only
@shumai/core does), so importing it directly in the watermark activity
broke CI typecheck for the transcode package.

- add transcodeService.renderSvgToPng, downscaleImageToPng and
  compositeOverlayToWebpFile encapsulating the sharp logic
- watermark activity now calls these methods instead of importing sharp
- activity tests mock the new methods (no sharp/real fixture needed)
- add unit tests for the new transcodeService helpers

* feat(watermark): restrict watermark transcode to existing image and video transcodes

* refactor(transcode): reuse transcodeVideo in watermark activity

* refactor(watermark): use Bun.hash instead of node crypto for watermark config hash

* refactor(watermark): move computeWatermarkConfigHash from dtos to core watermark-hash module

* refactor(api): delegate watermark DB queries from public-share route to watermarkService

* refactor(share): replace dynamic watermarkService import with static import

* feat(watermark): add waitForWatermarkFileActivity for in-flight watermark transcoding tasks

* refactor(asset): replace dynamic watermarkService import with static import

* test(watermark): harden purgeOrphanWatermarkConfigs coverage

Replace the single happy-path GC test with a dedicated suite covering:

- orphan config with proxies: purged, watermarkFiles removed, all four
  proxy keys deleted from S3 while the original key is preserved
- config still referenced by a share link is not purged
- config with pending/processing transcode_watermark tasks is not purged
  (in-flight guard), but completed tasks do not block purging
- pending tasks of other types (transcode_video) do not protect a config
- an S3 delete failure is non-fatal: remaining keys still deleted and the
  config is still purged
- mixed run: only the orphan config is purged while a referenced one
  survives (exact count assertion)

* feat(webui): add sharelink watermark editor and sidebar controls

* style(webui): enlarge watermark editor dialog and allocate 2/3 width to preview column

* fix(webui): override sm:max-w-lg in DialogContent to allow full 1400px width

* fix(webui): stop block click propagation and remove preview mode toggles

* fix(webui): store watermark block size as fraction of canvas width

The editor stored block.size in pixels (slider 10-120px, preview
fontSize: `${block.size}px`) while the SVG generator
(generateWatermarkSvg) interprets size as a fraction (0..1) of canvas
width. A 36px block therefore rendered as a ~36x-canvas glyph covering
the entire image.

- Keep backend fraction semantics (canvasWidth * size) so watermarks
  scale proportionally with output resolution across proxies
- Editor: defaults (text 5%, image 15%), slider ranges (1-12% / 2-50%)
  and number input now work in percent, storing a fraction
- Preview: scales blocks by the measured canvas width so WYSIWYG
- DTO schema: size constrained to (0..1) to enforce the contract
- Update DTO/editor tests to fraction sizes

* feat(webui): add single-row aspect ratio selector and 5 predefined background colors to watermark editor preview

* feat(webui): update aspect ratio to multi-toggle group and enable dot-grid pattern for all background colors

* fix(webui): update background swatches to distinct colors and share PRESET_BACKGROUND_OPTIONS array

* fix(webui): hide redundant absolute close button on watermark editor dialog header

* fix(transcode): skip raw video transcode when generating watermark proxies

The raw marker entry (isRaw: true) in videoTranscodes points at the
original source file and is only used to offer the 'Original' playback
option. It is not a transcoded proxy, so watermarking it produced a
redundant full-resolution transcode (the most expensive pass) plus an
unneeded S3 upload.

Skip entries with isRaw: true in transcodeWatermarkMediaActivity, and
cover the behavior with a unit regression test plus an e2e assertion
that exactly one watermark proxy is produced for a video asset.

* feat(webui): replace watermark image asset ID with 1MB file uploader

* fix(webui): correct watermark editor preview block sizing

The preview canvas width was measured in a useEffect([open]) that ran
before the Radix Dialog had mounted its content, so canvasRef.current was
still null, canvasWidthPx stayed 0, and every block silently fell back to
the hardcoded 640px width (block.size * (canvasWidthPx || 640)). A 100%
size therefore rendered at ~640px on an ~876px canvas (~72%), making the
preview smaller than the real watermarked output for both image and text
blocks.

- Measure the canvas via a ref callback (fires exactly when the node
  mounts, regardless of dialog mount timing) and keep a ResizeObserver
  attached for aspect-ratio/window changes.
- Use clientWidth (padding-box width) instead of getBoundingClientRect(),
  which includes the dialog's zoom-in-95 animation transform.
- Drop max-w-full/max-h-full on the preview <img> so logos scale up to
  the block size like the backend SVG rendering does, instead of being
  capped at their natural pixel size.

* fix(webui): keep watermark editor preview aspect ratio and restore config scroll

- Compute the preview canvas size with a JS contain-fit (ResizeObserver on the
  frame) instead of relying on CSS aspect-ratio + w-full/max-h-full, which
  broke the selected ratio on wide-and-short (or tall-and-narrow) windows.
- Add min-h-0 to the config ScrollArea so it shrinks to the column's remaining
  height instead of growing to its content height, restoring the scroll range.

* fix(webui): remove toast notification on template load

* fix(share): serve per-file watermark proxies in public share APIs

Stop gating watermark replacement on the share-link-wide watermarkStatus.
Public share endpoints now resolve each asset's own completed watermark
proxy and:

- replace videoTranscodes/imageTranscodes with the watermarked entries
  when the watermark file is completed;
- empty those arrays when no completed proxy exists yet (still
  transcoding or failed) so original, unwatermarked media is never
  exposed while a newly added file is being processed;
- leave non-video/image media (pdf, audio, ...) untouched, since they
  never receive watermark transcodes.

This removes the previous behavior where adding a file to a ready
watermark share flipped the whole share link to processing and served
original media for every file until the new transcode finished.

Adds API tests for detail/children endpoints (ready, in-flight, pdf, and
watermark-disabled cases) and a workflow E2E test for adding an asset to
an already-ready watermark sharelink.
2026-08-07 21:36:20 +08:00

1261 lines
51 KiB
TypeScript

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 (
<span className="inline-block w-4 h-2.5 border border-current rounded-[1px] shrink-0" />
)
case '9:16':
return (
<span className="inline-block w-2.5 h-4 border border-current rounded-[1px] shrink-0" />
)
case '4:3':
return (
<span className="inline-block w-3.5 h-2.5 border border-current rounded-[1px] shrink-0" />
)
case '3:4':
return (
<span className="inline-block w-2.5 h-3.5 border border-current rounded-[1px] shrink-0" />
)
case '1:1':
return <span className="inline-block w-3 h-3 border border-current rounded-[1px] shrink-0" />
default:
return (
<span className="inline-block w-4 h-2.5 border border-current rounded-[1px] shrink-0" />
)
}
}
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<WatermarkBlock[]>([])
const [selectedBlockId, setSelectedBlockId] = useState<string | null>(null)
const [loadedTemplateId, setLoadedTemplateId] = useState<string | null>(null)
const [aspectRatio, setAspectRatio] = useState<'16:9' | '9:16' | '4:3' | '3:4' | '1:1'>('16:9')
const [bgColor, setBgColor] = useState<string>('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<string | null>(null)
const canvasRef = useRef<HTMLDivElement>(null)
const canvasFrameRef = useRef<HTMLDivElement>(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<Record<string, string>>({})
const fileInputRef = useRef<HTMLInputElement>(null)
const $uploadFile = client.api.teams[':teamId'].files.$post
const handleImageFileChange = async (e: React.ChangeEvent<HTMLInputElement>, 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<WatermarkTemplateInfo[]>({
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<WatermarkBlock>) => {
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 (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
showCloseButton={false}
className="sm:max-w-[1400px] max-w-[95vw] w-[95vw] h-[88vh] flex flex-col p-0 gap-0 overflow-hidden"
onPointerDownOutside={(e) => e.preventDefault()}
>
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-border bg-card">
<div className="flex items-center gap-3">
<DialogTitle className="text-base font-semibold">{m.watermark_editor()}</DialogTitle>
</div>
<div className="flex items-center gap-2">
{/* Templates Dropdown Menu */}
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="gap-2 text-xs">
<FolderOpen className="h-4 w-4 text-muted-foreground" />
{m.watermark_templates()}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel className="text-xs font-semibold text-muted-foreground">
{m.load_template()}
</DropdownMenuLabel>
{templates.length === 0 ? (
<div className="px-2 py-1.5 text-xs text-muted-foreground italic">
{m.no_templates_found()}
</div>
) : (
templates.map((tpl) => (
<DropdownMenuItem
key={tpl.id}
onClick={() => handleSelectTemplate(tpl)}
className="flex items-center justify-between text-xs cursor-pointer"
>
<span className="truncate flex-1">{tpl.name}</span>
{loadedTemplateId === tpl.id && (
<Check className="h-3.5 w-3.5 text-primary ml-2 flex-shrink-0" />
)}
<Button
variant="ghost"
size="icon"
className="h-5 w-5 hover:bg-destructive/10 hover:text-destructive ml-1"
onClick={(e) => {
e.stopPropagation()
deleteTemplate(tpl.id)
}}
>
<Trash2 className="h-3 w-3" />
</Button>
</DropdownMenuItem>
))
)}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => {
setSaveTemplateMode('new')
setTemplateName('')
setIsSaveTemplateOpen(true)
}}
className="text-xs gap-2 cursor-pointer"
>
<Plus className="h-3.5 w-3.5 text-primary" />
{m.create_new_template()}
</DropdownMenuItem>
{templates.length > 0 && (
<DropdownMenuItem
onClick={() => {
setSaveTemplateMode('overwrite')
setTargetOverwriteTemplateId(loadedTemplateId || templates[0].id)
setIsSaveTemplateOpen(true)
}}
className="text-xs gap-2 cursor-pointer"
>
<Save className="h-3.5 w-3.5 text-muted-foreground" />
{m.overwrite_existing_template()}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
<Button
variant="outline"
size="sm"
className="text-xs"
onClick={() => onOpenChange(false)}
>
{m.cancel()}
</Button>
<Button
size="sm"
className="text-xs bg-primary hover:bg-primary/90 text-primary-foreground gap-1.5"
disabled={isSavingWatermark}
onClick={handleSaveWatermark}
>
<Save className="h-3.5 w-3.5" />
{m.save_watermark()}
</Button>
</div>
</div>
{/* Main 2-Column Content Area */}
<div className="flex-1 flex overflow-hidden">
{/* Left Preview Column (2/3 width) */}
<div className="w-[65%] flex flex-col p-4 bg-muted/20 border-r border-border overflow-hidden select-none">
{/* Single Row Controls Header */}
<div className="flex items-center justify-between mb-3">
{/* Aspect Ratio Toggles */}
<div className="flex items-center gap-1 bg-muted/60 p-1 rounded-md border border-border/60">
{(['16:9', '9:16', '4:3', '3:4', '1:1'] as const).map((ratio) => (
<Button
key={ratio}
variant={aspectRatio === ratio ? 'secondary' : 'ghost'}
size="sm"
className={cn(
'h-7 px-2.5 text-xs gap-1.5 font-mono transition-all',
aspectRatio === ratio
? 'bg-background shadow-xs font-semibold text-foreground border border-border/50'
: 'text-muted-foreground hover:text-foreground',
)}
onClick={() => setAspectRatio(ratio)}
>
<AspectIcon ratio={ratio} />
<span>{ratio}</span>
</Button>
))}
</div>
{/* 5 Predefined Background Color Swatches */}
<div className="flex items-center gap-1.5 bg-background border border-border/60 rounded-md p-1">
{PRESET_BACKGROUND_OPTIONS.map((color) => (
<button
key={color.id}
type="button"
onClick={() => setBgColor(color.id)}
style={{ backgroundColor: color.bg }}
className={cn(
'w-5 h-5 rounded-full border border-border/80 transition-all cursor-pointer relative',
bgColor === color.id
? 'ring-2 ring-primary ring-offset-1 scale-110'
: 'hover:scale-105 opacity-80 hover:opacity-100',
)}
title={color.label}
/>
))}
</div>
</div>
{/* Canvas Frame */}
<div
ref={setCanvasFrameRef}
className="flex-1 flex items-center justify-center overflow-hidden"
>
{(() => {
const activeBg =
PRESET_BACKGROUND_OPTIONS.find((b) => b.id === bgColor) ||
PRESET_BACKGROUND_OPTIONS[0]
const hasFittedSize = canvasSize.w > 0 && canvasSize.h > 0
return (
<div
ref={canvasRef}
onClick={() => 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 (
<div
key={block.id}
onMouseDown={(e) => 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' ? (
<span
style={{
fontSize: `${blockSizePx}px`,
color: block.color,
lineHeight: 1,
whiteSpace: 'nowrap',
fontWeight: 700,
textShadow: '0 1px 3px rgba(0,0,0,0.5)',
}}
>
{block.text || 'Text'}
</span>
) : (
<div
style={{
width: `${blockSizePx}px`,
height: `${blockSizePx}px`,
}}
className="bg-primary/20 border border-primary/40 rounded flex items-center justify-center p-1 overflow-hidden"
>
{localImagePreviews[block.id] ||
(block as WatermarkBlockImage).imageAssetUrl ? (
<img
src={
localImagePreviews[block.id] ||
(block as WatermarkBlockImage).imageAssetUrl
}
alt="Watermark logo"
className="w-full h-full object-contain pointer-events-none"
/>
) : (
<ImageIcon className="h-1/2 w-1/2 opacity-70 text-primary" />
)}
</div>
)}
</div>
)
})}
</div>
)
})()}
</div>
</div>
{/* Right Configuration Column (1/3 width) */}
<div className="w-[35%] flex flex-col bg-card overflow-hidden border-l border-border">
{/* Right Column Header */}
<div className="p-4 border-b border-border bg-muted/10 flex items-center justify-between">
<div className="flex items-center gap-2">
<LayoutGrid className="h-4 w-4 text-muted-foreground" />
<span className="text-xs font-semibold">{m.watermark()}</span>
</div>
</div>
{/* Block Selector Navigation Row */}
<div className="p-3 border-b border-border bg-background flex items-center justify-between gap-2">
<div className="flex items-center gap-1">
<Button
variant="outline"
size="icon"
className="h-7 w-7"
disabled={blocks.length <= 1}
onClick={handlePrevBlock}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs font-mono">
{blocks.length === 0 ? '0 / 0' : `${selectedIndex + 1} / ${blocks.length}`}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-48">
{blocks.map((b, idx) => (
<DropdownMenuItem
key={b.id}
onClick={() => setSelectedBlockId(b.id)}
className="text-xs flex items-center justify-between cursor-pointer"
>
<span className="flex items-center gap-2 truncate">
{b.type === 'text' ? (
<Type className="h-3.5 w-3.5 text-muted-foreground" />
) : (
<ImageIcon className="h-3.5 w-3.5 text-muted-foreground" />
)}
{b.type === 'text'
? b.text || 'Text'
: (b as WatermarkBlockImage).imageAssetKey || 'Image'}
</span>
<span className="text-[10px] font-mono text-muted-foreground ml-2">
#{idx + 1}
</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
<Button
variant="outline"
size="icon"
className="h-7 w-7"
disabled={blocks.length <= 1}
onClick={handleNextBlock}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
<div className="flex items-center gap-1">
{selectedBlock && (
<Button
variant="ghost"
size="icon"
className="h-7 w-7 text-destructive hover:bg-destructive/10"
title={m.delete()}
onClick={() => handleDeleteBlock(selectedBlock.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
)}
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button size="sm" className="h-7 text-xs gap-1">
<Plus className="h-3.5 w-3.5" />
{m.add()}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={handleAddTextBlock}
className="text-xs gap-2 cursor-pointer"
>
<Type className="h-3.5 w-3.5" />
{m.add_text_block()}
</DropdownMenuItem>
<DropdownMenuItem
onClick={handleAddImageBlock}
className="text-xs gap-2 cursor-pointer"
>
<ImageIcon className="h-3.5 w-3.5" />
{m.add_image_block()}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{/* 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. */}
<ScrollArea className="flex-1 min-h-0 p-4">
{selectedBlock ? (
<div className="space-y-5 text-xs">
{/* Block Type Badge */}
<div className="flex items-center justify-between pb-2 border-b border-border">
<span className="font-semibold text-muted-foreground flex items-center gap-1.5">
{selectedBlock.type === 'text' ? (
<Type className="h-4 w-4 text-primary" />
) : (
<ImageIcon className="h-4 w-4 text-primary" />
)}
{selectedBlock.type === 'text' ? m.add_text_block() : m.add_image_block()}
</span>
<span className="text-[10px] font-mono text-muted-foreground">
ID: {selectedBlock.id.slice(0, 6)}
</span>
</div>
{/* Text specific fields */}
{selectedBlock.type === 'text' && (
<div className="space-y-2">
<Label className="text-xs">{m.text_content()}</Label>
<Input
type="text"
value={(selectedBlock as WatermarkBlockText).text}
onChange={(e) =>
handleUpdateBlock(selectedBlock.id, { text: e.target.value })
}
className="text-xs h-8"
/>
</div>
)}
{/* Image specific fields */}
{selectedBlock.type === 'image' && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.image_asset_key()}</Label>
{(selectedBlock as WatermarkBlockImage).imageAssetKey && (
<button
type="button"
onClick={() =>
handleUpdateBlock(selectedBlock.id, {
imageAssetKey: '',
imageAssetUrl: undefined,
})
}
className="text-xs text-muted-foreground hover:text-destructive flex items-center gap-1 font-medium transition-colors cursor-pointer"
>
<X className="w-3.5 h-3.5" />
{m.remove ? m.remove() : 'Remove'}
</button>
)}
</div>
<input
type="file"
ref={fileInputRef}
className="hidden"
accept="image/*"
onChange={(e) => handleImageFileChange(e, selectedBlock.id)}
/>
<div
onClick={() => 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 && (
<div className="absolute inset-0 bg-background/70 backdrop-blur-xs flex flex-col items-center justify-center gap-2 z-20">
<div className="flex items-center gap-2 px-3 py-1.5 bg-background border rounded-full shadow-lg">
<Loader2 className="w-4 h-4 animate-spin text-primary" />
<span className="text-xs font-semibold">{m.uploading()}</span>
</div>
</div>
)}
{localImagePreviews[selectedBlock.id] ||
(selectedBlock as WatermarkBlockImage).imageAssetUrl ? (
<>
<img
src={
localImagePreviews[selectedBlock.id] ||
(selectedBlock as WatermarkBlockImage).imageAssetUrl
}
alt="Uploaded logo preview"
className="max-w-full max-h-full object-contain transition-transform duration-300 group-hover:scale-105"
/>
<div className="absolute inset-0 bg-black/45 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col items-center justify-center gap-1 text-white z-10">
<Upload className="w-5 h-5 transform translate-y-1 group-hover:translate-y-0 transition-transform duration-300" />
<span className="text-xs font-semibold">{m.upload_image()}</span>
</div>
</>
) : (
<div className="flex flex-col items-center gap-1.5 text-center p-3">
<div className="p-2 rounded-full bg-background border shadow-xs group-hover:scale-110 transition-transform duration-300">
<Upload className="w-4 h-4 text-muted-foreground" />
</div>
<div>
<p className="text-xs font-medium text-foreground">
{m.upload_watermark_image()}
</p>
<p className="text-[10px] text-muted-foreground mt-0.5 max-w-[150px] mx-auto leading-normal">
{m.upload_watermark_image_hint()}
</p>
</div>
</div>
)}
</div>
</div>
)}
{/* Size Control (fraction 0..1 of canvas width, shown as %) */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">
{selectedBlock.type === 'text' ? m.font_size() : m.image_size()}
</Label>
<span className="font-mono text-[11px] text-muted-foreground">
{Math.round(selectedBlock.size * 100)}%
</span>
</div>
<div className="flex items-center gap-3">
<Slider
min={selectedBlock.type === 'text' ? 0.01 : 0.02}
max={selectedBlock.type === 'text' ? 0.12 : 0.5}
step={0.005}
value={[selectedBlock.size]}
onValueChange={([val]) =>
handleUpdateBlock(selectedBlock.id, { size: val })
}
className="flex-1"
/>
<Input
type="number"
min={1}
max={100}
value={Math.round(selectedBlock.size * 100)}
onChange={(e) =>
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"
/>
</div>
</div>
{/* Color Control for Text */}
{selectedBlock.type === 'text' && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.color()}</Label>
<span className="font-mono text-[11px] text-muted-foreground uppercase">
{(selectedBlock as WatermarkBlockText).color}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="color"
value={(selectedBlock as WatermarkBlockText).color}
onChange={(e) =>
handleUpdateBlock(selectedBlock.id, { color: e.target.value })
}
className="w-8 h-8 rounded border border-border cursor-pointer bg-transparent p-0"
/>
<Input
type="text"
value={(selectedBlock as WatermarkBlockText).color}
onChange={(e) =>
handleUpdateBlock(selectedBlock.id, { color: e.target.value })
}
className="flex-1 h-8 text-xs font-mono"
/>
</div>
<div className="flex items-center gap-1.5 pt-1">
{[
'#FFFFFF',
'#000000',
'#999999',
'#EF4444',
'#3B82F6',
'#10B981',
'#F59E0B',
].map((hex) => (
<button
key={hex}
type="button"
onClick={() => handleUpdateBlock(selectedBlock.id, { color: hex })}
style={{ backgroundColor: hex }}
className="w-5 h-5 rounded-full border border-border hover:scale-110 transition-transform"
/>
))}
</div>
</div>
)}
{/* Opacity Control */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.opacity()}</Label>
<span className="font-mono text-[11px] text-muted-foreground">
{Math.round(selectedBlock.opacity * 100)}%
</span>
</div>
<Slider
min={0}
max={1}
step={0.01}
value={[selectedBlock.opacity]}
onValueChange={([val]) =>
handleUpdateBlock(selectedBlock.id, { opacity: val })
}
/>
</div>
{/* Rotation Control */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.rotation()}</Label>
<span className="font-mono text-[11px] text-muted-foreground">
{selectedBlock.rotation}°
</span>
</div>
<Slider
min={-180}
max={180}
step={1}
value={[selectedBlock.rotation]}
onValueChange={([val]) =>
handleUpdateBlock(selectedBlock.id, { rotation: val })
}
/>
<div className="flex items-center gap-1.5 pt-1">
{[-45, -30, 0, 30, 45].map((deg) => (
<Button
key={deg}
variant="outline"
size="sm"
className="h-6 text-[10px] flex-1 px-1 font-mono"
onClick={() => handleUpdateBlock(selectedBlock.id, { rotation: deg })}
>
{deg}°
</Button>
))}
</div>
</div>
{/* Position X Control */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.position_x()}</Label>
<span className="font-mono text-[11px] text-muted-foreground">
{Math.round(selectedBlock.x * 100)}%
</span>
</div>
<Slider
min={0}
max={1}
step={0.01}
value={[selectedBlock.x]}
onValueChange={([val]) => handleUpdateBlock(selectedBlock.id, { x: val })}
/>
</div>
{/* Position Y Control */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.position_y()}</Label>
<span className="font-mono text-[11px] text-muted-foreground">
{Math.round(selectedBlock.y * 100)}%
</span>
</div>
<Slider
min={0}
max={1}
step={0.01}
value={[selectedBlock.y]}
onValueChange={([val]) => handleUpdateBlock(selectedBlock.id, { y: val })}
/>
</div>
</div>
) : (
<div className="py-12 text-center text-xs text-muted-foreground space-y-3">
<p>{m.select_block_to_edit()}</p>
<Button size="sm" variant="outline" onClick={handleAddTextBlock}>
<Plus className="h-3.5 w-3.5 mr-1" />
{m.add_text_block()}
</Button>
</div>
)}
</ScrollArea>
</div>
</div>
</DialogContent>
</Dialog>
{/* Save Template Mini Modal */}
<Dialog open={isSaveTemplateOpen} onOpenChange={setIsSaveTemplateOpen}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="text-sm font-semibold">
{saveTemplateMode === 'new'
? m.create_new_template()
: m.overwrite_existing_template()}
</DialogTitle>
</DialogHeader>
<div className="py-3 space-y-4 text-xs">
{saveTemplateMode === 'new' ? (
<div className="space-y-2">
<Label>{m.template_name()}</Label>
<Input
type="text"
value={templateName}
onChange={(e) => setTemplateName(e.target.value)}
placeholder={m.enter_template_name()}
className="text-xs"
/>
</div>
) : (
<div className="space-y-2">
<Label>{m.select_template_to_overwrite()}</Label>
<select
value={targetOverwriteTemplateId || ''}
onChange={(e) => setTargetOverwriteTemplateId(e.target.value)}
className="w-full h-9 rounded-md border border-input bg-background px-3 text-xs"
>
{templates.map((t) => (
<option key={t.id} value={t.id}>
{t.name}
</option>
))}
</select>
</div>
)}
</div>
<DialogFooter>
<Button
variant="outline"
size="sm"
className="text-xs"
onClick={() => setIsSaveTemplateOpen(false)}
>
{m.cancel()}
</Button>
<Button
size="sm"
className="text-xs"
disabled={isCreatingTemplate || isUpdatingTemplate}
onClick={handleConfirmSaveTemplate}
>
{m.confirm()}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
)
}
function cn(...classes: (string | boolean | undefined | null)[]) {
return classes.filter(Boolean).join(' ')
}