Files
shumai/packages/webui/components/share-settings-sidebar.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

444 lines
16 KiB
TypeScript

import { client } from '@/ui/api/client'
import { DateTimePicker } from '@/ui/components/datetime-picker'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { Switch } from '@/ui/components/ui/switch'
import { WatermarkEditorDialog } from '@/ui/components/watermark-editor-dialog'
import { copyToClipboard as copyTextToClipboard } from '@/ui/lib/clipboard'
import { m } from '@/ui/paraglide/messages.js'
import {
ShareLinkInfo,
UpdateShareLinkRequest,
type FieldInfo as MetadataFieldInfo,
} from '@shumai/dtos'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
ArrowDownUp,
ChevronRight,
Copy,
ExternalLink,
LayoutGrid,
List,
ListFilter,
Loader2,
Palette,
Shield,
SortAsc,
} from 'lucide-react'
import React, { useState } from 'react'
import { toast } from 'sonner'
interface ShareSettingsSidebarProps {
shareLink: ShareLinkInfo
viewMode: 'card' | 'list'
onViewModeChange: (mode: 'card' | 'list') => void
defaultSortOrder: string | null
onSortOrderChange: (sortOrder: string | null) => void
}
export function ShareSettingsSidebar({
shareLink,
viewMode,
onViewModeChange,
defaultSortOrder,
onSortOrderChange,
}: ShareSettingsSidebarProps) {
const queryClient = useQueryClient()
const [password, setPassword] = useState(shareLink.password || '')
const [expireAt, setExpireAt] = useState<Date | undefined>(
shareLink.expireAt ? new Date(shareLink.expireAt) : undefined,
)
const [isWatermarkEditorOpen, setIsWatermarkEditorOpen] = useState(false)
React.useEffect(() => {
setPassword(shareLink.password || '')
}, [shareLink.password])
const [isPasswordEnabled, setIsPasswordEnabled] = useState(shareLink.hasPassword)
const [isExpireEnabled, setIsExpireEnabled] = useState(!!shareLink.expireAt)
const { data: watermarkInfo, refetch: refetchWatermark } = useQuery({
queryKey: ['share-watermark', shareLink.id],
queryFn: async () => {
const res = await client.api.shares[':shareId'].watermark.$get({
param: { shareId: shareLink.id },
})
if (!res.ok) return null
return await res.json()
},
refetchInterval: (query) => {
const status = query.state.data?.watermarkStatus || shareLink.watermarkStatus
return status === 'processing' ? 3000 : false
},
})
const $updateWatermark = client.api.shares[':shareId'].watermark.$put
const { mutate: disableWatermark } = useMutation({
mutationFn: async () => {
const res = await $updateWatermark({
param: { shareId: shareLink.id },
json: { enabled: false },
})
if (!res.ok) throw new Error(m.failed_update())
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
queryClient.invalidateQueries({ queryKey: ['share-watermark', shareLink.id] })
toast.success(m.watermark_disabled_msg())
},
})
const watermarkStatus =
watermarkInfo?.watermarkStatus ??
shareLink.watermarkStatus ??
(shareLink.watermarkConfigId ? 'ready' : 'disabled')
const watermarkConfig =
watermarkInfo?.watermarkConfig?.config ?? shareLink.watermarkConfig?.config ?? null
const isWatermarkEnabled = watermarkConfig !== null && watermarkStatus !== 'disabled'
const { data: fields } = useQuery({
queryKey: ['fields', shareLink.projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].fields.$get({
param: { projectId: shareLink.projectId },
})
if (!res.ok) throw new Error(m.failed_fetch_fields())
return await res.json()
},
enabled: !!shareLink.projectId,
})
const $updateShare = client.api.shares[':shareId'].$put
const { mutate: updateShare } = useMutation({
mutationFn: async (json: UpdateShareLinkRequest) => {
const res = await $updateShare({
param: { shareId: shareLink.id },
json,
})
if (!res.ok) throw new Error(m.failed_update())
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
toast.success(m.settings_updated())
},
})
const shareUrl = `${window.location.origin}/share/${shareLink.id}`
const copyToClipboard = async (text: string) => {
const ok = await copyTextToClipboard(text)
if (ok) {
toast.success(m.copied_to_clipboard())
}
}
const toggleFieldVisibility = (fieldId: string) => {
const current = shareLink.fieldVisibility || {}
const next = { ...current, [fieldId]: !current[fieldId] }
updateShare({ fieldVisibility: next })
}
// Parse current sort field and order
let currentSortField = 'index'
let currentSortOrder = 'asc'
if (defaultSortOrder) {
const parts = defaultSortOrder.split(':')
currentSortField = parts[0]
currentSortOrder = parts[1] || 'asc'
}
return (
<div className="flex flex-col h-full bg-background border-l border-border">
<div className="flex-1 overflow-y-auto">
<div className="p-4 space-y-6">
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium">{m.link_visibility()}</h3>
<Switch
checked={!shareLink.isDisabled}
onCheckedChange={(checked) => updateShare({ isDisabled: !checked })}
/>
</div>
<div className="relative w-full">
<Input value={shareUrl} readOnly className="pr-10 bg-muted/50 text-xs" />
<Button
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full"
onClick={() => copyToClipboard(shareUrl)}
>
<Copy className="h-4 w-4" />
</Button>
</div>
</div>
<div className="space-y-1">
<SidebarAccordionItem title={m.security()} icon={<Shield className="h-4 w-4" />}>
<div className="p-3 space-y-4 pt-0">
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.password()}</Label>
<Switch
checked={isPasswordEnabled}
onCheckedChange={(checked) => {
setIsPasswordEnabled(checked)
if (!checked) updateShare({ password: null })
}}
/>
</div>
{isPasswordEnabled && (
<div className="flex gap-2 animate-in fade-in slide-in-from-top-1 duration-200">
<Input
type="text"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={m.enter_password()}
className="text-xs"
/>
<Button size="sm" onClick={() => updateShare({ password })}>
{m.save()}
</Button>
</div>
)}
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.expiration_date()}</Label>
<Switch
checked={isExpireEnabled}
onCheckedChange={(checked) => {
setIsExpireEnabled(checked)
if (!checked) {
setExpireAt(undefined)
updateShare({ expireAt: null })
}
}}
/>
</div>
{isExpireEnabled && (
<div className="animate-in fade-in slide-in-from-top-1 duration-200">
<DateTimePicker
value={expireAt}
onChange={(date) => {
setExpireAt(date)
updateShare({ expireAt: date ? date.toISOString() : null })
}}
className="text-xs"
/>
</div>
)}
</div>
<div className="space-y-2 pt-2 border-t border-border/50">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.watermark()}</Label>
<Switch
checked={isWatermarkEnabled}
disabled={watermarkStatus === 'processing'}
onCheckedChange={(checked) => {
if (!checked) {
disableWatermark()
} else {
setIsWatermarkEditorOpen(true)
}
}}
/>
</div>
{isWatermarkEnabled && watermarkStatus === 'processing' && (
<div className="flex items-center gap-2 text-xs text-amber-600 dark:text-amber-400 font-medium py-1 animate-pulse">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
<span>{m.watermark_transcoding_processing()}</span>
</div>
)}
{isWatermarkEnabled && watermarkStatus !== 'processing' && (
<Button
variant="outline"
size="sm"
className="w-full text-xs gap-1.5 mt-1"
onClick={() => setIsWatermarkEditorOpen(true)}
>
{m.edit_watermark()}
</Button>
)}
</div>
</div>
</SidebarAccordionItem>
<SidebarAccordionItem title={m.appearance()} icon={<Palette className="h-4 w-4" />}>
<div className="p-3 space-y-3 pt-0 flex gap-2">
<Button
variant={viewMode === 'card' ? 'secondary' : 'outline'}
size="sm"
className="flex-1 gap-2 text-xs"
onClick={() => onViewModeChange('card')}
>
<LayoutGrid className="h-4 w-4" />
{m.grid()}
</Button>
<Button
variant={viewMode === 'list' ? 'secondary' : 'outline'}
size="sm"
className="flex-1 gap-2 text-xs"
onClick={() => onViewModeChange('list')}
>
<List className="h-4 w-4" />
{m.list()}
</Button>
</div>
</SidebarAccordionItem>
<SidebarAccordionItem title={m.fields()} icon={<ListFilter className="h-4 w-4" />}>
<div className="p-3 space-y-3 pt-0">
{(fields as MetadataFieldInfo[])?.map((field) => (
<div key={field.id} className="flex items-center justify-between">
<Label className="text-xs">{field.config?.name}</Label>
<Switch
checked={shareLink.fieldVisibility?.[field.id] ?? false}
onCheckedChange={() => toggleFieldVisibility(field.id)}
/>
</div>
))}
</div>
</SidebarAccordionItem>
<SidebarAccordionItem title={m.sort_by()} icon={<SortAsc className="h-4 w-4" />}>
<div className="p-3 space-y-4 pt-0">
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">{m.field()}</Label>
<Select
value={currentSortField}
onValueChange={(val) => {
if (val === 'index') {
onSortOrderChange(null)
} else {
onSortOrderChange(`${val}:${currentSortOrder}`)
}
}}
>
<SelectTrigger className="w-full text-xs h-9">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="index">{m.sort_custom()}</SelectItem>
<SelectItem value="name">{m.sort_name()}</SelectItem>
<SelectItem value="createdAt">{m.sort_date_created()}</SelectItem>
<SelectItem value="size">{m.sort_size()}</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">{m.order()}</Label>
<Button
variant="outline"
className="w-full justify-between font-normal text-xs h-9"
disabled={currentSortField === 'index'}
onClick={() => {
const nextOrder = currentSortOrder === 'asc' ? 'desc' : 'asc'
onSortOrderChange(`${currentSortField}:${nextOrder}`)
}}
>
<span>
{currentSortField === 'name'
? currentSortOrder === 'asc'
? m.sort_a_to_z()
: m.sort_z_to_a()
: currentSortField === 'createdAt'
? currentSortOrder === 'asc'
? m.sort_oldest_to_newest()
: m.sort_newest_to_oldest()
: currentSortField === 'size'
? currentSortOrder === 'asc'
? m.sort_smallest_to_largest()
: m.sort_largest_to_smallest()
: currentSortOrder === 'asc'
? m.ascending()
: m.descending()}
</span>
<ArrowDownUp className="h-4 w-4 opacity-50" />
</Button>
</div>
</div>
</SidebarAccordionItem>
</div>
</div>
</div>
<div className="p-4 border-t border-border space-y-2">
<Button
variant="outline"
className="w-full justify-center"
onClick={() => window.open(shareUrl, '_blank')}
>
<ExternalLink className="h-4 w-4 mr-2" />
{m.open_share_link()}
</Button>
<Button
className="w-full justify-center bg-blue-600 hover:bg-blue-700 text-white"
onClick={() => copyToClipboard(shareUrl)}
>
<Copy className="h-4 w-4 mr-2" />
{m.copy_link()}
</Button>
</div>
<WatermarkEditorDialog
open={isWatermarkEditorOpen}
onOpenChange={setIsWatermarkEditorOpen}
initialConfig={watermarkConfig}
shareId={shareLink.id}
onSaveSuccess={() => {
refetchWatermark()
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
}}
/>
</div>
)
}
function SidebarAccordionItem({
title,
icon,
children,
}: {
title: string
icon: React.ReactNode
children?: React.ReactNode
}) {
const [isOpen, setIsOpen] = useState(false)
return (
<div className="border-b border-border last:border-0">
<button
onClick={() => setIsOpen(!isOpen)}
className="w-full flex items-center justify-between py-3 px-2 hover:bg-muted/50 transition-colors"
>
<div className="flex items-center gap-3">
{icon}
<span className="text-sm font-medium">{title}</span>
</div>
<ChevronRight className={cn('h-4 w-4 transition-transform', isOpen && 'rotate-90')} />
</button>
{isOpen && children && (
<div className="animate-in fade-in slide-in-from-top-1 duration-200">{children}</div>
)}
</div>
)
}
function cn(...classes: (string | boolean | undefined | null)[]) {
return classes.filter(Boolean).join(' ')
}