'use client' import React, { useEffect, useState } from 'react' import { toast, useField } from '@payloadcms/ui' import { formatBytes, MediaCard } from './media-ui/MediaCard' type Resolved = { url: string previewUrl: string localPath: string | null where: string exists: boolean size: number | null remote: boolean } const MIME_BY_EXT: Record = { jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', gif: 'image/gif', svg: 'image/svg+xml', avif: 'image/avif', mp4: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', } function guessMime(url: string) { const ext = url.split(/[?#]/)[0].split('.').pop()?.toLowerCase() || '' return MIME_BY_EXT[ext] || 'image/jpeg' } /** * Shown under legacy "URL фото" fields: preview of the linked file, where it really lives * (apps/web/public/... or the remote address) and a button that moves it into the media library * so it gets the normal preview and editor. */ export function LegacyUrlPreview({ path, field, }: { path: string field?: { admin?: { custom?: { uploadField?: string } } } }) { const { value, setValue } = useField({ path }) const uploadName = field?.admin?.custom?.uploadField const uploadPath = uploadName ? path.replace(/[^.]+$/, uploadName) : '' const upload = useField({ path: uploadPath || path }) const [resolved, setResolved] = useState(null) const [error, setError] = useState('') const [busy, setBusy] = useState(false) useEffect(() => { const url = (value || '').trim() setResolved(null) setError('') if (!url) return const timer = setTimeout(async () => { const res = await fetch(`/api/custom/media-tools/resolve-url?url=${encodeURIComponent(url)}`, { credentials: 'include', }) const data = await res.json().catch(() => ({})) if (res.ok) setResolved(data as Resolved) else setError(data.error || 'Не удалось разобрать ссылку') }, 300) return () => clearTimeout(timer) }, [value]) if (!value) return null if (error) return

{error}

if (!resolved) return null const where = resolved.remote ? 'Внешняя ссылка' : resolved.exists ? 'Где лежит файл' : 'Файл не найден' return ( { setBusy(true) try { const res = await fetch('/api/custom/media-tools/import-url', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url: resolved.url }), }) const data = await res.json().catch(() => ({})) if (!res.ok) throw new Error(data.error || 'Не удалось перенести файл') upload.setValue(data.doc.id) setValue('') toast.success('Файл перенесён в медиатеку. Сохраните документ.') } catch (e) { toast.error(e instanceof Error ? e.message : 'Ошибка') } finally { setBusy(false) } }} > Перенести в медиатеку ) : null } notice={
{where} {resolved.remote ? resolved.url : resolved.localPath || resolved.where} {resolved.size ? {formatBytes(resolved.size)} : null} Это старая ссылка на файл. Чтобы обрезать фото или поменять точку фокуса, перенесите его в медиатеку.
} /> ) }