AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
import { useCallback, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import Lightbox from "yet-another-react-lightbox";
import Zoom from "yet-another-react-lightbox/plugins/zoom";
import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
import "yet-another-react-lightbox/styles.css";
import "yet-another-react-lightbox/plugins/thumbnails.css";
import {
Paperclip,
HardDrive,
ExternalLink,
ChevronLeft,
Search,
Grid,
List,
X,
Loader2,
Trash2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { ButtonTooltip } from "@/components/ui/button-tooltip";
import { formatDateTime } from "@/lib/utils";
import { WORKSPACE_PAGE_TITLE_CLASSNAME } from "@/lib/workspace-ui";
import type { EdgeEverRepository } from "@/lib/repository";
import { isPdfAttachment, type ResourceListItem } from "@edgeever/shared";
import { PdfViewer } from "@/components/pdf/PdfViewer";
import { PdfThumbnail } from "@/components/pdf/PdfThumbnail";
import { AttachmentFileIcon } from "@/components/attachments/AttachmentFileIcon";
import { AppConfirmDialog } from "@/components/dialogs/ConfirmDialogs";
import { ExecutionCenterButton } from "@/components/execution/ExecutionCenterButton";
import { formatBytes } from "@/lib/format-bytes";
export { formatBytes } from "@/lib/format-bytes";
const DOCUMENT_MIME_TYPES = new Set([
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-powerpoint",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"text/plain",
"text/markdown",
"application/json",
"application/xml",
"text/html",
"text/css",
"text/javascript",
]);
interface AssetsPaneProps {
onClose: () => void;
repository: EdgeEverRepository;
onOpenExecutionCenter: () => void;
}
export const AssetsPane = ({ onClose, repository, onOpenExecutionCenter }: AssetsPaneProps) => {
const { t } = useTranslation();
const queryClient = useQueryClient();
// States
const [searchQuery, setSearchQuery] = useState("");
const [filterType, setFilterType] = useState<"all" | "image" | "document" | "other">("all");
const [layoutMode, setLayoutMode] = useState<"grid" | "list">(() => {
return (localStorage.getItem("assets_layout_mode") as "grid" | "list") || "grid";
});
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
const [pdfPreview, setPdfPreview] = useState<ResourceListItem | null>(null);
const [deleteTarget, setDeleteTarget] = useState<ResourceListItem | null>(null);
// Query resources
const resourcesQuery = useQuery({
queryKey: ["resources"],
queryFn: () => repository.listResources(),
});
const resources = resourcesQuery.data?.resources ?? [];
const summary = resourcesQuery.data?.summary ?? {
totalCount: 0,
totalBytes: 0,
imageCount: 0,
attachmentCount: 0,
};
const deleteMutation = useMutation({
mutationFn: (resourceId: string) => repository.deleteResource(resourceId),
onSuccess: async () => {
setDeleteTarget(null);
await queryClient.invalidateQueries({ queryKey: ["resources"] });
},
});
const requestResourceDelete = (resource: ResourceListItem) => {
deleteMutation.reset();
setDeleteTarget(resource);
};
// Filter Logic
const filteredResources = useMemo(() => {
return resources.filter((resource) => {
// 1. Kind/Type Filter
const isDoc = DOCUMENT_MIME_TYPES.has(resource.mimeType || "") || resource.kind === "attachment";
if (filterType === "image" && resource.kind !== "image") return false;
if (filterType === "document" && (!isDoc || resource.kind === "image")) return false;
if (filterType === "other" && (resource.kind === "image" || isDoc)) return false;
// 2. Search Text Query
if (searchQuery.trim()) {
const query = searchQuery.toLowerCase();
const filenameMatch = (resource.filename || "").toLowerCase().includes(query);
const memoTitleMatch = (resource.memoTitle || "").toLowerCase().includes(query);
const memoExcerptMatch = (resource.memoExcerpt || "").toLowerCase().includes(query);
return filenameMatch || memoTitleMatch || memoExcerptMatch;
}
return true;
});
}, [resources, filterType, searchQuery]);
// Lightbox slides
const imageResources = useMemo(() => {
return filteredResources.filter((r) => r.kind === "image");
}, [filteredResources]);
const pdfResources = useMemo(
() => filteredResources.filter((resource) => isPdfAttachment(resource.mimeType, resource.filename)),
[filteredResources],
);
const slides = useMemo(() => {
return imageResources.map((r) => ({
src: r.url,
alt: r.filename || "",
title: r.filename || "",
}));
}, [imageResources]);
const handleImageClick = (resourceId: string) => {
const idx = imageResources.findIndex((r) => r.id === resourceId);
if (idx !== -1) {
setLightboxIndex(idx);
}
};
const handleResourceOpen = (resource: ResourceListItem) => {
if (resource.kind === "image") {
handleImageClick(resource.id);
} else if (isPdfAttachment(resource.mimeType, resource.filename)) {
setPdfPreview(resource);
} else {
window.open(resource.url, "_blank", "noopener,noreferrer");
}
};
const showAdjacentPdf = useCallback((direction: -1 | 1) => {
setPdfPreview((current) => {
if (!current || pdfResources.length === 0) return current;
const currentIndex = pdfResources.findIndex((resource) => resource.id === current.id);
if (currentIndex === -1) return pdfResources[0] ?? current;
const nextIndex = (currentIndex + direction + pdfResources.length) % pdfResources.length;
return pdfResources[nextIndex] ?? current;
});
}, [pdfResources]);
const showPreviousPdf = useCallback(() => showAdjacentPdf(-1), [showAdjacentPdf]);
const showNextPdf = useCallback(() => showAdjacentPdf(1), [showAdjacentPdf]);
const getResourceOpenLabel = (resource: ResourceListItem) =>
isPdfAttachment(resource.mimeType, resource.filename)
? t("assets.previewPdf", { filename: resource.filename || resource.id })
: resource.kind === "image"
? t("assets.previewImage")
: t("assets.downloadOpen");
const getResourceMemoSource = (resource: { memoDeleted: boolean; memoTitle: string | null; memoExcerpt: string | null; memoId: string }) =>
resource.memoDeleted ? t("assets.deletedMemo") : resource.memoTitle || resource.memoExcerpt || resource.memoId;
return (
<div className="relative flex h-full min-h-0 flex-col bg-card select-none outline-none">
{/* Header */}
<header className="flex h-[calc(4rem+env(safe-area-inset-top))] shrink-0 items-end justify-between border-b border-slate-200 px-6 pb-3 pt-[env(safe-area-inset-top)] lg:h-16 lg:items-center lg:pb-0 lg:pt-0">
<div className="flex items-center gap-3">
<ButtonTooltip title={t("common.back")}>
<Button
size="icon"
variant="ghost"
aria-label={t("common.back")}
onClick={onClose}
className="flex h-9 w-9 items-center justify-center rounded-lg hover:bg-slate-100"
>
<ChevronLeft className="h-5 w-5 text-slate-500" />
</Button>
</ButtonTooltip>
<div className="min-w-0">
<h1 className={`flex items-center gap-2 ${WORKSPACE_PAGE_TITLE_CLASSNAME}`}>
<Paperclip className="h-4 w-4 text-slate-900" />
{t("assets.title")}
</h1>
<p className="mt-0.5 flex flex-wrap items-center gap-2 text-xs text-slate-500">
<span className="inline-flex items-center gap-1">
<HardDrive className="h-3 w-3" />
{formatBytes(summary.totalBytes)}
</span>
<span>•</span>
<span>{t("assets.fileCount", { count: summary.totalCount })}</span>
<span>•</span>
<span>{t("assets.imageCount", { count: summary.imageCount })}</span>
</p>
</div>
</div>
<ExecutionCenterButton onClick={onOpenExecutionCenter} />
</header>
{/* Toolbar (Filters, Search, Layout mode) */}
<div className="shrink-0 border-b border-slate-100 bg-card p-4">
<div className="mx-auto flex w-full max-w-4xl flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
{/* Category Filters */}
<div className="flex items-center gap-1.5 overflow-x-auto pb-1 sm:pb-0 scrollbar-none">
{(["all", "image", "document", "other"] as const).map((type) => (
<button
key={type}
onClick={() => setFilterType(type)}
className={`rounded-lg border border-transparent px-3 py-1.5 text-xs transition-colors ${
filterType === type
? "bg-workspace-selection font-semibold text-slate-950"
: "font-medium text-slate-600 hover:bg-slate-100"
}`}
>
{t(`assets.filters.${type}`)}
</button>
))}
</div>
{/* Search & Layout Toggles */}
<div className="flex min-w-0 items-center gap-2">
{/* Search box */}
<div className="relative min-w-0 flex-1 sm:w-64 sm:flex-none">
<Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
<input
type="text"
placeholder={t("assets.searchPlaceholder")}
aria-label={t("assets.searchPlaceholder")}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="h-9 w-full rounded-lg border border-slate-200 bg-slate-50 pl-9 pr-8 text-xs text-slate-800 placeholder:text-slate-400 transition-colors focus:border-slate-400 focus:bg-slate-50 focus:outline-none focus:ring-1 focus:ring-slate-400/30"
/>
{searchQuery && (
<button
onClick={() => setSearchQuery("")}
className="absolute right-2 top-1/2 -translate-y-1/2 rounded-full p-0.5 text-slate-400 hover:bg-slate-100 hover:text-slate-650"
>
<X className="h-3 w-3" />
</button>
)}
</div>
{/* Layout switches */}
<div className="flex h-9 shrink-0 items-center gap-0.5 rounded-lg border border-slate-200 bg-slate-50/50 p-0.5">
<ButtonTooltip title={t("assets.gridView")}>
<button
onClick={() => setLayoutMode("grid")}
aria-label={t("assets.gridView")}
aria-pressed={layoutMode === "grid"}
className={`flex h-8 w-8 items-center justify-center rounded-md transition-colors ${
layoutMode === "grid" ? "bg-card text-slate-950 shadow-sm" : "text-slate-400 hover:text-slate-700"
}`}
>
<Grid className="h-4 w-4" />
</button>
</ButtonTooltip>
<ButtonTooltip title={t("assets.listView")}>
<button
onClick={() => setLayoutMode("list")}
aria-label={t("assets.listView")}
aria-pressed={layoutMode === "list"}
className={`flex h-8 w-8 items-center justify-center rounded-md transition-colors ${
layoutMode === "list" ? "bg-card text-slate-950 shadow-sm" : "text-slate-400 hover:text-slate-700"
}`}
>
<List className="h-4 w-4" />
</button>
</ButtonTooltip>
</div>
</div>
</div>
</div>
{/* Main Content Area */}
<div className="flex-1 overflow-y-auto bg-workspace-canvas p-6">
<div className="mx-auto max-w-4xl">
{resourcesQuery.isLoading ? (
<div className="flex flex-col items-center justify-center py-32 text-slate-400">
<Loader2 className="mb-2 h-8 w-8 animate-spin text-slate-400" />
<span className="text-xs font-medium">{t("assets.loading")}</span>
</div>
) : filteredResources.length === 0 ? (
<div className="flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-slate-200 bg-card px-6 py-24 text-center">
<Paperclip className="h-10 w-10 text-slate-350 mb-3 stroke-[1.5]" />
<p className="text-sm font-semibold text-slate-500">
{searchQuery || filterType !== "all" ? t("assets.noMatches") : t("assets.empty")}
</p>
<p className="mt-1 text-xs text-slate-400">
{searchQuery || filterType !== "all"
? t("assets.noMatchesDescription")
: t("assets.emptyDescription")}
</p>
</div>
) : layoutMode === "grid" ? (
/* Grid View */
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4">
{filteredResources.map((resource) => (
<div
key={resource.id}
className="group relative flex flex-col overflow-hidden rounded-xl border border-slate-200 bg-card shadow-sm transition-all duration-200 hover:border-slate-300 hover:shadow-md"
>
<ButtonTooltip title={t("assets.deleteAria", { filename: resource.filename || resource.id })}>
<Button
type="button"
size="icon"
variant="ghost"
aria-label={t("assets.deleteAria", { filename: resource.filename || resource.id })}
className="edgeever-reveal-on-touch absolute right-2 top-2 z-10 h-8 w-8 bg-card/90 text-slate-500 opacity-0 shadow-sm transition-opacity hover:bg-rose-50 hover:text-rose-600 focus:opacity-100 group-hover:opacity-100 focus-within:opacity-100"
onClick={() => requestResourceDelete(resource)}
>
<Trash2 className="h-4 w-4" />
</Button>
</ButtonTooltip>
{/* Thumbnail area */}
<div
role="button"
tabIndex={0}
aria-label={getResourceOpenLabel(resource)}
onClick={() => handleResourceOpen(resource)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
handleResourceOpen(resource);
}
}}
className="relative aspect-square w-full cursor-pointer overflow-hidden bg-slate-50 flex items-center justify-center border-b border-slate-100"
>
{resource.kind === "image" ? (
<img
src={resource.url}
alt={resource.filename || ""}
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-103"
loading="lazy"
/>
) : isPdfAttachment(resource.mimeType, resource.filename) ? (
<PdfThumbnail
url={resource.url}
label={resource.filename || resource.id}
byteSize={resource.byteSize}
className="p-2"
/>
) : (
<div className="flex flex-col items-center gap-1.5 p-3 text-center">
<AttachmentFileIcon mimeType={resource.mimeType} filename={resource.filename} className="text-slate-700" />
<span className="rounded bg-slate-100 px-1.5 py-0.5 text-xs font-semibold text-slate-500">
{(resource.filename || "").split(".").pop() || "FILE"}
</span>
</div>
)}
{/* Hover detail overlay */}
<div className="absolute inset-0 bg-slate-900/40 opacity-0 transition-opacity duration-200 group-hover:opacity-100 flex items-center justify-center">
<span className="rounded bg-card/90 px-2.5 py-1.5 text-xs font-semibold text-slate-800 shadow flex items-center gap-1">
{resource.kind === "image"
? t("assets.previewImage")
: isPdfAttachment(resource.mimeType, resource.filename)
? t("pdfViewer.fullscreen")
: t("assets.downloadOpen")}
<ExternalLink className="h-3 w-3" />
</span>
</div>
</div>
{/* Metadata area */}
<div className="flex flex-col p-3 min-w-0">
<ButtonTooltip title={resource.filename || resource.id}>
<span className="truncate text-sm font-semibold leading-snug text-slate-950">
{resource.filename || resource.id}
</span>
</ButtonTooltip>
<span className="mt-1 flex items-center justify-between text-xs font-medium text-slate-400">
<span>{formatBytes(resource.byteSize)}</span>
<span>{(resource.mimeType?.split("/")[1] || resource.kind).toUpperCase()}</span>
</span>
<ButtonTooltip title={
resource.memoDeleted
? t("assets.deletedMemo")
: t("assets.fromMemo", { source: resource.memoTitle || resource.memoExcerpt || resource.memoId })
}>
<span className="mt-1.5 truncate border-t border-slate-100 pt-1 text-xs text-slate-500">
📄 {resource.memoDeleted ? t("assets.deletedMemo") : resource.memoTitle || resource.memoExcerpt || t("assets.unnamedMemo")}
</span>
</ButtonTooltip>
</div>
</div>
))}
</div>
) : (
/* List View */
<div className="flex flex-col gap-2.5">
{filteredResources.map((resource) => (
<div
key={resource.id}
className="group relative flex items-center gap-3.5 rounded-xl border border-slate-200/80 bg-card p-3.5 text-left transition-all duration-200 hover:border-slate-300 hover:shadow-sm"
>
{/* Left Icon/Thumbnail */}
<div
role="button"
tabIndex={0}
aria-label={getResourceOpenLabel(resource)}
onClick={() => handleResourceOpen(resource)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
handleResourceOpen(resource);
}
}}
className="relative flex h-12 w-12 shrink-0 cursor-pointer items-center justify-center overflow-hidden rounded-lg border border-slate-100 bg-slate-50/50"
>
{resource.kind === "image" ? (
<img
src={resource.url}
alt={resource.filename || ""}
className="h-full w-full object-cover transition-transform duration-200 group-hover:scale-105"
loading="lazy"
/>
) : isPdfAttachment(resource.mimeType, resource.filename) ? (
<PdfThumbnail
url={resource.url}
label={resource.filename || resource.id}
byteSize={resource.byteSize}
className="p-1"
/>
) : (
<AttachmentFileIcon mimeType={resource.mimeType} filename={resource.filename} className="text-slate-700" />
)}
</div>
{/* Mid Info */}
<div className="min-w-0 flex-1">
<span className="block truncate text-sm font-semibold leading-snug text-slate-950">
{resource.filename || resource.id}
</span>
<span className="mt-1 block truncate text-xs font-medium text-slate-400">
{formatBytes(resource.byteSize)} · {resource.mimeType?.split("/")[1] || resource.kind} ·{" "}
{formatDateTime(resource.createdAt)}
</span>
<span className="mt-1 block truncate text-xs text-slate-500">
{t("assets.sourceMemo", { source: getResourceMemoSource(resource) })}
</span>
</div>
{/* Right Actions */}
<ButtonTooltip title={t("assets.deleteAria", { filename: resource.filename || resource.id })}>
<Button
type="button"
size="icon"
variant="ghost"
aria-label={t("assets.deleteAria", { filename: resource.filename || resource.id })}
className="edgeever-reveal-on-touch h-8 w-8 text-slate-350 opacity-0 transition-all duration-150 hover:bg-rose-50 hover:text-rose-600 focus:opacity-100 group-hover:opacity-100 focus-within:opacity-100"
onClick={() => requestResourceDelete(resource)}
>
<Trash2 className="h-4 w-4" />
</Button>
</ButtonTooltip>
<ButtonTooltip title={t("assets.openInNewWindow")}>
<a
href={resource.url}
target="_blank"
rel="noreferrer"
aria-label={t("assets.openInNewWindow")}
className="edgeever-reveal-on-touch flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 opacity-0 transition-all duration-150 hover:bg-slate-50 hover:text-slate-800 focus:opacity-100 focus-within:opacity-100 group-hover:opacity-100"
>
<ExternalLink className="h-4 w-4" />
</a>
</ButtonTooltip>
</div>
))}
</div>
)}
</div>
</div>
{/* Lightbox Viewer */}
{lightboxIndex !== null && (
<Lightbox
index={lightboxIndex}
slides={slides}
open={lightboxIndex !== null}
close={() => setLightboxIndex(null)}
plugins={[Zoom, Thumbnails]}
/>
)}
{pdfPreview ? (
<PdfViewer
key={pdfPreview.id}
url={pdfPreview.url}
label={pdfPreview.filename || pdfPreview.id}
filename={pdfPreview.filename || undefined}
byteSize={pdfPreview.byteSize}
fullscreen
onRequestClose={() => setPdfPreview(null)}
onPrevious={pdfResources.length > 1 ? showPreviousPdf : undefined}
onNext={pdfResources.length > 1 ? showNextPdf : undefined}
/>
) : null}
{deleteTarget ? (
<AppConfirmDialog
title={t("assets.deleteTitle")}
description={t("assets.deleteDescription")}
confirmLabel={t("common.delete")}
error={deleteMutation.error instanceof Error ? deleteMutation.error.message : null}
isWorking={deleteMutation.isPending}
onCancel={() => {
deleteMutation.reset();
setDeleteTarget(null);
}}
onConfirm={() => deleteMutation.mutate(deleteTarget.id)}
/>
) : null}
</div>
);
};