import { Button } from '@components/common/ui/Button.js'; import { Input } from '@components/common/ui/Input.js'; import { toast } from '@components/common/ui/Sonner.js'; import { _ } from '@evershop/evershop/lib/locale/translate/_'; import { matchesAccept } from '@evershop/evershop/lib/util/mimeMatch'; import { clipboardStamp, pastedFileName } from '@evershop/evershop/lib/util/pastedFileName'; import { Check, Copy, X } from 'lucide-react'; import React from 'react'; import { createPortal } from 'react-dom'; import './FileBrowser.scss'; import { useQuery } from 'urql'; /** * How many just-uploaded files to keep in the panel. It is its own surface * now and scrolls, so this is about staying a record of "what I just added" * rather than becoming a second listing. */ const MAX_RECENT_UPLOADS = 9; const GetApisQuery = ` query Query ($filters: [FilterInput!]) { setting { uploadAllowedMimeTypesEffective } browserApi: url(routeId: "fileBrowser", params: [{key: "0", value: ""}]) deleteApi: url(routeId: "fileDelete", params: [{key: "0", value: ""}]) renameApi: url(routeId: "fileRename", params: [{key: "0", value: ""}]) # "fileUpload", not "imageUpload". The two routes share a handler and the # same multer filter (the admin's allowed types); "imageUpload" adds one # extra middleware that rejects anything whose mimetype does not start # with "image", unconditionally. Posting here meant enabling PDF or video # in System Setting had no effect — the upload was refused by a rule that # never consulted the setting. "imageUpload" still exists and is still # correct for ImageUploader, which genuinely only wants images. uploadApi: url(routeId: "fileUpload", params: [{key: "0", value: ""}]) folderCreateApi: url(routeId: "folderCreate") } `; export interface File { name: string; url: string; size?: number; mimeType?: string; } /** 1.4 MB, 812 KB, 96 B. Absent size renders as nothing, never as "0 B". */ function formatBytes(bytes: number | undefined): string | undefined { if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes < 0) { return undefined; } if (bytes < 1024) { return `${bytes} B`; } const units = ['KB', 'MB', 'GB', 'TB']; let value = bytes / 1024; let unit = 0; while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit += 1; } return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`; } /** The badge drawn instead of a thumbnail: "PDF", "DOCX", "ZIP". */ function extensionOf(name: string): string { const dot = name.lastIndexOf('.'); return dot > 0 ? name.slice(dot + 1).toUpperCase() : '?'; } /** * A file name that becomes an input when clicked. * * Used by both the grid and the just-uploaded panel, so a rename works * wherever the name is visible. Clicking the NAME edits it and clicking the * PICTURE selects or uses the file — two targets, two meanings, no modal. */ const EditableName: React.FC<{ name: string; className: string; onRename: (next: string) => Promise | void; }> = ({ name, className, onRename }) => { // The extension is split off and NOT put in the input. // // It is what every consumer uses to decide what the file is — the grid picks // a thumbnail from it, the media type is derived from it, the storefront // serves by it. An editable extension lets a rename silently retype or // untype the file; shown as a fixed suffix, there is nothing to get wrong. // The API refuses a changed extension as well, because it is reachable on // its own. const dot = name.lastIndexOf('.'); const stem = dot > 0 ? name.slice(0, dot) : name; const extension = dot > 0 ? name.slice(dot) : ''; const [editing, setEditing] = React.useState(false); const [draft, setDraft] = React.useState(stem); const inputRef = React.useRef(null); // A rename elsewhere, or a different file taking this slot, must not leave // a stale draft behind. React.useEffect(() => { setDraft(stem); setEditing(false); }, [name, stem]); React.useEffect(() => { if (editing) { inputRef.current?.focus(); inputRef.current?.select(); } }, [editing]); const commit = async () => { const next = draft.trim(); setEditing(false); if (next && next !== stem) { // Send the whole name; the service would re-attach the extension anyway, // but sending a partial name would make the API's contract depend on who // is calling it. await onRename(`${next}${extension}`); } }; if (!editing) { return ( ); } return (
setDraft(e.target.value)} onClick={(e) => e.stopPropagation()} onKeyDown={(e) => { // Enter and Escape, because a text field that ignores them feels // broken however many buttons sit beside it. if (e.key === 'Enter') { e.preventDefault(); commit(); } else if (e.key === 'Escape') { e.preventDefault(); setDraft(stem); setEditing(false); } }} /> {extension && ( )}
); }; const File: React.FC<{ file: File; /** True when this file's details panel is open, so the panel's subject is * obvious when the grid runs long. */ active: boolean; /** * False when this type cannot be INSERTED by the caller — drawn dimmed. It * can still be opened: the details panel is also where a file is deleted, * and an image picker must not make a stray PDF unremovable. */ insertable?: boolean; openInfo: (file: File) => void; rename: (file: File, newName: string) => Promise | void; }> = ({ file, active, insertable = true, openInfo, rename }) => { const className = [active ? 'active' : '', insertable ? '' : 'not-insertable'] .filter(Boolean) .join(' '); // A file can be an image by extension and still fail to load — truncated // upload, a `.png` that is not one. Fall back to the badge rather than // leaving a broken image in the grid. const [previewFailed, setPreviewFailed] = React.useState(false); const showPreview = !previewFailed && (file.mimeType ?? '').startsWith('image/'); return (
{/* A button, not a link. This opens a panel beside the grid; it does not navigate, and the old `` both announced itself as a link and needed its default suppressed on every click. */}
{/* The name, with its extension — the thing you are actually looking for when scanning a folder, and the way to rename it. */} rename(file, next)} />
); }; /** * Details for one file, sliding in beside the grid. * * This replaces a card that was revealed on hover and drawn INSIDE the * thumbnail. Once the cells were made smaller there was no room in them for a * name, a type, a size, a pixel count and a full URL, so the card covered the * picture it was describing and still truncated. Out of the cell the same * information is legible at any grid density, and it becomes the natural home * for the actions that act on one file. * * Mount it with a `key` of the file name. Each file then gets a fresh * instance, so a measured pixel size or a copied-URL flash cannot carry over * from the file looked at before. */ const FileInfoPanel: React.FC<{ file: File; baseUrl?: string; /** Whether the caller can accept this type — wording only, see below. */ insertable: boolean; /** Absent when the browser was opened to manage files rather than pick one; * the insert action is then not offered at all. */ onInsert?: (file: File) => void; onDelete: (file: File) => void; onClose: () => void; }> = ({ file, baseUrl, insertable, onInsert, onDelete, onClose }) => { // Measured from the rendered preview, never from the server: no listing API // on any storage provider reports dimensions, and reading each file's header // would be one request per image. The browser has to fetch the picture to // draw it here anyway, so the numbers are free. const [dimensions, setDimensions] = React.useState(''); const [previewFailed, setPreviewFailed] = React.useState(false); const [copied, setCopied] = React.useState(false); const panelRef = React.useRef(null); const showPreview = !previewFailed && (file.mimeType ?? '').startsWith('image/'); const size = formatBytes(file.size); // The stored URL stays as the provider gave it — relative for local disk // (`/assets/...`), absolute for S3/Azure/GCS — because that is what gets // inserted into content, and a relative path has to stay relative to survive // the store changing domain. Only the DISPLAYED and COPIED value is // resolved, which is what is useful outside this screen. // // Resolved against the STORE's base URL, which the API sends, not against // `window.location.origin`: the admin can be reached on a different origin // from the storefront — behind a proxy, by IP, or on a separate admin host — // and the origin would then produce a URL that does not serve the file. The // origin is only the fallback for a response without the field. const absoluteUrl = React.useMemo(() => { try { return new URL(file.url, baseUrl || window.location.origin).href; } catch { return file.url; } }, [file.url, baseUrl]); const copyUrl = async () => { try { await navigator.clipboard.writeText(absoluteUrl); setCopied(true); window.setTimeout(() => setCopied(false), 1500); } catch { // Clipboard access needs a secure context and can be refused outright. // The URL is still on screen to select by hand, so a failure here is not // worth an error banner. setCopied(false); } }; // Escape closes the panel rather than the whole browser: the panel is the // innermost thing open, and dismissing the browser out from under someone // who meant to close a side panel loses their place in the folder. React.useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.stopPropagation(); onClose(); } }; document.addEventListener('keydown', onKey, true); return () => document.removeEventListener('keydown', onKey, true); }, [onClose]); // Clicking away closes it, so the X is a convenience rather than the only // way out. // // A thumbnail is the one exception. Without it, moving from one file to the // next would cost two clicks — one to dismiss, one to open — and which of // the two handlers ran first would decide whether the second click even // landed. Skipping the grid entirely leaves the tile's own handler to swap // the subject, and makes the behaviour independent of listener order. // // `mousedown`, not `click`: it matches how every other dismissable layer // feels, and it cannot be lost to the target being re-rendered away between // press and release. React.useEffect(() => { const onPointerDown = (e: MouseEvent) => { const target = e.target as Element | null; if (!target) return; if (panelRef.current?.contains(target)) return; if (target.closest?.('.image-item')) return; onClose(); }; document.addEventListener('mousedown', onPointerDown); return () => document.removeEventListener('mousedown', onPointerDown); }, [onClose]); return ( ); }; /** * Placeholder tiles shown while a folder is being fetched. * * A spinner says "something is happening"; this says what is coming and where * it will be. Because the tiles are the same shape as real ones, the grid does * not jump when they are replaced — the layout is already correct before the * data arrives, which a centred spinner cannot manage. */ const FileGridSkeleton: React.FC<{ count?: number }> = ({ count = 18 }) => (