Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: add search to documents

Marc Seitz8e784a497180
diff --git a/components/documents/document-card.tsx b/components/documents/document-card.tsx
index d5375f10..ab3ed85d 100644
--- a/components/documents/document-card.tsx
+++ b/components/documents/document-card.tsx
@@ -212,7 +212,7 @@ export default function DocumentsCard({
<div className="flex-col">
<div className="flex items-center">
- <h2 className="min-w-0 max-w-[150px] truncate text-sm font-semibold leading-6 text-foreground sm:max-w-md">
+ <h2 className="min-w-0 max-w-[250px] truncate text-sm font-semibold leading-6 text-foreground sm:max-w-md">
<Link
href={`/documents/${prismaDocument.id}`}
className="w-full truncate"
diff --git a/components/search-box.tsx b/components/search-box.tsx
new file mode 100644
index 00000000..9e796d5d
--- /dev/null
+++ b/components/search-box.tsx
@@ -0,0 +1,171 @@
+// Inspired by Steven Tey's flawless search implementation in dub.co
+// https://github.com/dubinc/dub/blob/450749a29ca2ec2486fb2272a73cfbd8a5d80b3f/apps/web/ui/shared/search-box.tsx
+import { useRouter } from "next/router";
+
+import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+} from "react";
+
+import { CircleXIcon, SearchIcon } from "lucide-react";
+import { useDebouncedCallback } from "use-debounce";
+
+import { cn } from "@/lib/utils";
+
+import LoadingSpinner from "./ui/loading-spinner";
+
+type SearchBoxProps = {
+ value: string;
+ loading?: boolean;
+ showClearButton?: boolean;
+ onChange: (value: string) => void;
+ onChangeDebounced?: (value: string) => void;
+ debounceTimeoutMs?: number;
+ inputClassName?: string;
+};
+
+export const SearchBox = forwardRef(
+ (
+ {
+ value,
+ loading,
+ showClearButton = true,
+ onChange,
+ onChangeDebounced,
+ debounceTimeoutMs = 500,
+ inputClassName,
+ }: SearchBoxProps,
+ forwardedRef,
+ ) => {
+ const inputRef = useRef<HTMLInputElement>(null);
+ useImperativeHandle(forwardedRef, () => inputRef.current);
+
+ const debounced = useDebouncedCallback(
+ (value) => onChangeDebounced?.(value),
+ debounceTimeoutMs,
+ );
+
+ const onKeyDown = useCallback((e: KeyboardEvent) => {
+ const target = e.target as HTMLElement;
+ // only focus on filter input when:
+ // - user is not typing in an input or textarea
+ // - there is no existing modal backdrop (i.e. no other modal is open)
+ if (
+ e.key === "/" &&
+ target.tagName !== "INPUT" &&
+ target.tagName !== "TEXTAREA"
+ ) {
+ e.preventDefault();
+ inputRef.current?.focus();
+ }
+ }, []);
+
+ useEffect(() => {
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, [onKeyDown]);
+
+ return (
+ <div className="relative">
+ <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-4">
+ {loading && value.length > 0 ? (
+ <LoadingSpinner className="h-4 w-4" />
+ ) : (
+ <SearchIcon className="h-4 w-4 text-muted-foreground" />
+ )}
+ </div>
+ <input
+ ref={inputRef}
+ type="text"
+ className={cn(
+ "peer w-full rounded-md border border-border bg-white px-10 text-foreground outline-none placeholder:text-muted-foreground dark:bg-gray-800 sm:text-sm",
+ "transition-all focus:border-gray-500 focus:ring-0",
+ inputClassName,
+ )}
+ placeholder="Search..."
+ value={value}
+ onChange={(e) => {
+ onChange(e.target.value);
+ debounced(e.target.value);
+ }}
+ autoCapitalize="none"
+ />
+ {showClearButton && value.length > 0 && (
+ <button
+ onClick={() => {
+ onChange("");
+ onChangeDebounced?.("");
+ }}
+ className="pointer-events-auto absolute inset-y-0 right-0 flex items-center pr-4"
+ >
+ <CircleXIcon className="h-4 w-4 text-muted-foreground" />
+ </button>
+ )}
+ </div>
+ );
+ },
+);
+
+export function SearchBoxPersisted({
+ urlParam = "search",
+ ...props
+}: { urlParam?: string } & Partial<SearchBoxProps>) {
+ const router = useRouter();
+ const queryParams = router.query;
+
+ const [value, setValue] = useState(queryParams[urlParam] ?? "");
+ const [debouncedValue, setDebouncedValue] = useState(value);
+
+ console.log("queryParams", queryParams);
+ console.log("debouncedValue", debouncedValue);
+ console.log("value", value);
+
+ // Set URL param when debounced value changes
+ useEffect(() => {
+ if (queryParams[urlParam] ?? "" !== debouncedValue)
+ if (debouncedValue === "") {
+ delete queryParams[urlParam];
+ router.push(
+ {
+ pathname: router.pathname,
+ query: queryParams,
+ },
+ undefined,
+ { shallow: true },
+ );
+ } else {
+ queryParams[urlParam] = debouncedValue;
+ console.log("queryParams", queryParams);
+ router.push(
+ {
+ pathname: router.pathname,
+ query: queryParams,
+ },
+ undefined,
+ { shallow: true },
+ );
+ }
+ }, [debouncedValue]);
+
+ // Set value when URL param changes
+ useEffect(() => {
+ const search = queryParams[urlParam];
+ // Only update if the value and debouncedValue are synced (the user isn't actively typing)
+ if ((search ?? "" !== value) && value === debouncedValue) {
+ setValue(search ?? "");
+ }
+ }, [queryParams[urlParam]]);
+
+ return (
+ <SearchBox
+ value={value as string}
+ onChange={setValue}
+ onChangeDebounced={setDebouncedValue}
+ {...props}
+ />
+ );
+}
diff --git a/lib/swr/use-documents.ts b/lib/swr/use-documents.ts
index a93d8101..3e3eaa92 100644
--- a/lib/swr/use-documents.ts
+++ b/lib/swr/use-documents.ts
@@ -1,3 +1,5 @@
+import { useRouter } from "next/router";
+
import { useTeam } from "@/context/team-context";
import { Folder } from "@prisma/client";
import useSWR from "swr";
@@ -5,18 +7,35 @@ import useSWR from "swr";
import { DocumentWithLinksAndLinkCountAndViewCount } from "@/lib/types";
import { fetcher } from "@/lib/utils";
-export function useDocuments() {
- const { currentTeam } = useTeam();
+export default function useDocuments() {
+ const router = useRouter();
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const queryParams = router.query;
+ const searchQuery = queryParams["search"];
- const { data, error } = useSWR<DocumentWithLinksAndLinkCountAndViewCount[]>(
- currentTeam ? `/api/teams/${currentTeam.id}/documents` : null,
+ const {
+ data: documents,
+ isValidating,
+ error,
+ } = useSWR<DocumentWithLinksAndLinkCountAndViewCount[]>(
+ teamId &&
+ `/api/teams/${teamId}/documents${searchQuery ? `/search?query=${searchQuery}` : ""}`,
fetcher,
+ {
+ revalidateOnFocus: false,
+ dedupingInterval: 30000,
+ keepPreviousData: true,
+ },
);
return {
- documents: data,
- isLoading: !error && !data,
- isError: error,
+ documents,
+ isValidating,
+ loading: !documents && !error,
+ isSearchResult: !!searchQuery,
+ error,
};
}
diff --git a/pages/api/teams/[teamId]/documents/search.ts b/pages/api/teams/[teamId]/documents/search.ts
index 3a7bb132..2db23d26 100644
--- a/pages/api/teams/[teamId]/documents/search.ts
+++ b/pages/api/teams/[teamId]/documents/search.ts
@@ -21,6 +21,21 @@ export default async function handle(
const userId = (session.user as CustomUser).id;
try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ });
+
+ if (!team) {
+ return res.status(404).end("Team not found");
+ }
+
const documents = await prisma.document.findMany({
where: {
teamId: teamId,
@@ -33,20 +48,9 @@ export default async function handle(
createdAt: "desc",
},
include: {
- folder: {
- select: {
- id: true,
- name: true,
- path: true,
- },
- },
_count: {
select: { links: true, views: true, versions: true },
},
- links: {
- take: 1,
- select: { id: true },
- },
},
});
diff --git a/pages/documents/index.tsx b/pages/documents/index.tsx
index 24a6a4d3..7c23bcca 100644
--- a/pages/documents/index.tsx
+++ b/pages/documents/index.tsx
@@ -1,93 +1,42 @@
-import { useRouter } from "next/router";
-
-import { useCallback, useMemo, useState } from "react";
-
import { useTeam } from "@/context/team-context";
-import { Search } from "lucide-react";
-import { FileIcon, FolderIcon, FolderPlusIcon, PlusIcon } from "lucide-react";
-import useSWR from "swr";
-import { useDebounce } from "use-debounce";
+import { FolderPlusIcon, PlusIcon } from "lucide-react";
import { AddDocumentModal } from "@/components/documents/add-document-modal";
-import { BreadcrumbComponent } from "@/components/documents/breadcrumb";
import { DocumentsList } from "@/components/documents/documents-list";
import { AddFolderModal } from "@/components/folders/add-folder-modal";
import AppLayout from "@/components/layouts/app";
+import { SearchBoxPersisted } from "@/components/search-box";
import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
-import { useDocuments, useFolder } from "@/lib/swr/use-documents";
-import { DocumentWithLinksAndLinkCountAndViewCount } from "@/lib/types";
-import { fetcher } from "@/lib/utils";
+import useDocuments, { useRootFolders } from "@/lib/swr/use-documents";
export default function Documents() {
- const router = useRouter();
const teamInfo = useTeam();
- const { folders } = useFolder({});
- const { documents: allDocuments, isLoading: isLoadingDocuments } =
- useDocuments();
-
- const [searchTerm, setSearchTerm] = useState("");
- const [debouncedSearchTerm] = useDebounce(searchTerm, 300);
-
- const fetchSearchResults = useCallback(async () => {
- if (!debouncedSearchTerm || !teamInfo?.currentTeam?.id) return null;
- const response = await fetch(
- `/api/teams/${teamInfo.currentTeam.id}/documents/search?query=${encodeURIComponent(debouncedSearchTerm)}`,
- );
- if (!response.ok) throw new Error("Failed to fetch search results");
- return response.json();
- }, [debouncedSearchTerm, teamInfo?.currentTeam?.id]);
-
- const { data: searchResults, error: searchError } = useSWR<
- DocumentWithLinksAndLinkCountAndViewCount[]
- >(
- debouncedSearchTerm ? ["searchDocuments", debouncedSearchTerm] : null,
- fetchSearchResults,
- );
-
- const displayedDocuments = useMemo(() => {
- if (debouncedSearchTerm && searchResults) {
- return searchResults;
- }
- return allDocuments;
- }, [debouncedSearchTerm, searchResults, allDocuments]);
-
- const isLoading =
- isLoadingDocuments || (!searchResults && debouncedSearchTerm);
+ const { folders } = useRootFolders();
+ const { documents, isValidating, isSearchResult } = useDocuments();
return (
<AppLayout>
<div className="sticky top-0 z-50 bg-white p-4 pb-0 dark:bg-gray-900 sm:mx-4 sm:pt-8">
- <section className="mb-4 flex items-center justify-between space-x-2 sm:space-x-0 md:mb-8 lg:mb-12">
+ <section className="mb-4 flex items-center justify-between space-x-2 sm:space-x-0">
<div className="space-y-0 sm:space-y-1">
<h2 className="text-xl font-semibold tracking-tight text-foreground sm:text-2xl">
All Documents
</h2>
- <p className="text-xs text-muted-foreground leading-4 sm:leading-none sm:text-sm">
+ <p className="text-xs leading-4 text-muted-foreground sm:text-sm sm:leading-none">
Manage all your documents in one place.
</p>
</div>
<div className="flex items-center gap-x-2">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-500" />
- <Input
- type="text"
- placeholder="Search documents..."
- className="w-64 pl-8 pr-4"
- value={searchTerm}
- onChange={(e) => setSearchTerm(e.target.value)}
- />
- </div>
<AddDocumentModal>
<Button
- className="group flex flex-1 items-center justify-start whitespace-nowrap gap-x-1 sm:gap-x-3 px-1 sm:px-3 text-left"
+ className="group flex flex-1 items-center justify-start gap-x-1 whitespace-nowrap px-1 text-left sm:gap-x-3 sm:px-3"
title="Add New Document"
>
<PlusIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
- <span className=" text-xs sm:text-base">Add New Document</span>
+ <span className="text-xs sm:text-base">Add New Document</span>
</Button>
</AddDocumentModal>
<AddFolderModal>
@@ -105,16 +54,20 @@ export default function Documents() {
</div>
</section>
+ <div className="flex justify-end">
+ <div className="relative w-full sm:max-w-xs">
+ <SearchBoxPersisted loading={isValidating} inputClassName="h-10" />
+ </div>
+ </div>
+
<section id="documents-header-count" />
<Separator className="mb-5 bg-gray-200 dark:bg-gray-800" />
<DocumentsList
- documents={displayedDocuments}
- folders={debouncedSearchTerm ? [] : folders}
+ documents={documents}
+ folders={isSearchResult ? [] : folders}
teamInfo={teamInfo}
- isLoading={isLoading}
- searchTerm={debouncedSearchTerm}
/>
</div>
</AppLayout>