346 lines
11 KiB
TypeScript
346 lines
11 KiB
TypeScript
import * as React from "react"
|
||
import {
|
||
ChevronLeftIcon,
|
||
ChevronRightIcon,
|
||
DownloadIcon,
|
||
FileArchiveIcon,
|
||
FileIcon,
|
||
FileTextIcon,
|
||
ImageIcon,
|
||
XIcon,
|
||
} from "lucide-react"
|
||
|
||
import { cn } from "../lib/utils"
|
||
import { formatBytes } from "../lib/format"
|
||
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "../ui/dialog"
|
||
|
||
export interface FileItem {
|
||
readonly name: string
|
||
/** Размер в байтах. */
|
||
readonly size: number
|
||
readonly type?: string
|
||
/** Ссылка на файл; без неё — только карточка без просмотра. */
|
||
readonly src?: string
|
||
readonly description?: string
|
||
}
|
||
|
||
export type FileGallerySize = "sm" | "md" | "lg"
|
||
|
||
export function isImageFile(file: FileItem) {
|
||
return Boolean(file.type?.startsWith("image/")) || /\.(jpe?g|png|gif|webp|bmp)$/i.test(file.name)
|
||
}
|
||
|
||
export function isPdfFile(file: FileItem) {
|
||
return Boolean(file.type?.includes("pdf")) || /\.pdf$/i.test(file.name)
|
||
}
|
||
|
||
export function fileIcon(file: FileItem) {
|
||
if (isImageFile(file)) return ImageIcon
|
||
if (isPdfFile(file)) return FileTextIcon
|
||
if (/\.(zip|rar|7z)$/i.test(file.name)) return FileArchiveIcon
|
||
return FileIcon
|
||
}
|
||
|
||
function extension(file: FileItem) {
|
||
return file.name.split(".").pop()?.toUpperCase() ?? ""
|
||
}
|
||
|
||
const tileSize: Record<FileGallerySize, string> = {
|
||
sm: "w-24",
|
||
md: "w-32",
|
||
lg: "w-44",
|
||
}
|
||
|
||
/**
|
||
* Список файлов плитками. Клик по изображению — лайтбокс со стрелками,
|
||
* по PDF — встроенный просмотрщик, остальное — скачивание.
|
||
*/
|
||
export function FileGallery({
|
||
files,
|
||
size = "md",
|
||
onRemove,
|
||
className,
|
||
}: {
|
||
files: readonly FileItem[]
|
||
size?: FileGallerySize
|
||
/** Показать крестик «убрать» на плитке (вложения в форме). */
|
||
onRemove?: (file: FileItem, index: number) => void
|
||
className?: string
|
||
}) {
|
||
const [openIndex, setOpenIndex] = React.useState<number | null>(null)
|
||
const open = (file: FileItem, index: number) => openFile(file, () => setOpenIndex(index))
|
||
|
||
return (
|
||
<>
|
||
<ul className={cn("flex flex-wrap gap-3", className)}>
|
||
{files.map((file, index) => (
|
||
<li key={file.name} className={cn("group", tileSize[size])}>
|
||
<FileTile
|
||
file={file}
|
||
size={size}
|
||
onOpen={() => open(file, index)}
|
||
onRemove={onRemove && (() => onRemove(file, index))}
|
||
/>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
|
||
<FileViewer files={files} openIndex={openIndex} onOpenIndexChange={setOpenIndex} />
|
||
</>
|
||
)
|
||
}
|
||
|
||
/** Открыть файл: изображение и PDF — во встроенном просмотрщике (preview), остальное — в новой вкладке. */
|
||
export function openFile(file: FileItem, preview: () => void) {
|
||
if (!file.src) return
|
||
if (isImageFile(file) || isPdfFile(file)) preview()
|
||
else window.open(file.src, "_blank", "noopener")
|
||
}
|
||
|
||
/**
|
||
* Просмотрщик для набора файлов: лайтбокс со стрелками для изображений, окно для PDF.
|
||
* Для своих раскладок файлов (вложения в чате и т. п.), когда плитки FileGallery не подходят.
|
||
*/
|
||
export function FileViewer({
|
||
files,
|
||
openIndex,
|
||
onOpenIndexChange,
|
||
}: {
|
||
files: readonly FileItem[]
|
||
openIndex: number | null
|
||
onOpenIndexChange: (index: number | null) => void
|
||
}) {
|
||
const images = files.filter((f) => isImageFile(f) && f.src)
|
||
const opened = openIndex === null ? null : files[openIndex]
|
||
if (!opened) return null
|
||
if (isImageFile(opened)) {
|
||
return (
|
||
<ImageLightbox
|
||
images={images}
|
||
index={Math.max(0, images.indexOf(opened))}
|
||
onIndexChange={(i) => onOpenIndexChange(files.indexOf(images[i]))}
|
||
onClose={() => onOpenIndexChange(null)}
|
||
/>
|
||
)
|
||
}
|
||
if (isPdfFile(opened)) return <PdfPreview file={opened} onClose={() => onOpenIndexChange(null)} />
|
||
return null
|
||
}
|
||
|
||
function FileTile({
|
||
file,
|
||
size,
|
||
onOpen,
|
||
onRemove,
|
||
}: {
|
||
file: FileItem
|
||
size: FileGallerySize
|
||
onOpen: () => void
|
||
onRemove?: () => void
|
||
}) {
|
||
const [broken, setBroken] = React.useState(false)
|
||
const Icon = fileIcon(file)
|
||
const image = isImageFile(file) && file.src && !broken
|
||
const previewable = Boolean(file.src) && (isImageFile(file) || isPdfFile(file))
|
||
|
||
return (
|
||
<div className="relative flex flex-col gap-1.5">
|
||
{onRemove && (
|
||
<button
|
||
type="button"
|
||
aria-label={`Убрать ${file.name}`}
|
||
onClick={onRemove}
|
||
className="absolute top-1.5 right-1.5 z-10 grid size-6 place-items-center rounded-full bg-card/90 text-muted-foreground shadow-sm transition hover:text-destructive"
|
||
>
|
||
<XIcon className="size-3.5" />
|
||
</button>
|
||
)}
|
||
<button
|
||
type="button"
|
||
onClick={onOpen}
|
||
disabled={!file.src}
|
||
className={cn(
|
||
"relative aspect-square w-full overflow-hidden rounded-xl bg-muted transition outline-none focus-visible:ring-2 focus-visible:ring-ring/60",
|
||
previewable && "cursor-zoom-in hover:ring-2 hover:ring-primary/30",
|
||
!file.src && "cursor-default",
|
||
)}
|
||
>
|
||
{image ? (
|
||
<img
|
||
src={file.src}
|
||
alt={file.description ?? file.name}
|
||
loading="lazy"
|
||
onError={() => setBroken(true)}
|
||
className="size-full object-cover transition duration-300 group-hover:scale-105"
|
||
/>
|
||
) : (
|
||
<span className="grid size-full place-items-center text-muted-foreground">
|
||
<span className="flex flex-col items-center gap-1.5">
|
||
<Icon className={cn(size === "sm" ? "size-5" : "size-7")} />
|
||
<span className="text-[10px] font-semibold tracking-wider">{extension(file)}</span>
|
||
</span>
|
||
</span>
|
||
)}
|
||
</button>
|
||
<div className="min-w-0 px-0.5">
|
||
{file.description && size !== "sm" && (
|
||
<div className="truncate text-xs font-medium" title={file.description}>
|
||
{file.description}
|
||
</div>
|
||
)}
|
||
<div className="truncate text-xs text-muted-foreground" title={file.name}>
|
||
{file.name}
|
||
</div>
|
||
<div className="mt-0.5 flex items-center justify-between text-[11px] text-muted-foreground tabular">
|
||
{formatBytes(file.size)}
|
||
{file.src && (
|
||
<a
|
||
href={file.src}
|
||
download={file.name}
|
||
target="_blank"
|
||
rel="noopener"
|
||
aria-label={`Скачать ${file.name}`}
|
||
className="rounded p-0.5 text-primary transition hover:bg-accent"
|
||
>
|
||
<DownloadIcon className="size-3.5" />
|
||
</a>
|
||
)}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
function ImageLightbox({
|
||
images,
|
||
index,
|
||
onIndexChange,
|
||
onClose,
|
||
}: {
|
||
images: readonly FileItem[]
|
||
index: number
|
||
onIndexChange: (index: number) => void
|
||
onClose: () => void
|
||
}) {
|
||
const file = images[index]
|
||
const go = React.useCallback(
|
||
(delta: number) => onIndexChange((index + delta + images.length) % images.length),
|
||
[index, images.length, onIndexChange],
|
||
)
|
||
|
||
React.useEffect(() => {
|
||
const onKey = (e: KeyboardEvent) => {
|
||
if (e.key === "ArrowRight") go(1)
|
||
if (e.key === "ArrowLeft") go(-1)
|
||
}
|
||
window.addEventListener("keydown", onKey)
|
||
return () => window.removeEventListener("keydown", onKey)
|
||
}, [go])
|
||
|
||
return (
|
||
<Dialog open onOpenChange={(v) => !v && onClose()}>
|
||
<DialogContent
|
||
showCloseButton={false}
|
||
className="max-w-[min(92vw,1100px)] gap-0 overflow-hidden border-0 bg-black/95 p-0 text-white sm:max-w-[min(92vw,1100px)]"
|
||
>
|
||
<DialogTitle className="sr-only">{file.description ?? file.name}</DialogTitle>
|
||
<DialogDescription className="sr-only">Просмотр изображения</DialogDescription>
|
||
<div className="relative grid min-h-[50vh] place-items-center">
|
||
<img src={file.src} alt={file.description ?? file.name} className="max-h-[80vh] w-auto object-contain" />
|
||
{images.length > 1 && (
|
||
<>
|
||
<LightboxButton side="left" label="Предыдущее" onClick={() => go(-1)}>
|
||
<ChevronLeftIcon />
|
||
</LightboxButton>
|
||
<LightboxButton side="right" label="Следующее" onClick={() => go(1)}>
|
||
<ChevronRightIcon />
|
||
</LightboxButton>
|
||
</>
|
||
)}
|
||
</div>
|
||
<div className="flex items-center gap-3 border-t border-white/10 px-4 py-3 text-sm">
|
||
<div className="min-w-0 flex-1">
|
||
<div className="truncate font-medium">{file.description ?? file.name}</div>
|
||
<div className="text-xs text-white/60">
|
||
{file.name} · {formatBytes(file.size)}
|
||
{images.length > 1 && ` · ${index + 1} из ${images.length}`}
|
||
</div>
|
||
</div>
|
||
<a
|
||
href={file.src}
|
||
download={file.name}
|
||
target="_blank"
|
||
rel="noopener"
|
||
className="grid size-8 place-items-center rounded-lg hover:bg-white/10"
|
||
aria-label="Скачать"
|
||
>
|
||
<DownloadIcon className="size-4" />
|
||
</a>
|
||
<button
|
||
type="button"
|
||
onClick={onClose}
|
||
className="grid size-8 place-items-center rounded-lg hover:bg-white/10"
|
||
aria-label="Закрыть"
|
||
>
|
||
<XIcon className="size-4" />
|
||
</button>
|
||
</div>
|
||
</DialogContent>
|
||
</Dialog>
|
||
)
|
||
}
|
||
|
||
function LightboxButton({
|
||
side,
|
||
label,
|
||
onClick,
|
||
children,
|
||
}: {
|
||
side: "left" | "right"
|
||
label: string
|
||
onClick: () => void
|
||
children: React.ReactNode
|
||
}) {
|
||
return (
|
||
<button
|
||
type="button"
|
||
aria-label={label}
|
||
onClick={onClick}
|
||
className={cn(
|
||
"absolute top-1/2 grid size-10 -translate-y-1/2 place-items-center rounded-full bg-white/10 backdrop-blur transition hover:bg-white/20 [&_svg]:size-5",
|
||
side === "left" ? "left-3" : "right-3",
|
||
)}
|
||
>
|
||
{children}
|
||
</button>
|
||
)
|
||
}
|
||
|
||
function PdfPreview({ file, onClose }: { file: FileItem; onClose: () => void }) {
|
||
return (
|
||
<Dialog open onOpenChange={(v) => !v && onClose()}>
|
||
<DialogContent className="flex h-[88vh] max-w-[min(92vw,1000px)] flex-col gap-0 p-0 sm:max-w-[min(92vw,1000px)]">
|
||
<div className="flex items-center gap-3 border-b px-4 py-3 pr-12">
|
||
<FileTextIcon className="size-4 text-primary" />
|
||
<div className="min-w-0 flex-1">
|
||
<DialogTitle className="truncate text-sm">{file.description ?? file.name}</DialogTitle>
|
||
<DialogDescription className="text-xs">
|
||
{file.name} · {formatBytes(file.size)}
|
||
</DialogDescription>
|
||
</div>
|
||
<a
|
||
href={file.src}
|
||
download={file.name}
|
||
target="_blank"
|
||
rel="noopener"
|
||
className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-sm text-primary hover:bg-accent"
|
||
>
|
||
<DownloadIcon className="size-4" /> Скачать
|
||
</a>
|
||
</div>
|
||
<iframe src={file.src} title={file.name} className="min-h-0 w-full flex-1 rounded-b-lg bg-muted" />
|
||
</DialogContent>
|
||
</Dialog>
|
||
)
|
||
}
|