feat(search-bar) = added in cloudpage
This commit is contained in:
@@ -513,7 +513,14 @@ router.get(
|
|||||||
if (!q) return sendError(res, 400, "Missing search query parameter 'q'");
|
if (!q) return sendError(res, 400, "Missing search query parameter 'q'");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { data, total } = await storage.searchFolders(q, limit, offset);
|
const parentId = null;
|
||||||
|
|
||||||
|
const { data, total } = await storage.searchFolders(
|
||||||
|
q,
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
parentId
|
||||||
|
);
|
||||||
return res.json({ error: false, data, totalCount: total });
|
return res.json({ error: false, data, totalCount: total });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return sendError(res, 500, "Folder search failed");
|
return sendError(res, 500, "Folder search failed");
|
||||||
|
|||||||
@@ -95,7 +95,8 @@ export interface IStorage {
|
|||||||
searchFolders(
|
searchFolders(
|
||||||
q: string,
|
q: string,
|
||||||
limit: number,
|
limit: number,
|
||||||
offset: number
|
offset: number,
|
||||||
|
parentId?: number | null
|
||||||
): Promise<{ data: CloudFolder[]; total: number }>;
|
): Promise<{ data: CloudFolder[]; total: number }>;
|
||||||
searchFiles(
|
searchFiles(
|
||||||
q: string,
|
q: string,
|
||||||
@@ -400,16 +401,34 @@ export const cloudStorageStorage: IStorage = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// --- SEARCH ---
|
// --- SEARCH ---
|
||||||
async searchFolders(q: string, limit = 20, offset = 0) {
|
async searchFolders(
|
||||||
|
q: string,
|
||||||
|
limit = 20,
|
||||||
|
offset = 0,
|
||||||
|
parentId?: number | null
|
||||||
|
) {
|
||||||
|
// Build where clause
|
||||||
|
const where: any = {
|
||||||
|
name: { contains: q, mode: "insensitive" },
|
||||||
|
};
|
||||||
|
|
||||||
|
// If parentId is explicitly provided:
|
||||||
|
// - parentId === null -> top-level folders (parent IS NULL)
|
||||||
|
// - parentId === number -> children of that folder
|
||||||
|
// If parentId is undefined -> search across all folders (no parent filter)
|
||||||
|
if (parentId !== undefined) {
|
||||||
|
where.parentId = parentId;
|
||||||
|
}
|
||||||
|
|
||||||
const [folders, total] = await Promise.all([
|
const [folders, total] = await Promise.all([
|
||||||
db.cloudFolder.findMany({
|
db.cloudFolder.findMany({
|
||||||
where: { name: { contains: q, mode: "insensitive" } },
|
where,
|
||||||
orderBy: { name: "asc" },
|
orderBy: { name: "asc" },
|
||||||
skip: offset,
|
skip: offset,
|
||||||
take: limit,
|
take: limit,
|
||||||
}),
|
}),
|
||||||
db.cloudFolder.count({
|
db.cloudFolder.count({
|
||||||
where: { name: { contains: q, mode: "insensitive" } },
|
where,
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
return { data: folders as unknown as CloudFolder[], total };
|
return { data: folders as unknown as CloudFolder[], total };
|
||||||
|
|||||||
@@ -1,21 +1,32 @@
|
|||||||
import React, { useEffect, useState } from "react";
|
import React, { useEffect, useState } from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { apiRequest } from "@/lib/queryClient";
|
import { apiRequest, queryClient } from "@/lib/queryClient";
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
import { Download, Maximize2, Minimize2, X } from "lucide-react";
|
import { Download, Maximize2, Minimize2, Trash2, X } from "lucide-react";
|
||||||
|
import { DeleteConfirmationDialog } from "../ui/deleteDialog";
|
||||||
|
import { QueryClient } from "@tanstack/react-query";
|
||||||
|
import { cloudFilesQueryKeyRoot } from "./files-section";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
fileId: number | null;
|
fileId: number | null;
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
|
onDeleted?: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function FilePreviewModal({ fileId, isOpen, onClose }: Props) {
|
export default function FilePreviewModal({
|
||||||
|
fileId,
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
onDeleted,
|
||||||
|
}: Props) {
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [meta, setMeta] = useState<any | null>(null);
|
const [meta, setMeta] = useState<any | null>(null);
|
||||||
const [blobUrl, setBlobUrl] = useState<string | null>(null);
|
const [blobUrl, setBlobUrl] = useState<string | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||||
|
const [deleting, setDeleting] = useState(false);
|
||||||
|
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isOpen || !fileId) return;
|
if (!isOpen || !fileId) return;
|
||||||
@@ -107,6 +118,49 @@ export default function FilePreviewModal({ fileId, isOpen, onClose }: Props) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function confirmDelete() {
|
||||||
|
if (!fileId) return;
|
||||||
|
|
||||||
|
setIsDeleteOpen(false);
|
||||||
|
setDeleting(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await apiRequest(
|
||||||
|
"DELETE",
|
||||||
|
`/api/cloud-storage/files/${fileId}`
|
||||||
|
);
|
||||||
|
const json = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(json?.message || `Delete failed (${res.status})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Deleted",
|
||||||
|
description: `File "${meta?.name ?? `file-${fileId}`}" deleted.`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// notify parent to refresh lists if they provided callback
|
||||||
|
if (typeof onDeleted === "function") {
|
||||||
|
try {
|
||||||
|
onDeleted();
|
||||||
|
} catch (e) {
|
||||||
|
// ignore parent errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// close modal
|
||||||
|
onClose();
|
||||||
|
} catch (err: any) {
|
||||||
|
toast({
|
||||||
|
title: "Delete failed",
|
||||||
|
description: err?.message ?? String(err),
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setDeleting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// container sizing classes
|
// container sizing classes
|
||||||
const containerBase =
|
const containerBase =
|
||||||
"bg-white rounded-md p-3 flex flex-col overflow-hidden shadow-xl";
|
"bg-white rounded-md p-3 flex flex-col overflow-hidden shadow-xl";
|
||||||
@@ -145,6 +199,13 @@ export default function FilePreviewModal({ fileId, isOpen, onClose }: Props) {
|
|||||||
<Button variant="ghost" onClick={handleDownload}>
|
<Button variant="ghost" onClick={handleDownload}>
|
||||||
<Download className="w-4 h-4" />
|
<Download className="w-4 h-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => setIsDeleteOpen(true)}
|
||||||
|
disabled={deleting}
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
<Button onClick={onClose}>
|
<Button onClick={onClose}>
|
||||||
{" "}
|
{" "}
|
||||||
<X className="w-4 h-4" />
|
<X className="w-4 h-4" />
|
||||||
@@ -211,6 +272,13 @@ export default function FilePreviewModal({ fileId, isOpen, onClose }: Props) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<DeleteConfirmationDialog
|
||||||
|
isOpen={isDeleteOpen}
|
||||||
|
entityName={meta?.name ?? undefined}
|
||||||
|
onCancel={() => setIsDeleteOpen(false)}
|
||||||
|
onConfirm={confirmDelete}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ import { getPageNumbers } from "@/utils/pageNumberGenerator";
|
|||||||
import { NewFolderModal } from "./new-folder-modal";
|
import { NewFolderModal } from "./new-folder-modal";
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
import FilePreviewModal from "./file-preview-modal";
|
import FilePreviewModal from "./file-preview-modal";
|
||||||
|
import { cloudSearchQueryKeyRoot } from "./search-bar";
|
||||||
|
|
||||||
export type FilesSectionProps = {
|
export type FilesSectionProps = {
|
||||||
parentId: number | null;
|
parentId: number | null;
|
||||||
@@ -44,6 +45,24 @@ export type FilesSectionProps = {
|
|||||||
onFileOpen?: (fileId: number) => void;
|
onFileOpen?: (fileId: number) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// canonical root key for files list queries (per-parent)
|
||||||
|
export const cloudFilesQueryKeyRoot = ["cloud-files"];
|
||||||
|
/**
|
||||||
|
* Build a full query key for files list under a parent folder with page parameters.
|
||||||
|
* Example usage:
|
||||||
|
* cloudFilesQueryKeyBase(parentId, page, pageSize)
|
||||||
|
*/
|
||||||
|
export const cloudFilesQueryKeyBase = (
|
||||||
|
parentId: number | null,
|
||||||
|
page: number,
|
||||||
|
pageSize: number
|
||||||
|
) => [
|
||||||
|
"cloud-files",
|
||||||
|
parentId === null ? "null" : String(parentId),
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
];
|
||||||
|
|
||||||
const FILES_LIMIT_DEFAULT = 20;
|
const FILES_LIMIT_DEFAULT = 20;
|
||||||
const MAX_FILE_MB = 10;
|
const MAX_FILE_MB = 10;
|
||||||
const MAX_FILE_BYTES = MAX_FILE_MB * 1024 * 1024;
|
const MAX_FILE_BYTES = MAX_FILE_MB * 1024 * 1024;
|
||||||
@@ -164,6 +183,8 @@ export default function FilesSection({
|
|||||||
qc.invalidateQueries({
|
qc.invalidateQueries({
|
||||||
queryKey: ["/api/cloud-storage/folders/recent", 1],
|
queryKey: ["/api/cloud-storage/folders/recent", 1],
|
||||||
});
|
});
|
||||||
|
qc.invalidateQueries({ queryKey: cloudFilesQueryKeyRoot, exact: false });
|
||||||
|
qc.invalidateQueries({ queryKey: cloudSearchQueryKeyRoot, exact: false });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
toast({
|
toast({
|
||||||
title: "Rename failed",
|
title: "Rename failed",
|
||||||
@@ -194,9 +215,14 @@ export default function FilesSection({
|
|||||||
|
|
||||||
// reload current page (ensure page index valid)
|
// reload current page (ensure page index valid)
|
||||||
loadPage(currentPage);
|
loadPage(currentPage);
|
||||||
|
|
||||||
qc.invalidateQueries({
|
qc.invalidateQueries({
|
||||||
queryKey: ["/api/cloud-storage/folders/recent", 1],
|
queryKey: ["/api/cloud-storage/folders/recent", 1],
|
||||||
});
|
});
|
||||||
|
// invalidate any cloud-files lists (so file lists refresh)
|
||||||
|
qc.invalidateQueries({ queryKey: cloudFilesQueryKeyRoot, exact: false });
|
||||||
|
// invalidate any cloud-search queries so search results refresh
|
||||||
|
qc.invalidateQueries({ queryKey: cloudSearchQueryKeyRoot, exact: false });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
toast({
|
toast({
|
||||||
title: "Delete failed",
|
title: "Delete failed",
|
||||||
@@ -310,6 +336,8 @@ export default function FilesSection({
|
|||||||
qc.invalidateQueries({
|
qc.invalidateQueries({
|
||||||
queryKey: ["/api/cloud-storage/folders/recent", 1],
|
queryKey: ["/api/cloud-storage/folders/recent", 1],
|
||||||
});
|
});
|
||||||
|
qc.invalidateQueries({ queryKey: cloudFilesQueryKeyRoot, exact: false });
|
||||||
|
qc.invalidateQueries({ queryKey: cloudSearchQueryKeyRoot, exact: false });
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
toast({
|
toast({
|
||||||
title: "Upload failed",
|
title: "Upload failed",
|
||||||
@@ -518,7 +546,29 @@ export default function FilesSection({
|
|||||||
setIsPreviewOpen(false);
|
setIsPreviewOpen(false);
|
||||||
setPreviewFileId(null);
|
setPreviewFileId(null);
|
||||||
}}
|
}}
|
||||||
|
onDeleted={() => {
|
||||||
|
// close preview
|
||||||
|
setIsPreviewOpen(false);
|
||||||
|
setPreviewFileId(null);
|
||||||
|
|
||||||
|
// reload this folder page
|
||||||
|
loadPage(currentPage);
|
||||||
|
|
||||||
|
// invalidate caches
|
||||||
|
qc.invalidateQueries({
|
||||||
|
queryKey: ["/api/cloud-storage/folders/recent", 1],
|
||||||
|
});
|
||||||
|
qc.invalidateQueries({
|
||||||
|
queryKey: cloudFilesQueryKeyRoot,
|
||||||
|
exact: false,
|
||||||
|
});
|
||||||
|
qc.invalidateQueries({
|
||||||
|
queryKey: cloudSearchQueryKeyRoot,
|
||||||
|
exact: false,
|
||||||
|
});
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* delete confirm */}
|
{/* delete confirm */}
|
||||||
<DeleteConfirmationDialog
|
<DeleteConfirmationDialog
|
||||||
isOpen={isDeleteOpen}
|
isOpen={isDeleteOpen}
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
// Updated components to support: 1) navigating into child folders (FolderSection -> FolderPanel)
|
|
||||||
// 2) a breadcrumb / path strip in FolderPanel so user can see & click parent folders
|
|
||||||
|
|
||||||
import React, { useEffect, useRef, useState } from "react";
|
import React, { useEffect, useRef, useState } from "react";
|
||||||
import FolderSection from "@/components/cloud-storage/folder-section";
|
import FolderSection from "@/components/cloud-storage/folder-section";
|
||||||
import FilesSection from "@/components/cloud-storage/files-section";
|
import FilesSection from "@/components/cloud-storage/files-section";
|
||||||
@@ -116,9 +113,8 @@ export default function FolderPanel({
|
|||||||
<h2 className="text-2xl font-semibold">
|
<h2 className="text-2xl font-semibold">
|
||||||
{currentFolderId == null
|
{currentFolderId == null
|
||||||
? "My Cloud Storage"
|
? "My Cloud Storage"
|
||||||
: `Folder ${currentFolderId}`}
|
: `Folder : ${path[path.length - 1]?.name ?? currentFolderId}`}
|
||||||
</h2>
|
</h2>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
{onClose && (
|
{onClose && (
|
||||||
<button
|
<button
|
||||||
|
|||||||
426
apps/Frontend/src/components/cloud-storage/search-bar.tsx
Normal file
426
apps/Frontend/src/components/cloud-storage/search-bar.tsx
Normal file
@@ -0,0 +1,426 @@
|
|||||||
|
import React, { useEffect, useMemo, useState } from "react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { apiRequest } from "@/lib/queryClient";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import {
|
||||||
|
Folder as FolderIcon,
|
||||||
|
File as FileIcon,
|
||||||
|
Search as SearchIcon,
|
||||||
|
Clock as ClockIcon,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { motion, AnimatePresence } from "framer-motion";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Canonical query keys
|
||||||
|
*/
|
||||||
|
export const cloudSearchQueryKeyRoot = ["cloud-search"];
|
||||||
|
|
||||||
|
export const cloudSearchQueryKeyBase = (
|
||||||
|
q: string,
|
||||||
|
searchTarget: "filename" | "foldername" | "both",
|
||||||
|
typeFilter: "any" | "images" | "pdf" | "video" | "audio",
|
||||||
|
page: number
|
||||||
|
) => ["cloud-search", q, searchTarget, typeFilter, page];
|
||||||
|
|
||||||
|
type ResultRow = {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
mimeType?: string | null;
|
||||||
|
folderId?: number | null;
|
||||||
|
isComplete?: boolean;
|
||||||
|
kind: "file" | "folder";
|
||||||
|
fileSize?: string | number | null;
|
||||||
|
createdAt?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function CloudSearchBar({
|
||||||
|
onOpenFolder = (id: number | null) => {},
|
||||||
|
onSelectFile = (fileId: number) => {},
|
||||||
|
}: {
|
||||||
|
onOpenFolder?: (id: number | null) => void;
|
||||||
|
onSelectFile?: (fileId: number) => void;
|
||||||
|
}) {
|
||||||
|
const [q, setQ] = useState("");
|
||||||
|
const [searchTarget, setSearchTarget] = useState<
|
||||||
|
"filename" | "foldername" | "both"
|
||||||
|
>("filename"); // default filename
|
||||||
|
const [typeFilter, setTypeFilter] = useState<
|
||||||
|
"any" | "images" | "pdf" | "video" | "audio"
|
||||||
|
>("any");
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [limit] = useState(10);
|
||||||
|
|
||||||
|
const debounceMs = 600;
|
||||||
|
const [debouncedQ, setDebouncedQ] = useState(q);
|
||||||
|
|
||||||
|
// debounce input
|
||||||
|
useEffect(() => {
|
||||||
|
const t = setTimeout(() => setDebouncedQ(q.trim()), debounceMs);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [q, debounceMs]);
|
||||||
|
|
||||||
|
function typeParamFromFilter(filter: string) {
|
||||||
|
if (filter === "any") return undefined;
|
||||||
|
if (filter === "images") return "image";
|
||||||
|
if (filter === "pdf") return "application/pdf";
|
||||||
|
return filter;
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetcher used by useQuery
|
||||||
|
async function fetchSearch(): Promise<{
|
||||||
|
results: ResultRow[];
|
||||||
|
total: number;
|
||||||
|
}> {
|
||||||
|
const query = debouncedQ ?? "";
|
||||||
|
if (!query) return { results: [], total: 0 };
|
||||||
|
|
||||||
|
const offset = (page - 1) * limit;
|
||||||
|
const typeParam = typeParamFromFilter(typeFilter as string);
|
||||||
|
|
||||||
|
// helper: call files endpoint
|
||||||
|
async function callFiles() {
|
||||||
|
const tQuery = typeParam ? `&type=${encodeURIComponent(typeParam)}` : "";
|
||||||
|
const res = await apiRequest(
|
||||||
|
"GET",
|
||||||
|
`/api/cloud-storage/search/files?q=${encodeURIComponent(query)}${tQuery}&limit=${limit}&offset=${offset}`
|
||||||
|
);
|
||||||
|
const json = await res.json();
|
||||||
|
if (!res.ok) throw new Error(json?.message || "File search failed");
|
||||||
|
const mapped: ResultRow[] = (json.data || []).map((d: any) => ({
|
||||||
|
id: d.id,
|
||||||
|
name: d.name,
|
||||||
|
kind: "file",
|
||||||
|
mimeType: d.mimeType,
|
||||||
|
fileSize: d.fileSize,
|
||||||
|
folderId: d.folderId ?? null,
|
||||||
|
createdAt: d.createdAt,
|
||||||
|
}));
|
||||||
|
return { mapped, total: json.totalCount ?? mapped.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
// helper: call folders endpoint
|
||||||
|
async function callFolders() {
|
||||||
|
const res = await apiRequest(
|
||||||
|
"GET",
|
||||||
|
`/api/cloud-storage/search/folders?q=${encodeURIComponent(query)}&limit=${limit}&offset=${offset}`
|
||||||
|
);
|
||||||
|
const json = await res.json();
|
||||||
|
if (!res.ok) throw new Error(json?.message || "Folder search failed");
|
||||||
|
const mapped: ResultRow[] = (json.data || []).map((d: any) => ({
|
||||||
|
id: d.id,
|
||||||
|
name: d.name,
|
||||||
|
kind: "folder",
|
||||||
|
folderId: d.parentId ?? null,
|
||||||
|
}));
|
||||||
|
// enforce top-level folders only when searching folders specifically
|
||||||
|
// (if the API already filters, this is harmless)
|
||||||
|
return { mapped, total: json.totalCount ?? mapped.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decide which endpoints to call
|
||||||
|
if (searchTarget === "filename") {
|
||||||
|
const f = await callFiles();
|
||||||
|
return { results: f.mapped, total: f.total };
|
||||||
|
} else if (searchTarget === "foldername") {
|
||||||
|
const fo = await callFolders();
|
||||||
|
// filter top-level only (parentId === null)
|
||||||
|
const topLevel = fo.mapped.filter((r) => r.folderId == null);
|
||||||
|
return { results: topLevel, total: fo.total };
|
||||||
|
} else {
|
||||||
|
// both: call both and combine (folders first, then files), but keep page limit
|
||||||
|
const [filesRes, foldersRes] = await Promise.all([
|
||||||
|
callFiles(),
|
||||||
|
callFolders(),
|
||||||
|
]);
|
||||||
|
// folders restrict to top-level
|
||||||
|
const foldersTop = foldersRes.mapped.filter((r) => r.folderId == null);
|
||||||
|
const combined = [...foldersTop, ...filesRes.mapped].slice(0, limit);
|
||||||
|
const combinedTotal = foldersRes.total + filesRes.total;
|
||||||
|
return { results: combined, total: combinedTotal };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// react-query: key depends on debouncedQ, searchTarget, typeFilter, page
|
||||||
|
const queryKey = useMemo(
|
||||||
|
() => cloudSearchQueryKeyBase(debouncedQ, searchTarget, typeFilter, page),
|
||||||
|
[debouncedQ, searchTarget, typeFilter, page]
|
||||||
|
);
|
||||||
|
|
||||||
|
const { data, isFetching, error } = useQuery({
|
||||||
|
queryKey,
|
||||||
|
queryFn: fetchSearch,
|
||||||
|
enabled: debouncedQ.length > 0,
|
||||||
|
staleTime: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
// sync local UI state with query data
|
||||||
|
const results = data?.results ?? [];
|
||||||
|
const total = data?.total ?? 0;
|
||||||
|
const loading = isFetching;
|
||||||
|
const errMsg = error ? ((error as any)?.message ?? String(error)) : null;
|
||||||
|
|
||||||
|
// persist recent terms & matches when new results arrive
|
||||||
|
useEffect(() => {
|
||||||
|
if (!debouncedQ) return;
|
||||||
|
// recent terms
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem("cloud_search_recent_terms");
|
||||||
|
const prev: string[] = raw ? JSON.parse(raw) : [];
|
||||||
|
const term = debouncedQ;
|
||||||
|
const copy = [term, ...prev.filter((t) => t !== term)].slice(0, 10);
|
||||||
|
localStorage.setItem("cloud_search_recent_terms", JSON.stringify(copy));
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
// recent matches snapshot
|
||||||
|
try {
|
||||||
|
const rawMatches = localStorage.getItem("cloud_search_recent_matches");
|
||||||
|
const prevMatches: Record<string, ResultRow[]> = rawMatches
|
||||||
|
? JSON.parse(rawMatches)
|
||||||
|
: {};
|
||||||
|
const snapshot = results;
|
||||||
|
const copy = { ...prevMatches, [debouncedQ]: snapshot };
|
||||||
|
localStorage.setItem("cloud_search_recent_matches", JSON.stringify(copy));
|
||||||
|
} catch {}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [data, debouncedQ]);
|
||||||
|
|
||||||
|
// load recentTerms & recentMatches from storage for initial UI
|
||||||
|
const [recentTerms, setRecentTerms] = useState<string[]>(() => {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem("cloud_search_recent_terms");
|
||||||
|
return raw ? JSON.parse(raw) : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const [recentMatches, setRecentMatches] = useState<
|
||||||
|
Record<string, ResultRow[]>
|
||||||
|
>(() => {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem("cloud_search_recent_matches");
|
||||||
|
return raw ? JSON.parse(raw) : {};
|
||||||
|
} catch {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// update recentTerms/recentMatches UI copies whenever localStorage changes (best-effort)
|
||||||
|
useEffect(() => {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem("cloud_search_recent_terms");
|
||||||
|
setRecentTerms(raw ? JSON.parse(raw) : []);
|
||||||
|
} catch {}
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem("cloud_search_recent_matches");
|
||||||
|
setRecentMatches(raw ? JSON.parse(raw) : {});
|
||||||
|
} catch {}
|
||||||
|
}, [data]); // refresh small UX cache when new data arrives
|
||||||
|
|
||||||
|
// reset page when q or filters change (like before)
|
||||||
|
useEffect(() => setPage(1), [debouncedQ, searchTarget, typeFilter]);
|
||||||
|
|
||||||
|
const totalPages = useMemo(
|
||||||
|
() => Math.max(1, Math.ceil(total / limit)),
|
||||||
|
[total, limit]
|
||||||
|
);
|
||||||
|
|
||||||
|
function onClear() {
|
||||||
|
setQ("");
|
||||||
|
// the query will auto-disable when debouncedQ is empty
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-card p-4 rounded-2xl shadow-sm">
|
||||||
|
<div className="flex flex-col md:flex-row gap-3 md:items-center">
|
||||||
|
<div className="flex items-center gap-2 flex-1">
|
||||||
|
<SearchIcon className="h-5 w-5 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
value={q}
|
||||||
|
onChange={(e) => setQ(e.target.value)}
|
||||||
|
placeholder="Search files and folders..."
|
||||||
|
aria-label="Search files and folders"
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<Button variant="ghost" onClick={() => onClear()}>
|
||||||
|
Clear
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Select
|
||||||
|
onValueChange={(v) => setSearchTarget(v as any)}
|
||||||
|
value={searchTarget}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-40">
|
||||||
|
<SelectValue placeholder="Search target" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="filename">Filename (default)</SelectItem>
|
||||||
|
<SelectItem value="foldername">
|
||||||
|
Folder name (top-level)
|
||||||
|
</SelectItem>
|
||||||
|
<SelectItem value="both">Both</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
|
||||||
|
<Select
|
||||||
|
onValueChange={(v) => setTypeFilter(v as any)}
|
||||||
|
value={typeFilter}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-40">
|
||||||
|
<SelectValue placeholder="Type" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="any">Any type</SelectItem>
|
||||||
|
<SelectItem value="images">Images</SelectItem>
|
||||||
|
<SelectItem value="pdf">PDFs</SelectItem>
|
||||||
|
<SelectItem value="video">Videos</SelectItem>
|
||||||
|
<SelectItem value="audio">Audio</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
|
||||||
|
<Button onClick={() => setPage((p) => p)}>Search</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<h4 className="mb-2 text-sm font-semibold flex items-center gap-2">
|
||||||
|
<ClockIcon className="h-4 w-4" /> Recent searches
|
||||||
|
</h4>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{recentTerms.length ? (
|
||||||
|
recentTerms.map((t) => (
|
||||||
|
<motion.button
|
||||||
|
key={t}
|
||||||
|
whileHover={{ scale: 1.03 }}
|
||||||
|
whileTap={{ scale: 0.98 }}
|
||||||
|
className="px-3 py-1 rounded-full bg-muted text-sm"
|
||||||
|
onClick={() => setQ(t)}
|
||||||
|
>
|
||||||
|
{t}
|
||||||
|
</motion.button>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<div className="text-sm text-muted-foreground">
|
||||||
|
No recent searches
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h4 className="mb-2 text-sm font-semibold">Results</h4>
|
||||||
|
|
||||||
|
<div className="bg-background rounded-md p-2 max-h-72 overflow-auto">
|
||||||
|
<AnimatePresence>
|
||||||
|
{loading && (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
exit={{ opacity: 0 }}
|
||||||
|
className="p-4 text-center text-sm"
|
||||||
|
>
|
||||||
|
Searching...
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loading && errMsg && (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
exit={{ opacity: 0 }}
|
||||||
|
className="p-4 text-sm text-destructive"
|
||||||
|
>
|
||||||
|
{errMsg}
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loading && !results.length && debouncedQ && !errMsg && (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
exit={{ opacity: 0 }}
|
||||||
|
className="p-4 text-sm text-muted-foreground"
|
||||||
|
>
|
||||||
|
No results for "{debouncedQ}"
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loading &&
|
||||||
|
results.map((r) => (
|
||||||
|
<motion.div
|
||||||
|
key={`${r.kind}-${r.id}`}
|
||||||
|
initial={{ opacity: 0, y: 6 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0 }}
|
||||||
|
className="p-2 rounded hover:bg-muted/50 flex items-center gap-3 cursor-pointer"
|
||||||
|
onClick={() => {
|
||||||
|
if (r.kind === "folder") onOpenFolder(r.id);
|
||||||
|
else onSelectFile(r.id);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="w-8 h-8 flex items-center justify-center rounded bg-muted">
|
||||||
|
{r.kind === "folder" ? (
|
||||||
|
<FolderIcon className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<FileIcon className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="truncate font-medium">{r.name}</div>
|
||||||
|
<div className="text-xs text-muted-foreground truncate">
|
||||||
|
{r.kind === "file" ? (r.mimeType ?? "file") : "Folder"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{r.kind === "file" && r.fileSize != null && (
|
||||||
|
<div className="text-xs text-muted-foreground">
|
||||||
|
{String(r.fileSize)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</motion.div>
|
||||||
|
))}
|
||||||
|
</AnimatePresence>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-3 flex items-center justify-between">
|
||||||
|
<div className="text-sm text-muted-foreground">
|
||||||
|
{total} result(s)
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
||||||
|
disabled={page <= 1}
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<div className="text-sm">
|
||||||
|
{page} / {totalPages}
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
|
||||||
|
disabled={page >= totalPages}
|
||||||
|
>
|
||||||
|
<ChevronRight className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -10,6 +10,11 @@ import { useAuth } from "@/hooks/use-auth";
|
|||||||
import RecentTopLevelFoldersCard, {
|
import RecentTopLevelFoldersCard, {
|
||||||
recentTopLevelFoldersQueryKey,
|
recentTopLevelFoldersQueryKey,
|
||||||
} from "@/components/cloud-storage/recent-top-level-folder-modal";
|
} from "@/components/cloud-storage/recent-top-level-folder-modal";
|
||||||
|
import CloudSearchBar, {
|
||||||
|
cloudSearchQueryKeyRoot,
|
||||||
|
} from "@/components/cloud-storage/search-bar";
|
||||||
|
import FilePreviewModal from "@/components/cloud-storage/file-preview-modal";
|
||||||
|
import { cloudFilesQueryKeyRoot } from "@/components/cloud-storage/files-section";
|
||||||
|
|
||||||
export default function CloudStoragePage() {
|
export default function CloudStoragePage() {
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
@@ -28,6 +33,21 @@ export default function CloudStoragePage() {
|
|||||||
// New folder modal
|
// New folder modal
|
||||||
const [isNewFolderOpen, setIsNewFolderOpen] = useState(false);
|
const [isNewFolderOpen, setIsNewFolderOpen] = useState(false);
|
||||||
|
|
||||||
|
// searchbar - file preview modal state
|
||||||
|
const [previewFileId, setPreviewFileId] = useState<number | null>(null);
|
||||||
|
const [isPreviewOpen, setIsPreviewOpen] = useState(false);
|
||||||
|
|
||||||
|
// searchbar - handlers
|
||||||
|
function handleOpenFolder(folderId: number | null) {
|
||||||
|
setPanelInitialFolderId(folderId);
|
||||||
|
setPanelOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSelectFile(fileId: number) {
|
||||||
|
setPreviewFileId(fileId);
|
||||||
|
setIsPreviewOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
// create folder handler (page-level)
|
// create folder handler (page-level)
|
||||||
async function handleCreateFolder(name: string) {
|
async function handleCreateFolder(name: string) {
|
||||||
try {
|
try {
|
||||||
@@ -72,21 +92,21 @@ export default function CloudStoragePage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex gap-2 items-center">
|
<div className="flex gap-2 items-center">
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
onClick={() => {
|
|
||||||
/* search flow omitted - wire your search UI here */
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<SearchIcon className="h-4 w-4 mr-2" /> Search
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Button onClick={() => setIsNewFolderOpen(true)}>
|
<Button onClick={() => setIsNewFolderOpen(true)}>
|
||||||
<FolderIcon className="h-4 w-4 mr-2" /> New Folder
|
<FolderIcon className="h-4 w-4 mr-2" /> New Folder
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<CloudSearchBar
|
||||||
|
onOpenFolder={(folderId) => {
|
||||||
|
handleOpenFolder(folderId);
|
||||||
|
}}
|
||||||
|
onSelectFile={(fileId) => {
|
||||||
|
handleSelectFile(fileId);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Recent folders card (delegated component) */}
|
{/* Recent folders card (delegated component) */}
|
||||||
<RecentTopLevelFoldersCard
|
<RecentTopLevelFoldersCard
|
||||||
key={recentKey}
|
key={recentKey}
|
||||||
@@ -115,6 +135,36 @@ export default function CloudStoragePage() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{/* File preview modal */}
|
||||||
|
<FilePreviewModal
|
||||||
|
fileId={previewFileId}
|
||||||
|
isOpen={isPreviewOpen}
|
||||||
|
onClose={() => {
|
||||||
|
setIsPreviewOpen(false);
|
||||||
|
setPreviewFileId(null);
|
||||||
|
}}
|
||||||
|
onDeleted={() => {
|
||||||
|
// close preview (modal may already close, but be explicit)
|
||||||
|
setIsPreviewOpen(false);
|
||||||
|
setPreviewFileId(null);
|
||||||
|
|
||||||
|
// refresh the recent folders card
|
||||||
|
qc.invalidateQueries({ queryKey: recentTopLevelFoldersQueryKey(1) });
|
||||||
|
|
||||||
|
// invalidate file lists and search results
|
||||||
|
qc.invalidateQueries({
|
||||||
|
queryKey: cloudFilesQueryKeyRoot,
|
||||||
|
exact: false,
|
||||||
|
});
|
||||||
|
qc.invalidateQueries({
|
||||||
|
queryKey: cloudSearchQueryKeyRoot,
|
||||||
|
exact: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// remount the recent card so it clears internal selection (UX nicety)
|
||||||
|
setRecentKey((k) => k + 1);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* New folder modal (reusable) */}
|
{/* New folder modal (reusable) */}
|
||||||
<NewFolderModal
|
<NewFolderModal
|
||||||
|
|||||||
Reference in New Issue
Block a user