Skip to content

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

feat(tags): tag support for links

Ashish Viradiyabaa1d6198e5c
diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsx
index 07a4a4a6..d895827b 100644
--- a/components/links/link-sheet/index.tsx
+++ b/components/links/link-sheet/index.tsx
@@ -42,6 +42,7 @@ import { convertDataUrlToFile, uploadImage } from "@/lib/utils";
import { CustomFieldData } from "./custom-fields-panel";
import DomainSection from "./domain-section";
import { LinkOptions } from "./link-options";
+import TagSection from "./tag/tagSection";
export const DEFAULT_LINK_PROPS = (
linkType: LinkType,
@@ -77,6 +78,7 @@ export const DEFAULT_LINK_PROPS = (
audienceType: groupId ? LinkAudienceType.GROUP : LinkAudienceType.GENERAL,
groupId: groupId,
customFields: [],
+ tags: [],
});
export type DEFAULT_LINK_TYPE = {
@@ -110,6 +112,7 @@ export type DEFAULT_LINK_TYPE = {
audienceType: LinkAudienceType;
groupId: string | null;
customFields: CustomFieldData[];
+ tags: string[];
};
export default function LinkSheet({
@@ -130,6 +133,7 @@ export default function LinkSheet({
id: string;
groupId?: string;
};
+
const { domains } = useDomains();
const {
@@ -433,6 +437,13 @@ export default function LinkSheet({
editLink={!!currentLink}
/>
</div>
+ <div className="space-y-2">
+ <TagSection
+ {...{ data, setData }}
+ editLink={!!currentLink}
+ teamId={teamInfo?.currentTeam?.id as string}
+ />
+ </div>
<div className="relative flex items-center">
<Separator className="absolute bg-muted-foreground" />
@@ -544,6 +555,13 @@ export default function LinkSheet({
editLink={!!currentLink}
/>
</div>
+ <div className="space-y-2">
+ <TagSection
+ {...{ data, setData }}
+ editLink={!!currentLink}
+ teamId={teamInfo?.currentTeam?.id as string}
+ />
+ </div>
<div className="relative flex items-center">
<Separator className="absolute bg-muted-foreground" />
diff --git a/components/links/link-sheet/tag/tagBadge.tsx b/components/links/link-sheet/tag/tagBadge.tsx
new file mode 100644
index 00000000..e76a339c
--- /dev/null
+++ b/components/links/link-sheet/tag/tagBadge.tsx
@@ -0,0 +1,99 @@
+import { Tag } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+
+import { TagColorProps } from "@/lib/types";
+import { cn } from "@/lib/utils";
+
+export default function TagBadge({
+ name,
+ color,
+ withIcon,
+ plus,
+ className,
+ isSelected,
+}: {
+ name?: string;
+ color: TagColorProps;
+ withIcon?: boolean;
+ plus?: number;
+ className?: string;
+ isSelected?: boolean;
+}) {
+ return (
+ <Button
+ size="sm"
+ variant="secondary"
+ className={cn(
+ "my-auto block cursor-pointer whitespace-nowrap !rounded-full border px-2 py-0.5 text-sm",
+ (withIcon || plus) &&
+ "flex items-center gap-x-1.5 p-1.5 sm:rounded-md sm:px-2 sm:py-0.5",
+ color === "red" && "border-red-300 bg-red-100 text-red-600",
+ color === "yellow" && "border-yellow-300 bg-yellow-100 text-yellow-600",
+ color === "green" && "border-green-300 bg-green-100 text-green-600",
+ color === "blue" && "border-blue-300 bg-blue-100 text-blue-600",
+ color === "purple" && "border-purple-300 bg-purple-100 text-purple-600",
+ color === "slate" && "border-stone-300 bg-stone-400 text-stone-600",
+ color === "fuchsia" &&
+ "border-fuchsia-300 bg-fuchsia-400 text-fuchsia-600",
+ isSelected && "border-2 bg-transparent",
+ className,
+ )}
+ >
+ {withIcon && (
+ <Tag
+ className={cn(
+ "shrink-0 p-0.5 dark:text-primary-foreground",
+ isSelected && `bg-${color}-100 rounded-sm border border-gray-200`,
+ )}
+ />
+ )}
+ {name && (
+ <p {...(withIcon && { className: "hidden sm:inline-block" })}>
+ {name || ""}
+ </p>
+ )}
+ {!!plus && (
+ <span className="hidden sm:block">
+ <span className="pr-1.5 opacity-30 md:pl-1 md:pr-2.5">|</span>+{plus}
+ </span>
+ )}
+ </Button>
+ );
+}
+
+export const COLORS_LIST: { color: TagColorProps; css: string }[] = [
+ {
+ color: "red",
+ css: "bg-red-100 text-red-600",
+ },
+ {
+ color: "yellow",
+ css: "bg-yellow-100 text-yellow-600",
+ },
+ {
+ color: "green",
+ css: "bg-green-100 text-green-600",
+ },
+ {
+ color: "blue",
+ css: "bg-blue-100 text-blue-600",
+ },
+ {
+ color: "purple",
+ css: "bg-purple-100 text-purple-600",
+ },
+ {
+ color: "slate",
+ css: "bg-slate-100 text-slate-600",
+ },
+ {
+ color: "fuchsia",
+ css: "bg-fuchsia-100 text-fuchsia-600",
+ },
+];
+
+export function randomBadgeColor() {
+ const randomIndex = Math.floor(Math.random() * COLORS_LIST.length);
+ return COLORS_LIST[randomIndex].color;
+}
diff --git a/components/links/link-sheet/tag/tagDetails.tsx b/components/links/link-sheet/tag/tagDetails.tsx
new file mode 100644
index 00000000..ac32b0d8
--- /dev/null
+++ b/components/links/link-sheet/tag/tagDetails.tsx
@@ -0,0 +1,111 @@
+import { useSearchParams } from "next/navigation";
+import { usePathname } from "next/navigation";
+import { useRouter } from "next/router";
+
+import { PropsWithChildren, useMemo, useRef } from "react";
+
+import { BadgeTooltip } from "@/components/ui/tooltip";
+
+import { LinkWithViews, TagProps } from "@/lib/types";
+
+import TagBadge from "./tagBadge";
+
+function useOrganizedTags(tags: LinkWithViews["tags"]) {
+ const searchParams = useSearchParams();
+
+ const [primaryTag, additionalTags] = useMemo(() => {
+ const filteredTagIds =
+ searchParams?.get("tagIds")?.split(",")?.filter(Boolean) ?? [];
+
+ const sortedTags =
+ filteredTagIds.length > 0
+ ? [...tags].sort(
+ (a, b) =>
+ filteredTagIds.indexOf(b.id) - filteredTagIds.indexOf(a.id),
+ )
+ : tags;
+
+ return [sortedTags?.[0], sortedTags.slice(1)];
+ }, [tags, searchParams]);
+
+ return { primaryTag, additionalTags };
+}
+
+export function TagColumn({ link }: { link: LinkWithViews }) {
+ const { tags } = link;
+
+ const ref = useRef<HTMLDivElement>(null);
+
+ const { primaryTag, additionalTags } = useOrganizedTags(tags);
+
+ return (
+ <div ref={ref} className="flex items-center gap-2 sm:gap-5">
+ {primaryTag ? (
+ <TagsTooltip additionalTags={additionalTags}>
+ <TagButton tag={primaryTag} plus={additionalTags.length} />
+ </TagsTooltip>
+ ) : (
+ <p>-</p>
+ )}
+ </div>
+ );
+}
+
+function TagsTooltip({
+ additionalTags,
+ children,
+}: PropsWithChildren<{ additionalTags: TagProps[] }>) {
+ return !!additionalTags.length ? (
+ <BadgeTooltip
+ align="end"
+ content={
+ <div className="flex flex-wrap gap-1.5 p-3">
+ {additionalTags.map((tag) => (
+ <TagButton key={tag.id} tag={tag} />
+ ))}
+ </div>
+ }
+ >
+ <div>{children}</div>
+ </BadgeTooltip>
+ ) : (
+ children
+ );
+}
+
+function TagButton({ tag, plus }: { tag: TagProps; plus?: number }) {
+ const router = useRouter();
+ const pathname = usePathname();
+ const searchParams = useSearchParams();
+
+ const selectedTagIds =
+ searchParams?.get("tagIds")?.split(",")?.filter(Boolean) ?? [];
+
+ const handleClick = () => {
+ const newTagIds = selectedTagIds.includes(tag.id)
+ ? selectedTagIds.filter((id) => id !== tag.id)
+ : [...selectedTagIds, tag.id];
+
+ const params = new URLSearchParams(searchParams?.toString());
+
+ if (newTagIds.length) {
+ params.set("tagIds", newTagIds.join(","));
+ } else {
+ params.delete("tagIds");
+ }
+
+ router.push(`${pathname}?${params.toString()}`, undefined, {
+ shallow: true,
+ });
+ };
+ return (
+ <button onClick={handleClick}>
+ <TagBadge
+ {...tag}
+ withIcon
+ plus={plus}
+ isSelected={selectedTagIds.includes(tag.id)}
+ />
+ </button>
+ );
+}
diff --git a/components/links/link-sheet/tag/tagSection.tsx b/components/links/link-sheet/tag/tagSection.tsx
new file mode 100644
index 00000000..ada9ab9b
--- /dev/null
+++ b/components/links/link-sheet/tag/tagSection.tsx
@@ -0,0 +1,138 @@
+import { useRouter } from "next/navigation";
+
+import { Dispatch, SetStateAction, useMemo, useState } from "react";
+
+import { Tag } from "lucide-react";
+import { toast } from "sonner";
+import { mutate } from "swr";
+
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import { MultiSelect } from "@/components/ui/multi-select-v2";
+
+import { useTags } from "@/lib/swr/use-tags";
+import { TagProps } from "@/lib/types";
+
+import { DEFAULT_LINK_TYPE } from "..";
+
+function getTagOption(tag: TagProps) {
+ return {
+ value: tag.id,
+ label: tag.name,
+ icon: (
+ <Tag
+ size={20}
+ className={`rounded-sm border border-gray-200 bg-${tag.color}-100 p-1 dark:text-primary-foreground`}
+ />
+ ),
+ meta: { color: tag.color, description: tag.description },
+ };
+}
+
+export default function TagSection({
+ data,
+ setData,
+ editLink,
+ teamId,
+}: {
+ data: DEFAULT_LINK_TYPE;
+ setData: Dispatch<SetStateAction<DEFAULT_LINK_TYPE>>;
+ editLink?: boolean;
+ teamId: string;
+}) {
+ const router = useRouter();
+ // TODO
+ // const [searchQuery, setSearchQuery] = useState<string>("");
+ // const [currentPage, setCurrentPage] = useState(1);
+ const [isPopoverOpen, setIsPopoverOpen] = useState(false);
+ const [selectedValues, setSelectedValues] = useState<string[]>(
+ data.tags || [],
+ );
+
+ const {
+ // tagCount,
+ tags: availableTags,
+ loading: loadingTags,
+ } = useTags({
+ query: {
+ sortBy: "createdAt",
+ sortOrder: "desc",
+ },
+ });
+
+ const options = useMemo(
+ () => availableTags?.map((tag) => getTagOption(tag)),
+ [availableTags],
+ );
+
+ // Callback to handle value change
+ const handleValueChange = (value: string[]) => {
+ setSelectedValues(value);
+ setData((prevData) => ({
+ ...prevData,
+ tags: value,
+ }));
+ };
+
+ const createTag = async (tag: string) => {
+ const res = await fetch(`/api/teams/${teamId}/tag`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ name: tag }),
+ });
+ if (!res.ok) {
+ const { error } = await res.json();
+ toast.error(error);
+ return false;
+ }
+
+ const newTag = await res.json();
+ await mutate(
+ `/api/teams/${teamId}/tag?${new URLSearchParams({
+ sortBy: "createdAt",
+ sortOrder: "desc",
+ includeLinksCount: false,
+ } as Record<string, any>).toString()}`,
+ );
+ setSelectedValues([...selectedValues, newTag.id]);
+ setData((prevData) => ({
+ ...prevData,
+ tags: [...prevData.tags, newTag.id],
+ }));
+ setIsPopoverOpen(false);
+ toast.success(`Successfully created tag!`);
+ return true;
+ };
+
+ return (
+ <>
+ <div className="flex justify-between">
+ <Label htmlFor="link-domain">Tags</Label>
+ <Button
+ variant="link"
+ className="h-auto p-0 underline"
+ type="button"
+ onClick={() => router.push("/settings/tag")}
+ >
+ Create and Manage
+ </Button>
+ </div>
+ <div className="flex">
+ <MultiSelect
+ loading={loadingTags}
+ options={options ?? []}
+ value={selectedValues}
+ setIsPopoverOpen={setIsPopoverOpen}
+ isPopoverOpen={isPopoverOpen}
+ onValueChange={handleValueChange}
+ placeholder="Select options"
+ maxCount={3}
+ searchPlaceholder="Search or create tags..."
+ onCreate={(search) => createTag(search)}
+ />
+ </div>
+ </>
+ );
+}
diff --git a/components/links/links-table.tsx b/components/links/links-table.tsx
index 9ae79768..3ccc1554 100644
--- a/components/links/links-table.tsx
+++ b/components/links/links-table.tsx
@@ -1,3 +1,4 @@
+import { useSearchParams } from "next/navigation";
import { useRouter } from "next/router";
import { useMemo, useState } from "react";
@@ -58,6 +59,7 @@ import LinkSheet, {
DEFAULT_LINK_PROPS,
type DEFAULT_LINK_TYPE,
} from "./link-sheet";
+import { TagColumn } from "./link-sheet/tag/tagDetails";
import LinksVisitors from "./links-visitors";
export default function LinksTable({
@@ -71,6 +73,11 @@ export default function LinksTable({
primaryVersion?: DocumentVersion;
mutateDocument?: () => void;
}) {
+ const searchParams = useSearchParams();
+ const selectedTagIds = useMemo(
+ () => searchParams?.get("tagIds")?.split(",")?.filter(Boolean) ?? [],
+ [searchParams],
+ );
const now = Date.now();
const router = useRouter();
const { isFree } = usePlan();
@@ -79,7 +86,7 @@ export default function LinksTable({
groupId?: string;
};
- const processedLinks = useMemo(() => {
+ let processedLinks = useMemo(() => {
if (!links?.length) return [];
const oneMinuteAgo = subMinutes(now, 1);
@@ -107,6 +114,14 @@ export default function LinksTable({
});
}, [links, now]);
+ processedLinks = useMemo(() => {
+ if (!links?.length) return [];
+ return processedLinks.filter((link) => {
+ if (selectedTagIds.length === 0) return true;
+ return link.tags.some((tag) => selectedTagIds.includes(tag.id));
+ });
+ }, [links, processedLinks, selectedTagIds]);
+
const { canAddLinks } = useLimits();
const { data: features } = useSWR<{
embedding: boolean;
@@ -170,6 +185,7 @@ export default function LinksTable({
audienceType: link.audienceType,
groupId: link.groupId,
customFields: link.customFields || [],
+ tags: link.tags.map((tag) => tag.id) || [],
});
//wait for dropdown to close before opening the link sheet
setTimeout(() => {
@@ -321,6 +337,15 @@ export default function LinksTable({
? links.filter((link) => link.isArchived).length
: 0;
+ const hasAnyTags = useMemo(
+ () =>
+ processedLinks.reduce(
+ (acc, link) => acc || (link?.tags && link.tags.length > 0),
+ false,
+ ),
+ [processedLinks],
+ );
+
return (
<>
<div className="w-full">
@@ -335,6 +360,9 @@ export default function LinksTable({
<TableHead className="w-[150px] sm:w-[200px] md:w-[250px]">
Link
</TableHead>
+ {hasAnyTags ? (
+ <TableHead className="w-[250px] 2xl:w-auto">Tags</TableHead>
+ ) : null}
<TableHead className="w-[250px] sm:w-auto">Views</TableHead>
<TableHead>Last Viewed</TableHead>
<TableHead className="text-center sm:text-right"></TableHead>
@@ -458,6 +486,11 @@ export default function LinksTable({
</Button>
</ButtonTooltip>
</TableCell>
+ {hasAnyTags ? (
+ <TableCell className="w-[250px] 2xl:w-auto">
+ <TagColumn link={link} />
+ </TableCell>
+ ) : null}
<TableCell>
<CollapsibleTrigger
disabled={
@@ -628,6 +661,11 @@ export default function LinksTable({
Link
</TableHead>
<TableHead>Views</TableHead>
+ {hasAnyTags ? (
+ <TableHead className="w-[250px] 2xl:w-auto">
+ Tags
+ </TableHead>
+ ) : null}
<TableHead>Last Viewed</TableHead>
<TableHead className="ftext-center sm:text-right"></TableHead>
</TableRow>
@@ -665,6 +703,13 @@ export default function LinksTable({
: `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`}
</div>
</TableCell>
+ {hasAnyTags ? (
+ <TableCell className="w-[250px] 2xl:w-auto">
+ <div className="flex items-center gap-x-2">
+ <TagColumn link={link} />
+ </div>
+ </TableCell>
+ ) : null}
<TableCell>
<div className="flex items-center space-x-1 [&[data-state=open]>svg.chevron]:rotate-180">
<BarChart className="h-4 w-4 text-gray-400" />
diff --git a/components/settings/settings-header.tsx b/components/settings/settings-header.tsx
index 0c157f5d..d8895cf4 100644
--- a/components/settings/settings-header.tsx
+++ b/components/settings/settings-header.tsx
@@ -53,6 +53,11 @@ export function SettingsHeader() {
href: `/settings/presets`,
segment: "presets",
},
+ {
+ label: "Tag",
+ href: `/settings/tag`,
+ segment: "tag",
+ },
{
label: "Billing",
href: `/settings/billing`,
diff --git a/components/tag/add-tag-Modal.tsx b/components/tag/add-tag-Modal.tsx
new file mode 100644
index 00000000..02fb0cc6
--- /dev/null
+++ b/components/tag/add-tag-Modal.tsx
@@ -0,0 +1,183 @@
+import { ChangeEvent, FormEventHandler, useMemo, useRef } from "react";
+
+import { PlanEnum } from "@/ee/stripe/constants";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+
+import { usePlan } from "@/lib/swr/use-billing";
+import { TagColorProps } from "@/lib/types";
+import { cn } from "@/lib/utils";
+
+import { UpgradePlanModal } from "../billing/upgrade-plan-modal";
+import { COLORS_LIST } from "../links/link-sheet/tag/tagBadge";
+import { Textarea } from "../ui/textarea";
+import { ToggleGroup, ToggleGroupItem } from "../ui/toggle-group";
+
+export function AddTagsModal({
+ open,
+ setMenuOpen,
+ children,
+ tagForm,
+ setTagForm,
+ handleSubmit,
+ tagCount = 0,
+}: {
+ tagCount: number | undefined;
+ open: boolean;
+ setMenuOpen: (open: boolean) => void;
+ children?: React.ReactNode;
+ tagForm: {
+ color: TagColorProps;
+ name: string;
+ description: string | null;
+ loading: boolean;
+ id?: string;
+ };
+ setTagForm: React.Dispatch<
+ React.SetStateAction<{
+ color: TagColorProps;
+ name: string;
+ description: string | null;
+ loading: boolean;
+ }>
+ >;
+ handleSubmit: FormEventHandler<HTMLFormElement> | undefined;
+}) {
+ const { isFree } = usePlan();
+ const initialValues = useRef(tagForm);
+
+ useMemo(() => {
+ if (tagForm.id && tagForm.id !== initialValues.current.id) {
+ initialValues.current = tagForm;
+ }
+ }, [tagForm.id]);
+
+ const hasChanged =
+ tagForm.name !== initialValues.current.name ||
+ tagForm.color !== initialValues.current.color ||
+ tagForm.description !== initialValues.current.description;
+
+ const isFormValid =
+ tagForm.name.length >= 3 && !!tagForm.color && (!tagForm.id || hasChanged);
+
+ // If the team is on a free plan and has reached the max limit of 5 tags
+ if (isFree && tagCount >= 5) {
+ if (children) {
+ return (
+ <UpgradePlanModal clickedPlan={PlanEnum.Pro} trigger={"Create_tag"}>
+ <Button>Upgrade to Create Tags</Button>
+ </UpgradePlanModal>
+ );
+ }
+ }
+
+ function handleValueChange(
+ e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
+ ): void {
+ setTagForm((prev) => ({
+ ...prev,
+ [e.target.name]: e.target.value,
+ }));
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={setMenuOpen}>
+ <DialogTrigger asChild>{children}</DialogTrigger>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader className="text-start">
+ <DialogTitle>{tagForm.id ? "Create Tag" : "Edit Tag"}</DialogTitle>
+ <DialogDescription>
+ Organize your Links with tags for easy categorization and search.
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit}>
+ <Label htmlFor="name" className="opacity-80">
+ Tag name
+ </Label>
+ <Input
+ name="name"
+ id="name"
+ value={tagForm.name}
+ placeholder="documentation"
+ className="mb-3 mt-1 w-full"
+ onChange={(e) => handleValueChange(e)}
+ />
+
+ <Label htmlFor="color" className="opacity-80">
+ Tag Color
+ </Label>
+ <ToggleGroup
+ id="color"
+ type="single"
+ value={tagForm.color}
+ onValueChange={(value: TagColorProps) => {
+ if (value) {
+ setTagForm((prev) => ({
+ ...prev,
+ color: value,
+ }));
+ }
+ }}
+ className="my-2 flex-shrink-0 flex-wrap !justify-start gap-3"
+ >
+ {COLORS_LIST.map((li) => (
+ <ToggleGroupItem
+ key={li.color}
+ value={li.color}
+ aria-label={`Select ${li.color}`}
+ className={cn(
+ "h-8 rounded-full border-0 px-3 text-sm transition-all",
+ tagForm.color === li.color
+ ? `ring-${li.color}-600 ring-2 text-${li.color}-600`
+ : `border-transparent ${li.css}`,
+ )}
+ >
+ {li.color}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+
+ <div>
+ <Label htmlFor="description" className="opacity-80">
+ Description
+ </Label>
+ <Textarea
+ value={tagForm.description || ""}
+ onChange={(e) => handleValueChange(e)}
+ rows={5}
+ name="description"
+ id="description"
+ placeholder="Add a description to understand the purpose of this tag..."
+ className="mt-1 flex-1 bg-muted"
+ autoComplete="off"
+ />
+ </div>
+ <DialogFooter>
+ <Button
+ type="submit"
+ className="mt-3 h-9 w-full"
+ disabled={!isFormValid || tagForm.loading}
+ >
+ {tagForm.loading
+ ? "Saving..."
+ : tagForm.id
+ ? "Save Changes"
+ : "Create Tag"}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/ui/multi-select-v2.tsx b/components/ui/multi-select-v2.tsx
new file mode 100644
index 00000000..3ee4a56b
--- /dev/null
+++ b/components/ui/multi-select-v2.tsx
@@ -0,0 +1,475 @@
+import * as React from "react";
+
+import { type VariantProps, cva } from "class-variance-authority";
+import {
+ CheckIcon,
+ ChevronDownIcon,
+ CircleHelpIcon,
+ PlusIcon,
+ WandSparkles,
+ XCircle,
+ XIcon,
+} from "lucide-react";
+
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+} from "@/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Separator } from "@/components/ui/separator";
+
+import { cn } from "@/lib/utils";
+
+import { Icon } from "../shared/icons";
+import LoadingSpinner from "./loading-spinner";
+import { BadgeTooltip } from "./tooltip";
+
+/**
+ * Variants for the multi-select component to handle different styles.
+ * Uses class-variance-authority (cva) to define different styles based on "variant" prop.
+ */
+const multiSelectVariants = cva(
+ "m-1 transition ease-in-out delay-150 hover:-translate-y-1 hover:scale-110 duration-300",
+ {
+ variants: {
+ variant: {
+ default:
+ "border-foreground/10 text-foreground bg-card hover:bg-card/80",
+ secondary:
+ "border-foreground/10 bg-secondary text-secondary-foreground hover:bg-secondary/80",
+ destructive:
+ "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
+ inverted: "inverted",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+);
+
+/**
+ * Props for MultiSelect component
+ */
+interface MultiSelectProps<
+ TMeta = { color: string; description: string | null },
+> extends React.ButtonHTMLAttributes<HTMLButtonElement>,
+ VariantProps<typeof multiSelectVariants> {
+ /**
+ * An array of option objects to be displayed in the multi-select component.
+ * Each option object has a label, value, and an optional icon.
+ */
+ options: ComboboxOption<TMeta>[];
+ searchPlaceholder?: string;
+ inputClassName?: string;
+ createLabel?: (search: string) => React.ReactNode;
+ onCreate?: (search: string) => Promise<boolean>;
+ optionClassName?: string;
+
+ /**
+ * Callback function triggered when the selected values change.
+ * Receives an array of the new selected values.
+ */
+ onValueChange: (value: string[]) => void;
+
+ /** The default selected values when the component mounts. */
+ defaultValue?: string[];
+
+ /** update dynamic selected values when the value change. */
+ value: string[];
+
+ /**
+ * Placeholder text to be displayed when no values are selected.
+ * Optional, defaults to "Select options".
+ */
+ placeholder?: string;
+
+ /**
+ * Animation duration in seconds for the visual effects (e.g., bouncing badges).
+ * Optional, defaults to 0 (no animation).
+ */
+ animation?: number;
+
+ /**
+ * Maximum number of items to display. Extra selected items will be summarized.
+ * Optional, defaults to 3.
+ */
+ maxCount?: number;
+
+ /**
+ * The modality of the popover. When set to true, interaction with outside elements
+ * will be disabled and only popover content will be visible to screen readers.
+ * Optional, defaults to false.
+ */
+ modalPopover?: boolean;
+
+ /**
+ * If true, renders the multi-select component as a child of another component.
+ * Optional, defaults to false.
+ */
+ asChild?: boolean;
+
+ /**
+ * Additional class names to apply custom styles to the multi-select component.
+ * Optional, can be used to add custom styles.
+ */
+ className?: string;
+ isPopoverOpen: boolean;
+ setIsPopoverOpen: React.Dispatch<React.SetStateAction<boolean>>;
+ loading?: boolean;
+}
+
+export type ComboboxOption<
+ TMeta = { color: string; description: string | null },
+> = {
+ label: string | React.ReactNode;
+ value: string;
+ icon?: Icon | React.ReactNode;
+ meta?: TMeta;
+ separatorAfter?: boolean;
+};
+
+export const MultiSelect = React.forwardRef<
+ HTMLButtonElement,
+ MultiSelectProps
+>(
+ (
+ {
+ options,
+ onValueChange,
+ variant,
+ defaultValue = [],
+ placeholder = "Select options",
+ animation = 0,
+ maxCount = 3,
+ modalPopover = false,
+ asChild = false,
+ className,
+ value,
+ searchPlaceholder = "Search...",
+ inputClassName,
+ optionClassName,
+ onCreate,
+ createLabel,
+ setIsPopoverOpen,
+ isPopoverOpen,
+ loading,
+ ...props
+ },
+ ref,
+ ) => {
+ // const [selectedValues, setSelectedValues] =
+ // React.useState<string[]>(defaultValue);
+ const [isCreating, setIsCreating] = React.useState(false);
+ const [isAnimating, setIsAnimating] = React.useState(false);
+ const [search, setSearch] = React.useState("");
+
+ const handleInputKeyDown = (
+ event: React.KeyboardEvent<HTMLInputElement>,
+ ) => {
+ if (event.key === "Enter") {
+ setIsPopoverOpen(true);
+ } else if (event.key === "Backspace" && !event.currentTarget.value) {
+ event.preventDefault();
+ event.stopPropagation();
+ const newSelectedValues = [...value];
+ newSelectedValues.pop();
+ // setSelectedValues(newSelectedValues);
+ onValueChange(newSelectedValues);
+ }
+ };
+
+ const toggleOption = (option: string) => {
+ const newSelectedValues = value.includes(option)
+ ? value.filter((value) => value !== option)
+ : [...value, option];
+ // setSelectedValues(newSelectedValues);
+ onValueChange(newSelectedValues);
+ };
+
+ const handleClear = () => {
+ // setSelectedValues([]);
+ onValueChange([]);
+ };
+
+ const handleTogglePopover = () => {
+ setIsPopoverOpen((prev) => !prev);
+ };
+
+ const clearExtraOptions = () => {
+ const newSelectedValues = value.slice(0, maxCount);
+ // setSelectedValues(newSelectedValues);
+ onValueChange(newSelectedValues);
+ };
+
+ const toggleAll = () => {
+ if (value.length === options.length) {
+ handleClear();
+ } else {
+ const allValues = options.map((option) => option.value);
+ // setSelectedValues(allValues);
+ onValueChange(allValues);
+ }
+ };
+ // flex w-full rounded-none rounded-l-md border border-input bg-white text-foreground placeholder-muted-foreground focus:border-muted-foreground focus:outline-none focus:ring-inset focus:ring-muted-foreground dark:border-gray-500 dark:bg-gray-800 focus:dark:bg-transparent sm:text-sm
+ return (
+ <Popover
+ open={isPopoverOpen}
+ onOpenChange={setIsPopoverOpen}
+ modal={modalPopover}
+ >
+ <PopoverTrigger asChild>
+ <Button
+ ref={ref}
+ {...props}
+ onClick={handleTogglePopover}
+ className={cn(
+ "flex h-auto w-full items-center justify-between rounded-md border border-input bg-inherit px-3 py-2 hover:bg-inherit focus:border-muted-foreground focus:outline-none focus:ring-1 focus:ring-inset focus:ring-muted-foreground dark:border-gray-500 dark:bg-gray-800 focus:dark:bg-transparent [&_svg]:pointer-events-auto",
+ className,
+ )}
+ >
+ {loading ? (
+ <div className="mx-auto flex w-full items-center justify-between">
+ <LoadingSpinner className="size-4 shrink-0" />
+ </div>
+ ) : value.length > 0 ? (
+ <div className="flex w-full items-center justify-between">
+ <div className="flex flex-wrap items-center">
+ {value.slice(0, maxCount).map((value) => {
+ const option = options.find((o) => o.value === value);
+ return (
+ <Badge
+ key={value}
+ className={cn(
+ isAnimating ? "animate-bounce" : "",
+ multiSelectVariants({ variant }),
+ )}
+ style={{ animationDuration: `${animation}s` }}
+ >
+ {option?.label}
+ <XCircle
+ className="ml-2 h-4 w-4 cursor-pointer"
+ onClick={(event) => {
+ event.stopPropagation();
+ toggleOption(value);
+ }}
+ />
+ </Badge>
+ );
+ })}
+ {value.length > maxCount && (
+ <Badge
+ className={cn(
+ "border-foreground/1 bg-transparent text-foreground hover:bg-transparent",
+ isAnimating ? "animate-bounce" : "",
+ multiSelectVariants({ variant }),
+ )}
+ style={{ animationDuration: `${animation}s` }}
+ >
+ {`+ ${value.length - maxCount} more`}
+ <XCircle
+ className="ml-2 h-4 w-4 cursor-pointer"
+ onClick={(event) => {
+ event.stopPropagation();
+ clearExtraOptions();
+ }}
+ />
+ </Badge>
+ )}
+ </div>
+ <div className="flex items-center justify-between">
+ <XIcon
+ className="mx-2 h-4 cursor-pointer text-muted-foreground"
+ onClick={(event) => {
+ event.stopPropagation();
+ handleClear();
+ }}
+ />
+ <Separator
+ orientation="vertical"
+ className="flex h-full min-h-6"
+ />
+ <ChevronDownIcon className="ml-2 h-4 w-4 cursor-pointer text-muted-foreground opacity-50" />
+ </div>
+ </div>
+ ) : (
+ <div className="mx-auto flex w-full items-center justify-between">
+ <span className="text-sm font-normal text-muted-foreground">
+ {placeholder}
+ </span>
+ <ChevronDownIcon className="h-4 w-4 cursor-pointer text-muted-foreground opacity-50" />
+ </div>
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ className="w-auto p-0 sm:w-[600px] sm:max-w-[35rem]"
+ align="start"
+ onEscapeKeyDown={() => setIsPopoverOpen(false)}
+ >
+ <Command>
+ <CommandInput
+ placeholder={searchPlaceholder}
+ value={search}
+ onValueChange={setSearch}
+ className={cn(
+ "grow border-0 py-3 pl-4 pr-2 outline-none placeholder:text-neutral-400 focus:ring-0 sm:text-sm",
+ inputClassName,
+ )}
+ onKeyDown={handleInputKeyDown}
+ />
+ <CommandList>
+ <CommandGroup>
+ <CommandItem
+ key="all"
+ onSelect={toggleAll}
+ className="cursor-pointer"
+ >
+ <div
+ className={cn(
+ "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
+ value.length === options?.length
+ ? "bg-primary text-primary-foreground"
+ : "opacity-50 [&_svg]:invisible",
+ )}
+ >
+ <CheckIcon className="h-4 w-4" />
+ </div>
+ <span>(Select All)</span>
+ </CommandItem>
+ </CommandGroup>
+ <CommandSeparator />
+ <CommandGroup>
+ {loading ? (
+ <CommandItem className="justify-center">
+ <LoadingSpinner className="size-4 shrink-0" />
+ </CommandItem>
+ ) : options.length > 0 ? (
+ options.map((option) => {
+ const isSelected = value.includes(option.value);
+ const IconComponent = option.icon;
+ return (
+ <CommandItem
+ key={option.value}
+ onSelect={() => toggleOption(option.value)}
+ className="cursor-pointer gap-2"
+ data-Value={option.value}
+ >
+ <div
+ className={cn(
+ "flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
+ isSelected
+ ? "bg-primary text-primary-foreground"
+ : "opacity-50 [&_svg]:invisible",
+ )}
+ >
+ <CheckIcon className="h-4 w-4" />
+ </div>
+ {IconComponent && isReactNode(IconComponent) ? (
+ IconComponent
+ ) : typeof IconComponent === "function" ? (
+ <IconComponent className="h-5 w-4" />
+ ) : null}
+ <span>{option.label}</span>
+ {option.meta?.description && (
+ <BadgeTooltip content={option.meta?.description}>
+ <CircleHelpIcon className="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" />
+ </BadgeTooltip>
+ )}
+ </CommandItem>
+ );
+ })
+ ) : (
+ <CommandItem className="justify-center">
+ <span>No tags available</span>
+ </CommandItem>
+ )}
+ </CommandGroup>
+ {search.length > 0 && onCreate && (
+ <>
+ <CommandSeparator />
+ <CommandGroup>
+ <CommandItem
+ className={cn(
+ "flex cursor-pointer items-center gap-2 whitespace-nowrap",
+ optionClassName,
+ )}
+ onSelect={async () => {
+ setIsCreating(true);
+ const success = await onCreate?.(search);
+ if (success) {
+ setSearch("");
+ setIsPopoverOpen(false);
+ }
+ setIsCreating(false);
+ }}
+ >
+ {isCreating ? (
+ <LoadingSpinner className="size-4 shrink-0" />
+ ) : (
+ <PlusIcon className="size-4 shrink-0" />
+ )}
+ <p className="grow truncate">
+ {createLabel?.(search) || `Create "${search}"`}
+ </p>
+ </CommandItem>
+ </CommandGroup>
+ </>
+ )}
+ <CommandSeparator />
+ <CommandGroup>
+ <div className="flex items-center justify-between">
+ {value.length > 0 && (
+ <>
+ <CommandItem
+ onSelect={handleClear}
+ className="flex-1 cursor-pointer justify-center"
+ >
+ Clear
+ </CommandItem>
+ <Separator
+ orientation="vertical"
+ className="flex h-full min-h-6"
+ />
+ </>
+ )}
+ <CommandItem
+ onSelect={() => setIsPopoverOpen(false)}
+ className="max-w-full flex-1 cursor-pointer justify-center"
+ >
+ Close
+ </CommandItem>
+ </div>
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ {animation > 0 && value.length > 0 && (
+ <WandSparkles
+ className={cn(
+ "my-2 h-3 w-3 cursor-pointer bg-background text-foreground",
+ isAnimating ? "" : "text-muted-foreground",
+ )}
+ onClick={() => setIsAnimating(!isAnimating)}
+ />
+ )}
+ </Popover>
+ );
+ },
+);
+
+MultiSelect.displayName = "MultiSelect";
+
+const isReactNode = (element: any): element is React.ReactNode =>
+ React.isValidElement(element);
diff --git a/components/ui/tooltip.tsx b/components/ui/tooltip.tsx
index 741b680e..16e0de2a 100644
--- a/components/ui/tooltip.tsx
+++ b/components/ui/tooltip.tsx
@@ -55,11 +55,17 @@ export const BadgeTooltip = ({
children,
linkText,
link,
+ side = "top",
+ align = "center",
+ className,
}: {
+ className?: string;
+ align?: "start" | "center" | "end";
link?: string;
- content: string;
+ content: string | React.ReactNode;
children: React.ReactNode;
linkText?: string;
+ side?: "top" | "right" | "bottom" | "left";
}) => {
return (
<Tooltip>
@@ -67,22 +73,32 @@ export const BadgeTooltip = ({
{children}
</TooltipTrigger>
<TooltipPortal>
- <TooltipContent className="max-w-72 text-center text-muted-foreground">
- {link ? (
+ <TooltipContent
+ className={cn(
+ "max-w-72 text-center text-muted-foreground",
+ className,
+ )}
+ side={side}
+ sideOffset={8}
+ align={align}
+ >
+ {typeof content === "string" ? (
<p>
{content}{" "}
- <a
- href={link}
- className="underline underline-offset-4 transition-all hover:text-gray-800 hover:dark:text-muted-foreground/80"
- target="_blank"
- rel="noopener noreferrer"
- onClick={(e) => e.stopPropagation()}
- >
- {linkText || "Learn more"}
- </a>
+ {link && (
+ <a
+ href={link}
+ className="underline underline-offset-4 transition-all hover:text-gray-800 hover:dark:text-muted-foreground/80"
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {linkText || "Learn more"}
+ </a>
+ )}
</p>
) : (
- <p>{content}</p>
+ content
)}
</TooltipContent>
</TooltipPortal>
diff --git a/lib/swr/use-tags.ts b/lib/swr/use-tags.ts
new file mode 100644
index 00000000..c8004432
--- /dev/null
+++ b/lib/swr/use-tags.ts
@@ -0,0 +1,75 @@
+import { useTeam } from "@/context/team-context";
+import useSWR from "swr";
+import { z } from "zod";
+
+import { fetcher } from "@/lib/utils";
+
+import { TagsWithTotalCount } from "../types";
+
+export const getTagsQuerySchema = z.object({
+ sortBy: z
+ .enum(["name", "createdAt"])
+ .optional()
+ .default("name")
+ .describe("The field to sort the tags by."),
+ sortOrder: z
+ .enum(["asc", "desc"])
+ .optional()
+ .default("asc")
+ .describe("The order to sort the tags by."),
+ search: z
+ .string()
+ .optional()
+ .describe("The search term to filter the tags by."),
+ page: z
+ .preprocess((val) => parseInt(val as string, 10), z.number().min(1))
+ .optional(),
+ pageSize: z
+ .preprocess(
+ (val) => parseInt(val as string, 10),
+ z.number().min(1).max(100),
+ )
+ .optional(),
+});
+
+const partialQuerySchema = getTagsQuerySchema.partial();
+
+export function useTags({
+ query,
+ enabled = true,
+ includeLinksCount = false,
+}: {
+ query?: z.infer<typeof partialQuerySchema>;
+ enabled?: boolean;
+ includeLinksCount?: boolean;
+}) {
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const {
+ data: tags,
+ isValidating,
+ error,
+ isLoading,
+ } = useSWR<TagsWithTotalCount>(
+ teamId &&
+ enabled &&
+ `/api/teams/${teamId}/tag?${new URLSearchParams({
+ ...query,
+ includeLinksCount,
+ } as Record<string, any>).toString()}`,
+ fetcher,
+ {
+ dedupingInterval: 100000,
+ },
+ );
+
+ return {
+ tags: tags?.tags,
+ tagCount: tags?.totalCount,
+ loading: tags ? false : true,
+ isValidating,
+ error,
+ isLoading,
+ };
+}
diff --git a/lib/types.ts b/lib/types.ts
index 3ed84059..bfbf7969 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -49,6 +49,7 @@ export interface LinkWithViews extends Link {
views: View[];
feedback: { id: true; data: { question: string; type: string } } | null;
customFields: CustomField[];
+ tags: TagProps[];
}
export interface LinkWithDocument extends Link {
@@ -337,3 +338,31 @@ export type BasePlan =
| "datarooms"
| "datarooms-plus"
| "enterprise";
+
+export const tagColors = [
+ "red",
+ "yellow",
+ "green",
+ "blue",
+ "purple",
+ "pink",
+ "slate",
+ "fuchsia",
+] as const;
+
+export type TagColorProps = (typeof tagColors)[number];
+
+export interface TagsWithTotalCount {
+ tags: TagProps[];
+ totalCount: number;
+}
+
+export interface TagProps {
+ id: string;
+ name: string;
+ description: string | null;
+ color: TagColorProps;
+ _count?: {
+ taggedItems: number;
+ };
+}
diff --git a/pages/api/links/[id]/archive.ts b/pages/api/links/[id]/archive.ts
index 87fcdf4b..24be9dc5 100644
--- a/pages/api/links/[id]/archive.ts
+++ b/pages/api/links/[id]/archive.ts
@@ -38,18 +38,32 @@ export default async function handle(
_count: {
select: { views: true },
},
+ taggedItems: {
+ select: {
+ tag: {
+ select: {
+ name: true,
+ description: true,
+ color: true,
+ id: true,
+ },
+ },
+ },
+ },
},
});
-
if (!updatedLink) {
return res.status(404).json({ error: "Link not found" });
}
+ const { taggedItems, ...rest } = updatedLink;
+ const tags = taggedItems.map((t) => t.tag);
+
await fetch(
`${process.env.NEXTAUTH_URL}/api/revalidate?secret=${process.env.REVALIDATE_TOKEN}&linkId=${id}&hasDomain=${updatedLink.domainId ? "true" : "false"}`,
);
- return res.status(200).json(updatedLink);
+ return res.status(200).json({ ...rest, tags });
} catch (error) {
errorhandler(error, res);
}
diff --git a/pages/api/links/[id]/duplicate.ts b/pages/api/links/[id]/duplicate.ts
index 9cea0ebc..eb81c020 100644
--- a/pages/api/links/[id]/duplicate.ts
+++ b/pages/api/links/[id]/duplicate.ts
@@ -42,27 +42,64 @@ export default async function handle(
const link = await prisma.link.findUnique({
where: { id, teamId },
+ include: {
+ taggedItems: {
+ select: {
+ tag: {
+ select: {
+ id: true,
+ },
+ },
+ },
+ },
+ },
});
if (!link) {
return res.status(404).json({ error: "Link not found" });
}
+ const { taggedItems, ...rest } = link;
+ const linkTags = taggedItems.map((t) => t.tag.id);
+
const newLinkName = link.name
? link.name + " (Copy)"
: `Link #${link.id.slice(-5)} (Copy)`;
- const newLink = await prisma.link.create({
- data: {
- ...link,
- id: undefined,
- slug: link.slug ? link.slug + "-copy" : null,
- name: newLinkName,
- watermarkConfig: link.watermarkConfig || Prisma.JsonNull,
- createdAt: undefined,
- updatedAt: undefined,
- },
- });
+ const newLink = await prisma.$transaction(async (tx) => {
+ const createdLink = await tx.link.create({
+ data: {
+ ...rest,
+ id: undefined,
+ slug: link.slug ? link.slug + "-copy" : null,
+ name: newLinkName,
+ watermarkConfig: link.watermarkConfig || Prisma.JsonNull,
+ createdAt: undefined,
+ updatedAt: undefined,
+ },
+ });
+
+ if (linkTags?.length) {
+ await tx.taggedItem.createMany({
+ data: linkTags.map((tagId: string) => ({
+ tagId,
+ itemType: "LINK",
+ linkId: createdLink.id,
+ taggedBy: (session.user as CustomUser).id,
+ })),
+ skipDuplicates: true,
+ });
+ }
+
+ const tags = linkTags?.length
+ ? await tx.tag.findMany({
+ where: { id: { in: linkTags } },
+ select: { id: true, name: true, color: true, description: true },
+ })
+ : [];
+
+ return { ...createdLink, tags };
+ });
const linkWithView = {
...newLink,
_count: { views: 0 },
diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.ts
index e0518d91..d51434db 100644
--- a/pages/api/links/[id]/index.ts
+++ b/pages/api/links/[id]/index.ts
@@ -14,6 +14,7 @@ import {
generateEncrpytedPassword,
} from "@/lib/utils";
+import { DomainObject } from "..";
import { authOptions } from "../../auth/[...nextauth]";
export default async function handle(
@@ -198,7 +199,7 @@ export default async function handle(
slug = null;
}
- let domainObj;
+ let domainObj: DomainObject | null;
if (domain && slug) {
domainObj = await prisma.domain.findUnique({
@@ -245,88 +246,135 @@ export default async function handle(
});
}
- // Update the link in the database
- const updatedLink = await prisma.link.update({
- where: { id, teamId },
- data: {
- documentId: documentLink ? targetId : null,
- dataroomId: dataroomLink ? targetId : null,
- password: hashedPassword,
- name: linkData.name || null,
- emailProtected:
- linkData.audienceType === LinkAudienceType.GROUP
- ? true
- : linkData.emailProtected,
- emailAuthenticated: linkData.emailAuthenticated,
- allowDownload: linkData.allowDownload,
- allowList: linkData.allowList,
- denyList: linkData.denyList,
- expiresAt: exat,
- domainId: domainObj?.id || null,
- domainSlug: domain || null,
- slug: slug || null,
- enableNotification: linkData.enableNotification,
- enableFeedback: linkData.enableFeedback,
- enableScreenshotProtection: linkData.enableScreenshotProtection,
- enableCustomMetatag: linkData.enableCustomMetatag,
- metaTitle: linkData.metaTitle || null,
- metaDescription: linkData.metaDescription || null,
- metaImage: linkData.metaImage || null,
- metaFavicon: linkData.metaFavicon || null,
- ...(linkData.customFields && {
- customFields: {
- deleteMany: {}, // Delete all existing custom fields
- createMany: {
- data: linkData.customFields.map((field: any, index: number) => ({
- type: field.type,
- identifier: field.identifier,
- label: field.label,
- placeholder: field.placeholder,
- required: field.required,
- disabled: field.disabled,
- orderIndex: index,
- })),
- skipDuplicates: true,
+ const updatedLink = await prisma.$transaction(async (tx) => {
+ const link = await tx.link.update({
+ where: { id, teamId },
+ data: {
+ documentId: documentLink ? targetId : null,
+ dataroomId: dataroomLink ? targetId : null,
+ password: hashedPassword,
+ name: linkData.name || null,
+ emailProtected:
+ linkData.audienceType === LinkAudienceType.GROUP
+ ? true
+ : linkData.emailProtected,
+ emailAuthenticated: linkData.emailAuthenticated,
+ allowDownload: linkData.allowDownload,
+ allowList: linkData.allowList,
+ denyList: linkData.denyList,
+ expiresAt: exat,
+ domainId: domainObj?.id || null,
+ domainSlug: domain || null,
+ slug: slug || null,
+ enableNotification: linkData.enableNotification,
+ enableFeedback: linkData.enableFeedback,
+ enableScreenshotProtection: linkData.enableScreenshotProtection,
+ enableCustomMetatag: linkData.enableCustomMetatag,
+ metaTitle: linkData.metaTitle || null,
+ metaDescription: linkData.metaDescription || null,
+ metaImage: linkData.metaImage || null,
+ metaFavicon: linkData.metaFavicon || null,
+ ...(linkData.customFields && {
+ customFields: {
+ deleteMany: {}, // Delete all existing custom fields
+ createMany: {
+ data: linkData.customFields.map(
+ (field: any, index: number) => ({
+ type: field.type,
+ identifier: field.identifier,
+ label: field.label,
+ placeholder: field.placeholder,
+ required: field.required,
+ disabled: field.disabled,
+ orderIndex: index,
+ }),
+ ),
+ skipDuplicates: true,
+ },
},
- },
- }),
- enableQuestion: linkData.enableQuestion,
- ...(linkData.enableQuestion && {
- feedback: {
- upsert: {
- create: {
- data: {
- question: linkData.questionText,
- type: linkData.questionType,
+ }),
+ enableQuestion: linkData.enableQuestion,
+ ...(linkData.enableQuestion && {
+ feedback: {
+ upsert: {
+ create: {
+ data: {
+ question: linkData.questionText,
+ type: linkData.questionType,
+ },
},
- },
- update: {
- data: {
- question: linkData.questionText,
- type: linkData.questionType,
+ update: {
+ data: {
+ question: linkData.questionText,
+ type: linkData.questionType,
+ },
},
},
},
+ }),
+ enableAgreement: linkData.enableAgreement,
+ agreementId: linkData.agreementId || null,
+ showBanner: linkData.showBanner,
+ enableWatermark: linkData.enableWatermark || false,
+ watermarkConfig: linkData.watermarkConfig || null,
+ groupId: linkData.groupId || null,
+ audienceType: linkData.audienceType || LinkAudienceType.GENERAL,
+ },
+ include: {
+ views: {
+ orderBy: {
+ viewedAt: "desc",
+ },
},
- }),
- enableAgreement: linkData.enableAgreement,
- agreementId: linkData.agreementId || null,
- showBanner: linkData.showBanner,
- enableWatermark: linkData.enableWatermark || false,
- watermarkConfig: linkData.watermarkConfig || null,
- groupId: linkData.groupId || null,
- audienceType: linkData.audienceType || LinkAudienceType.GENERAL,
- },
- include: {
- views: {
- orderBy: {
- viewedAt: "desc",
+ _count: {
+ select: { views: true },
+ },
+ },
+ });
+ if (linkData.tags?.length) {
+ // Remove only tags that are not in the new list
+ await tx.taggedItem.deleteMany({
+ where: {
+ linkId: id,
+ itemType: "LINK",
+ tagId: { notIn: linkData.tags },
+ },
+ });
+
+ // Add new tags while avoiding duplicates
+ await tx.taggedItem.createMany({
+ data: linkData.tags.map((tagId: string) => ({
+ tagId,
+ itemType: "LINK",
+ linkId: id,
+ taggedBy: userId,
+ })),
+ skipDuplicates: true,
+ });
+ } else {
+ // If all tags are removed, delete all tagged items for this link
+ await tx.taggedItem.deleteMany({
+ where: {
+ linkId: id,
+ itemType: "LINK",
+ },
+ });
+ }
+ const tags = await tx.tag.findMany({
+ where: {
+ taggedItems: {
+ some: { linkId: link.id },
},
},
- _count: {
- select: { views: true },
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ description: true,
},
- },
+ });
+
+ return { ...link, tags };
});
if (!updatedLink) {
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index 0615279e..e5190bcb 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -13,6 +13,11 @@ import {
import { authOptions } from "../auth/[...nextauth]";
+export interface DomainObject {
+ id: string;
+ slug: string;
+}
+
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
@@ -66,7 +71,7 @@ export default async function handler(
slug = null;
}
- let domainObj;
+ let domainObj: DomainObject | null;
if (domain && slug) {
domainObj = await prisma.domain.findUnique({
@@ -111,81 +116,104 @@ export default async function handler(
}
// Fetch the link and its related document from the database
- const link = await prisma.link.create({
- data: {
- documentId: documentLink ? targetId : null,
- dataroomId: dataroomLink ? targetId : null,
- linkType,
- teamId,
- password: hashedPassword,
- name: linkData.name || null,
- emailProtected:
- linkData.audienceType === LinkAudienceType.GROUP
- ? true
- : linkData.emailProtected,
- emailAuthenticated: linkData.emailAuthenticated,
- expiresAt: exat,
- allowDownload: linkData.allowDownload,
- domainId: domainObj?.id || null,
- domainSlug: domain || null,
- slug: slug || null,
- enableNotification: linkData.enableNotification,
- enableFeedback: linkData.enableFeedback,
- enableScreenshotProtection: linkData.enableScreenshotProtection,
- enableCustomMetatag: linkData.enableCustomMetatag,
- metaTitle: linkData.metaTitle || null,
- metaDescription: linkData.metaDescription || null,
- metaImage: linkData.metaImage || null,
- metaFavicon: linkData.metaFavicon || null,
- allowList: linkData.allowList,
- denyList: linkData.denyList,
- audienceType: linkData.audienceType,
- groupId:
- linkData.audienceType === LinkAudienceType.GROUP
- ? linkData.groupId
- : null,
- ...(linkData.enableQuestion && {
- enableQuestion: linkData.enableQuestion,
- feedback: {
- create: {
- data: {
- question: linkData.questionText,
- type: linkData.questionType,
+ const updatedLink = await prisma.$transaction(async (tx) => {
+ const link = await tx.link.create({
+ data: {
+ documentId: documentLink ? targetId : null,
+ dataroomId: dataroomLink ? targetId : null,
+ linkType,
+ teamId,
+ password: hashedPassword,
+ name: linkData.name || null,
+ emailProtected:
+ linkData.audienceType === LinkAudienceType.GROUP
+ ? true
+ : linkData.emailProtected,
+ emailAuthenticated: linkData.emailAuthenticated,
+ expiresAt: exat,
+ allowDownload: linkData.allowDownload,
+ domainId: domainObj?.id || null,
+ domainSlug: domain || null,
+ slug: slug || null,
+ enableNotification: linkData.enableNotification,
+ enableFeedback: linkData.enableFeedback,
+ enableScreenshotProtection: linkData.enableScreenshotProtection,
+ enableCustomMetatag: linkData.enableCustomMetatag,
+ metaTitle: linkData.metaTitle || null,
+ metaDescription: linkData.metaDescription || null,
+ metaImage: linkData.metaImage || null,
+ metaFavicon: linkData.metaFavicon || null,
+ allowList: linkData.allowList,
+ denyList: linkData.denyList,
+ audienceType: linkData.audienceType,
+ groupId:
+ linkData.audienceType === LinkAudienceType.GROUP
+ ? linkData.groupId
+ : null,
+ ...(linkData.enableQuestion && {
+ enableQuestion: linkData.enableQuestion,
+ feedback: {
+ create: {
+ data: {
+ question: linkData.questionText,
+ type: linkData.questionType,
+ },
},
},
- },
- }),
- ...(linkData.enableAgreement && {
- enableAgreement: linkData.enableAgreement,
- agreementId: linkData.agreementId,
- }),
- ...(linkData.enableWatermark && {
- enableWatermark: linkData.enableWatermark,
- watermarkConfig: linkData.watermarkConfig,
- }),
- showBanner: linkData.showBanner,
- ...(linkData.customFields && {
- customFields: {
- createMany: {
- data: linkData.customFields.map(
- (field: any, index: number) => ({
- type: field.type,
- identifier: field.identifier,
- label: field.label,
- placeholder: field.placeholder,
- required: field.required,
- disabled: field.disabled,
- orderIndex: index,
- }),
- ),
+ }),
+ ...(linkData.enableAgreement && {
+ enableAgreement: linkData.enableAgreement,
+ agreementId: linkData.agreementId,
+ }),
+ ...(linkData.enableWatermark && {
+ enableWatermark: linkData.enableWatermark,
+ watermarkConfig: linkData.watermarkConfig,
+ }),
+ showBanner: linkData.showBanner,
+ ...(linkData.customFields && {
+ customFields: {
+ createMany: {
+ data: linkData.customFields.map(
+ (field: any, index: number) => ({
+ type: field.type,
+ identifier: field.identifier,
+ label: field.label,
+ placeholder: field.placeholder,
+ required: field.required,
+ disabled: field.disabled,
+ orderIndex: index,
+ }),
+ ),
+ },
},
- },
- }),
- },
+ }),
+ },
+ });
+
+ if (linkData.tags?.length) {
+ await tx.taggedItem.createMany({
+ data: linkData.tags.map((tagId: string) => ({
+ tagId,
+ itemType: "LINK",
+ linkId: link.id,
+ taggedBy: userId,
+ })),
+ skipDuplicates: true,
+ });
+ }
+
+ const tags = linkData.tags?.length
+ ? await tx.tag.findMany({
+ where: { id: { in: linkData.tags } },
+ select: { id: true, name: true, color: true, description: true },
+ })
+ : [];
+
+ return { ...link, tags };
});
const linkWithView = {
- ...link,
+ ...updatedLink,
_count: { views: 0 },
views: [],
};
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/links.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/links.ts
index 4878dcd4..688db22b 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/links.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/links.ts
@@ -5,7 +5,6 @@ import { getServerSession } from "next-auth/next";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
-import { getTeamWithUsersAndDocument } from "@/lib/team/helper";
import { CustomUser } from "@/lib/types";
import { decryptEncrpytedPassword, log } from "@/lib/utils";
@@ -50,7 +49,7 @@ export default async function handle(
return res.status(403).end("Unauthorized to access this team");
}
- const links = await prisma.link.findMany({
+ let links = await prisma.link.findMany({
where: {
groupId: groupId,
dataroomId: dataroomId,
@@ -77,11 +76,36 @@ export default async function handle(
});
// Decrypt the password for each link
- links.forEach((link) => {
- if (link.password !== null) {
- link.password = decryptEncrpytedPassword(link.password);
- }
- });
+ if (links && links.length > 0) {
+ links = await Promise.all(
+ links.map(async (link) => {
+ // Decrypt the password if it exists
+ if (link.password !== null) {
+ link.password = decryptEncrpytedPassword(link.password);
+ }
+ const tags = await prisma.tag.findMany({
+ where: {
+ taggedItems: {
+ some: {
+ linkId: link.id,
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ description: true,
+ },
+ });
+
+ return {
+ ...link,
+ ["tags"]: tags,
+ };
+ }),
+ );
+ }
return res.status(200).json(links);
} catch (error) {
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/links.ts b/pages/api/teams/[teamId]/datarooms/[id]/links.ts
index 8067f569..ccc8c69d 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/links.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/links.ts
@@ -4,7 +4,6 @@ import { getServerSession } from "next-auth/next";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
-import { getTeamWithUsersAndDocument } from "@/lib/team/helper";
import { CustomUser } from "@/lib/types";
import { decryptEncrpytedPassword, log } from "@/lib/utils";
@@ -45,7 +44,7 @@ export default async function handle(
return res.status(401).end("Unauthorized");
}
- const links = await prisma.link.findMany({
+ let links = await prisma.link.findMany({
where: {
dataroomId,
linkType: "DATAROOM_LINK",
@@ -70,11 +69,36 @@ export default async function handle(
});
// Decrypt the password for each link
- links.forEach((link) => {
- if (link.password !== null) {
- link.password = decryptEncrpytedPassword(link.password);
- }
- });
+ if (links && links.length > 0) {
+ links = await Promise.all(
+ links.map(async (link) => {
+ // Decrypt the password if it exists
+ if (link.password !== null) {
+ link.password = decryptEncrpytedPassword(link.password);
+ }
+ const tags = await prisma.tag.findMany({
+ where: {
+ taggedItems: {
+ some: {
+ linkId: link.id,
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ description: true,
+ },
+ });
+
+ return {
+ ...link,
+ ["tags"]: tags,
+ };
+ }),
+ );
+ }
return res.status(200).json(links);
} catch (error) {
diff --git a/pages/api/teams/[teamId]/documents/[id]/advanced-mode.ts b/pages/api/teams/[teamId]/documents/[id]/advanced-mode.ts
index 8fe68add..971022c0 100644
--- a/pages/api/teams/[teamId]/documents/[id]/advanced-mode.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/advanced-mode.ts
@@ -1,15 +1,11 @@
import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
-import { DocumentStorageType } from "@prisma/client";
-import { waitUntil } from "@vercel/functions";
import { getServerSession } from "next-auth/next";
-import { version } from "os";
import { errorhandler } from "@/lib/errorHandler";
import { copyFileToBucketServer } from "@/lib/files/copy-file-to-bucket-server";
import prisma from "@/lib/prisma";
-import { getTeamWithUsersAndDocument } from "@/lib/team/helper";
import { CustomUser } from "@/lib/types";
export default async function handle(
diff --git a/pages/api/teams/[teamId]/documents/[id]/change-orientation.ts b/pages/api/teams/[teamId]/documents/[id]/change-orientation.ts
index 59ff3320..e8e6ba26 100644
--- a/pages/api/teams/[teamId]/documents/[id]/change-orientation.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/change-orientation.ts
@@ -6,7 +6,6 @@ import { version } from "os";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
-import { getTeamWithUsersAndDocument } from "@/lib/team/helper";
import { CustomUser } from "@/lib/types";
export default async function handle(
diff --git a/pages/api/teams/[teamId]/documents/[id]/links.ts b/pages/api/teams/[teamId]/documents/[id]/links.ts
index 6c5e541b..d2ea6d67 100644
--- a/pages/api/teams/[teamId]/documents/[id]/links.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/links.ts
@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
import { getTeamWithUsersAndDocument } from "@/lib/team/helper";
import { CustomUser } from "@/lib/types";
import { decryptEncrpytedPassword, log } from "@/lib/utils";
@@ -72,14 +73,39 @@ export default async function handle(
},
});
- const links = document!.links;
+ let links = document!.links;
// Decrypt the password for each link
- links?.forEach((link) => {
- if (link.password !== null) {
- link.password = decryptEncrpytedPassword(link.password);
- }
- });
+ if (links && links.length > 0) {
+ links = await Promise.all(
+ links.map(async (link) => {
+ // Decrypt the password if it exists
+ if (link.password !== null) {
+ link.password = decryptEncrpytedPassword(link.password);
+ }
+ const tags = await prisma.tag.findMany({
+ where: {
+ taggedItems: {
+ some: {
+ linkId: link.id,
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ description: true,
+ },
+ });
+
+ return {
+ ...link,
+ ["tags"]: tags,
+ };
+ }),
+ );
+ }
return res.status(200).json(links);
} catch (error) {
diff --git a/pages/api/teams/[teamId]/tag/[tagId]/index.tsx b/pages/api/teams/[teamId]/tag/[tagId]/index.tsx
new file mode 100644
index 00000000..1f64ba24
--- /dev/null
+++ b/pages/api/teams/[teamId]/tag/[tagId]/index.tsx
@@ -0,0 +1,120 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth";
+
+import { errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+import { createTagBodySchema } from "..";
+
+const updateTagBodySchema = createTagBodySchema;
+
+export const config = {
+ api: {
+ bodyParser: {
+ sizeLimit: "4mb",
+ },
+ },
+};
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId } = req.query as { teamId: string };
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ },
+ select: {
+ id: true,
+ users: { select: { userId: true } },
+ },
+ });
+
+ // check that the user is member of the team, otherwise return 403
+ const teamUsers = team?.users;
+ const isUserPartOfTeam = teamUsers?.some(
+ (user) => user.userId === (session.user as CustomUser).id,
+ );
+ if (!isUserPartOfTeam) {
+ return res.status(403).end("Unauthorized to access this team");
+ }
+ } catch (error) {
+ errorhandler(error, res);
+ }
+ if (req.method === "PUT") {
+ // PUT /api/teams/:teamId/tag/[tagId]
+
+ const { teamId, tagId } = req.query as { teamId: string; tagId: string };
+ const {
+ name,
+ color,
+ description = "",
+ } = updateTagBodySchema.parse(req.body);
+ const tag = await prisma.tag.findFirst({
+ where: {
+ id: tagId,
+ teamId: teamId,
+ },
+ });
+
+ if (!tag) {
+ return res.status(404).json({ error: "Tag not found." });
+ }
+ try {
+ const response = await prisma.tag.update({
+ where: {
+ id: tagId,
+ },
+ data: {
+ name,
+ color,
+ description,
+ },
+ });
+
+ return res.status(200).json(response);
+ } catch (error) {
+ return res.status(500).json({ error: (error as Error).message });
+ }
+ } else if (req.method === "DELETE") {
+ // DELETE /api/teams/:teamId/tag/[tagId]
+ const { teamId, tagId } = req.query as { teamId: string; tagId: string };
+ // First verify the tag belongs to the team
+ const tag = await prisma.tag.findFirst({
+ where: {
+ id: tagId,
+ teamId: teamId,
+ },
+ });
+
+ if (!tag) {
+ return res.status(404).json({ error: "Tag not found" });
+ }
+
+ // Then delete the tag
+ await prisma.tag.delete({
+ where: {
+ id: tagId,
+ },
+ include: {
+ taggedItems: true,
+ },
+ });
+ return res.status(204).end();
+ } else {
+ // We only allow GET and DELETE requests
+ res.setHeader("Allow", ["PUT", "DELETE"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/api/teams/[teamId]/tag/index.ts b/pages/api/teams/[teamId]/tag/index.ts
new file mode 100644
index 00000000..9c50bbbd
--- /dev/null
+++ b/pages/api/teams/[teamId]/tag/index.ts
@@ -0,0 +1,206 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth";
+import { z } from "zod";
+
+import {
+ COLORS_LIST,
+ randomBadgeColor,
+} from "@/components/links/link-sheet/tag/tagBadge";
+
+import { errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import { CustomUser, tagColors } from "@/lib/types";
+
+export const config = {
+ api: {
+ bodyParser: {
+ sizeLimit: "4mb",
+ },
+ },
+};
+
+export const searchParamsSchema = z.object({
+ sortBy: z
+ .enum(["name", "createdAt"])
+ .optional()
+ .default("name")
+ .describe("The field to sort the tags by."),
+ sortOrder: z
+ .enum(["asc", "desc"])
+ .optional()
+ .default("asc")
+ .describe("The order to sort the tags by."),
+ search: z
+ .string()
+ .optional()
+ .describe("The search term to filter the tags by."),
+ includeLinksCount: z
+ .preprocess((val) => val === "true", z.boolean())
+ .optional(),
+ page: z
+ .preprocess((val) => parseInt(val as string, 10), z.number().min(1))
+ .optional(),
+ pageSize: z
+ .preprocess(
+ (val) => parseInt(val as string, 10),
+ z.number().min(1).max(100),
+ )
+ .optional(),
+});
+
+export const tagColorSchema = z
+ .enum(tagColors, {
+ errorMap: () => {
+ return {
+ message: `Invalid color. Must be one of: ${tagColors.join(", ")}`,
+ };
+ },
+ })
+ .describe("The color of the tag");
+
+export const createTagBodySchema = z
+ .object({
+ name: z
+ .string()
+ .trim()
+ .min(3)
+ .max(50)
+ .describe("The name of the tag to create."),
+ color: tagColorSchema.describe(
+ `The color of the tag. If not provided, a random color will be used from the list: ${tagColors.join(", ")}.`,
+ ),
+ description: z
+ .string()
+ .trim()
+ .max(120)
+ .optional()
+ .describe("The description of the tag to create."),
+ })
+ .partial()
+ .superRefine((data, ctx) => {
+ if (!data.name) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["name"],
+ message: "Name is required.",
+ });
+ }
+ });
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId } = req.query as { teamId: string };
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ },
+ select: {
+ id: true,
+ users: { select: { userId: true } },
+ },
+ });
+
+ // check that the user is member of the team, otherwise return 403
+ const teamUsers = team?.users;
+ const isUserPartOfTeam = teamUsers?.some(
+ (user) => user.userId === (session.user as CustomUser).id,
+ );
+ if (!isUserPartOfTeam) {
+ return res.status(403).end("Unauthorized to access this team");
+ }
+ } catch (error) {
+ errorhandler(error, res);
+ }
+ if (req.method === "GET") {
+ // GET /api/teams/:teamId/tag
+
+ const { search, includeLinksCount, sortBy, sortOrder, pageSize, page } =
+ searchParamsSchema.parse(req.query);
+
+ const whereCondition = {
+ teamId: teamId,
+ ...(search && {
+ name: {
+ contains: search,
+ },
+ }),
+ };
+
+ const [tags, totalCount] = await prisma.$transaction([
+ prisma.tag.findMany({
+ where: whereCondition,
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ description: true,
+ ...(includeLinksCount && {
+ _count: {
+ select: {
+ taggedItems: true,
+ },
+ },
+ }),
+ },
+ orderBy: {
+ [sortBy]: sortOrder,
+ },
+ ...(pageSize &&
+ page && {
+ take: pageSize,
+ skip: (page - 1) * pageSize,
+ }),
+ }),
+ prisma.tag.count({ where: whereCondition }),
+ ]);
+
+ if (!tags) {
+ return res.status(200).json({ tags: null, totalCount: 0 });
+ }
+
+ return res.status(200).json({ tags, totalCount });
+ } else if (req.method === "POST") {
+ // POST /api/teams/:teamId/tag
+
+ const { color, name, description } = createTagBodySchema.parse(req.body);
+
+ const existingTag = await prisma.tag.findFirst({
+ where: {
+ teamId: teamId,
+ name: name,
+ },
+ });
+ if (existingTag) {
+ return res.status(400).json({
+ error: "A tag with that name already exists.",
+ });
+ }
+ const response = await prisma.tag.create({
+ data: {
+ name: name!,
+ color:
+ color && COLORS_LIST.map(({ color }) => color).includes(color)
+ ? color
+ : randomBadgeColor(),
+ teamId: teamId,
+ description: description,
+ },
+ });
+ return res.status(200).json(response);
+ } else {
+ // We only allow GET and DELETE requests
+ res.setHeader("Allow", ["GET", "POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/settings/tag.tsx b/pages/settings/tag.tsx
new file mode 100644
index 00000000..3d3adc10
--- /dev/null
+++ b/pages/settings/tag.tsx
@@ -0,0 +1,455 @@
+import { useRouter } from "next/router";
+
+import { useEffect, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import {
+ CircleHelpIcon,
+ MoreHorizontalIcon,
+ Settings2Icon,
+ Tag,
+ TrashIcon,
+} from "lucide-react";
+import { toast } from "sonner";
+import { mutate } from "swr";
+import { z } from "zod";
+
+import AppLayout from "@/components/layouts/app";
+import { randomBadgeColor } from "@/components/links/link-sheet/tag/tagBadge";
+import { SearchBoxPersisted } from "@/components/search-box";
+import { SettingsHeader } from "@/components/settings/settings-header";
+import { AddTagsModal } from "@/components/tag/add-tag-Modal";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Pagination,
+ PaginationContent,
+ PaginationItem,
+ PaginationLink,
+ PaginationNext,
+ PaginationPrevious,
+} from "@/components/ui/pagination";
+import { Skeleton } from "@/components/ui/skeleton";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { BadgeTooltip } from "@/components/ui/tooltip";
+
+import { useTags } from "@/lib/swr/use-tags";
+import {
+ TagColorProps,
+ TagProps,
+ TagsWithTotalCount,
+ tagColors,
+} from "@/lib/types";
+
+const schema = z.object({
+ name: z
+ .string()
+ .trim()
+ .min(3)
+ .max(50)
+ .describe("The name of the tag to create."),
+ description: z
+ .string()
+ .trim()
+ .max(120)
+ .optional()
+ .describe("The description of the tag to create."),
+ color: z.enum(tagColors, {
+ required_error: "Please select a color for the tag",
+ }),
+});
+
+const defaultValue = {
+ name: "",
+ description: "",
+ color: randomBadgeColor(),
+ loading: false,
+};
+export default function TagSetting() {
+ const [open, setOpen] = useState(false);
+ const teamInfo = useTeam();
+ const router = useRouter();
+ const [currentPage, setCurrentPage] = useState(1);
+ const queryParams = router.query;
+ const searchQuery = queryParams["search"];
+ const teamId = teamInfo?.currentTeam?.id;
+ const [tagForm, setTagForm] = useState<{
+ color: TagColorProps;
+ name: string;
+ description: string | null;
+ loading: boolean;
+ id?: string;
+ }>(defaultValue);
+
+ useEffect(() => {
+ if (open && !tagForm.id) {
+ setTagForm((prev) => ({ ...prev, color: randomBadgeColor() }));
+ }
+ }, [open]);
+
+ const {
+ tagCount,
+ tags: availableTags,
+ loading: loadingTags,
+ isValidating,
+ } = useTags({
+ query: {
+ sortBy: "createdAt",
+ sortOrder: "desc",
+ page: currentPage,
+ pageSize: 10,
+ ...(searchQuery ? { search: String(searchQuery) } : {}),
+ },
+ includeLinksCount: true,
+ });
+
+ const handleDeleteTag = async (tagId: string) => {
+ toast.promise(
+ fetch(`/api/teams/${teamId}/tag/${tagId}`, {
+ method: "DELETE",
+ }).then(() => {
+ mutate(
+ `/api/teams/${teamId}/tag?${new URLSearchParams({
+ sortBy: "createdAt",
+ sortOrder: "desc",
+ page: currentPage,
+ pageSize: 10,
+ ...(searchQuery ? { search: String(searchQuery) } : {}),
+ includeLinksCount: true,
+ } as Record<string, any>).toString()}`,
+ null,
+ {
+ populateCache: (_, tags: TagsWithTotalCount | undefined) => {
+ if (!tags) return { tags: [], totalCount: 0 };
+
+ return {
+ tags: tags.tags.filter((tag) => tag.id !== tagId),
+ totalCount: tags.totalCount > 0 ? tags.totalCount - 1 : 0,
+ };
+ },
+ revalidate: false,
+ },
+ );
+ }),
+ {
+ loading: "Deleting tag...",
+ success: "Tag deleted successfully!",
+ error: "Failed to delete Tag. Try again.",
+ },
+ );
+ };
+
+ const handleSubmit = async (event: React.FormEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+
+ const validation = schema.safeParse({
+ name: tagForm.name,
+ description: tagForm.description,
+ color: tagForm.color,
+ });
+
+ if (!validation.success) {
+ return toast.error(validation.error.errors[0].message);
+ }
+
+ setTagForm((prev) => ({
+ ...prev,
+ loading: true,
+ }));
+
+ const url = tagForm.id
+ ? `/api/teams/${teamId}/tag/${tagForm.id}`
+ : `/api/teams/${teamId}/tag`;
+
+ const method = tagForm.id ? "PUT" : "POST";
+
+ const response = await fetch(url, {
+ method,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ name: tagForm.name,
+ color: tagForm.color,
+ description: tagForm.description,
+ }),
+ });
+
+ if (!response.ok) {
+ const { error } = await response.json();
+ toast.error(error);
+ setTagForm((prev) => ({
+ ...prev,
+ name: "",
+ loading: false,
+ }));
+ return;
+ }
+ const newTag = await response.json();
+
+ mutate(
+ `/api/teams/${teamId}/tag?${new URLSearchParams({
+ sortBy: "createdAt",
+ sortOrder: "desc",
+ page: currentPage,
+ pageSize: 10,
+ ...(searchQuery ? { search: String(searchQuery) } : {}),
+ includeLinksCount: true,
+ } as Record<string, any>).toString()}`,
+ (tags: TagsWithTotalCount | undefined) => {
+ if (!tags?.tags) return { tags: [newTag], totalCount: 1 };
+
+ const updatedTags: TagProps[] = tagForm.id
+ ? tags.tags.map((tag: TagProps) =>
+ tag.id === tagForm.id ? newTag : tag,
+ )
+ : [newTag, ...tags.tags];
+
+ return {
+ tags: updatedTags,
+ totalCount: tagForm.id ? tags.totalCount : tags.totalCount + 1,
+ };
+ },
+ {
+ revalidate: false,
+ },
+ );
+ setOpen(false);
+ toast.success(
+ tagForm.id ? "Tag updated successfully!" : "Tag created successfully!",
+ );
+ };
+
+ const setMenuOpen = (open: boolean) => {
+ setOpen(open);
+ setTagForm(defaultValue);
+ };
+
+ return (
+ <AppLayout>
+ <main className="mx-2 mb-10 mt-4 space-y-8 px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <SettingsHeader />
+ <div>
+ <div className="space-y-1">
+ <h3 className="text-2xl font-semibold">Tags</h3>
+
+ <p className="flex items-center gap-2 text-sm text-muted-foreground">
+ Manage and categorize your tags here.
+ </p>
+ </div>
+ <div className="my-4 flex items-center justify-between">
+ <SearchBoxPersisted loading={isValidating} inputClassName="h-10" />
+ <AddTagsModal
+ open={open}
+ setMenuOpen={setMenuOpen}
+ tagForm={tagForm}
+ setTagForm={setTagForm}
+ handleSubmit={handleSubmit}
+ tagCount={tagCount}
+ >
+ <Button>Create Tag</Button>
+ </AddTagsModal>
+ </div>
+ <div className="rounded-md border">
+ <Table>
+ <TableHeader>
+ <TableRow className="*:whitespace-nowrap *:font-medium hover:bg-transparent">
+ <TableHead>Tag Name</TableHead>
+ <TableHead></TableHead>
+ <TableHead className="text-center sm:text-right">
+ Action
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {tagCount === 0 && !loadingTags && (
+ <TableRow>
+ <TableCell colSpan={5}>
+ <div className="flex h-40 w-full items-center justify-center">
+ <p>No Tags Available</p>
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ {availableTags && !loadingTags ? (
+ availableTags.map((tag) => {
+ return (
+ <>
+ <TableRow key={tag.id} className="group/row">
+ {/* Name */}
+ <TableCell>
+ <div className="flex items-center overflow-visible sm:space-x-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <Tag
+ size={24}
+ className={`rounded-sm border border-gray-200 dark:text-primary-foreground bg-${tag.color}-100 p-1`}
+ />
+ <p>{tag.name}</p>
+ {!!tag.description && (
+ <BadgeTooltip
+ content={tag.description}
+ key="tag_tooltip"
+ >
+ <CircleHelpIcon className="h-4 w-4 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground" />
+ </BadgeTooltip>
+ )}
+ </div>
+ </div>
+ </div>
+ </TableCell>
+ {/* Link Count */}
+ <TableCell className="text-center text-sm text-muted-foreground sm:text-right">
+ <Button variant="outline" size="sm">
+ {tag._count?.taggedItems || 0} links
+ </Button>
+ </TableCell>
+
+ {/* Actions */}
+ <TableCell className="text-center sm:text-right">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ className="h-8 w-8 p-0 group-hover/row:ring-1 group-hover/row:ring-gray-200 group-hover/row:dark:ring-gray-700"
+ >
+ <span className="sr-only">Open menu</span>
+ <MoreHorizontalIcon className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ setTagForm({
+ color: tag.color,
+ name: tag.name,
+ description: tag.description,
+ id: tag.id,
+ loading: false,
+ });
+ setOpen(true);
+ }}
+ >
+ <Settings2Icon className="mr-2 h-4 w-4" />
+ Edit tag
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ className="text-destructive transition-colors duration-200 focus:bg-destructive focus:text-destructive-foreground"
+ onClick={(e) => {
+ e.stopPropagation();
+ handleDeleteTag(tag.id);
+ }}
+ >
+ <TrashIcon className="mr-2 h-4 w-4" />
+ Delete tag
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ </>
+ );
+ })
+ ) : (
+ <TableRow>
+ <TableCell className="min-w-[100px]">
+ <Skeleton className="h-6 w-full" />
+ </TableCell>
+ <TableCell className="min-w-[450px]">
+ <Skeleton className="h-6 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-6 w-24" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-6 w-24" />
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ {/* Pagination Controls */}
+ <div className="mt-2 flex w-full items-center">
+ <div className="w-full text-sm">
+ {!loadingTags ? (
+ <>
+ Showing{" "}
+ <strong className="font-semibold">
+ {tagCount && tagCount > 10
+ ? availableTags?.length
+ : tagCount}
+ </strong>{" "}
+ of <strong>{tagCount}</strong> tags
+ </>
+ ) : (
+ "Getting Data from the server..."
+ )}
+ </div>
+ <Pagination className="justify-end">
+ <PaginationContent>
+ <PaginationItem>
+ <PaginationPrevious
+ onClick={() => setCurrentPage(currentPage - 1)}
+ disabled={currentPage === 1}
+ className="cursor-pointer"
+ />
+ </PaginationItem>
+ {currentPage !== 1 ? (
+ <PaginationItem className="cursor-pointer">
+ <PaginationLink onClick={() => setCurrentPage(1)}>
+ {1}
+ </PaginationLink>
+ </PaginationItem>
+ ) : null}
+
+ <PaginationItem>
+ <PaginationLink isActive>{currentPage}</PaginationLink>
+ </PaginationItem>
+
+ {tagCount && currentPage !== Math.ceil(tagCount / 10) ? (
+ <PaginationItem>
+ <PaginationLink
+ className="cursor-pointer"
+ onClick={() => setCurrentPage(Math.ceil(tagCount / 10))}
+ >
+ {Math.ceil(tagCount / 10)}
+ </PaginationLink>
+ </PaginationItem>
+ ) : null}
+ <PaginationItem>
+ <PaginationNext
+ className="cursor-pointer"
+ onClick={() => setCurrentPage(currentPage + 1)}
+ disabled={
+ tagCount ? currentPage === Math.ceil(tagCount / 10) : true
+ }
+ />
+ </PaginationItem>
+ </PaginationContent>
+ </Pagination>
+ </div>
+ </div>
+ </main>
+ </AppLayout>
+ );
+}
diff --git a/prisma/migrations/20250310130303_added_tags_model/migration.sql b/prisma/migrations/20250310130303_added_tags_model/migration.sql
new file mode 100644
index 00000000..7ca31ed4
--- /dev/null
+++ b/prisma/migrations/20250310130303_added_tags_model/migration.sql
@@ -0,0 +1,75 @@
+-- CreateEnum
+CREATE TYPE "TaggableItemType" AS ENUM ('LINK', 'DOCUMENT', 'DATAROOM');
+
+-- CreateTable
+CREATE TABLE "Tag" (
+ "id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "color" TEXT NOT NULL,
+ "description" TEXT,
+ "teamId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+ "createdBy" TEXT,
+
+ CONSTRAINT "Tag_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "TaggedItem" (
+ "id" TEXT NOT NULL,
+ "tagId" TEXT NOT NULL,
+ "itemType" "TaggableItemType" NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "taggedBy" TEXT,
+ "linkId" TEXT,
+ "documentId" TEXT,
+ "dataroomId" TEXT,
+
+ CONSTRAINT "TaggedItem_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "Tag_teamId_idx" ON "Tag"("teamId");
+
+-- CreateIndex
+CREATE INDEX "Tag_name_idx" ON "Tag"("name");
+
+-- CreateIndex
+CREATE INDEX "Tag_id_idx" ON "Tag"("id");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "Tag_teamId_name_key" ON "Tag"("teamId", "name");
+
+-- CreateIndex
+CREATE INDEX "TaggedItem_itemType_linkId_idx" ON "TaggedItem"("itemType", "linkId");
+
+-- CreateIndex
+CREATE INDEX "TaggedItem_itemType_documentId_idx" ON "TaggedItem"("itemType", "documentId");
+
+-- CreateIndex
+CREATE INDEX "TaggedItem_itemType_dataroomId_idx" ON "TaggedItem"("itemType", "dataroomId");
+
+-- CreateIndex
+CREATE INDEX "TaggedItem_tagId_linkId_idx" ON "TaggedItem"("tagId", "linkId");
+
+-- CreateIndex
+CREATE INDEX "TaggedItem_tagId_documentId_idx" ON "TaggedItem"("tagId", "documentId");
+
+-- CreateIndex
+CREATE INDEX "TaggedItem_tagId_dataroomId_idx" ON "TaggedItem"("tagId", "dataroomId");
+
+-- AddForeignKey
+ALTER TABLE "Tag" ADD CONSTRAINT "Tag_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "TaggedItem" ADD CONSTRAINT "TaggedItem_tagId_fkey" FOREIGN KEY ("tagId") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "TaggedItem" ADD CONSTRAINT "TaggedItem_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "Link"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "TaggedItem" ADD CONSTRAINT "TaggedItem_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "Document"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "TaggedItem" ADD CONSTRAINT "TaggedItem_dataroomId_fkey" FOREIGN KEY ("dataroomId") REFERENCES "Dataroom"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 6f92e41a..85655a1e 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -94,6 +94,7 @@ model Team {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
+ Tag Tag[]
}
model Brand {
@@ -163,7 +164,8 @@ model Document {
folderId String? // Optional Folder ID for documents in folders
folder Folder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
- datarooms DataroomDocument[] // Datarooms associated with this document
+ datarooms DataroomDocument[] // Datarooms associated with this document
+ taggedItems TaggedItem[]
@@index([ownerId])
@@index([teamId])
@@ -280,12 +282,62 @@ model Link {
team Team? @relation(fields: [teamId], references: [id], onDelete: Cascade)
customFields CustomField[]
+ taggedItems TaggedItem[]
@@unique([domainSlug, slug])
@@index([documentId])
@@index([teamId])
}
+enum TaggableItemType {
+ LINK
+ DOCUMENT
+ DATAROOM
+}
+
+model Tag {
+ id String @id @default(uuid())
+ name String
+ color String
+ description String?
+ teamId String
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ createdBy String?
+ taggedItems TaggedItem[]
+
+ @@unique([teamId, name])
+ @@index([teamId])
+ @@index([name])
+ @@index([id])
+}
+
+model TaggedItem {
+ id String @id @default(uuid())
+ tagId String
+ tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)
+ itemType TaggableItemType
+ createdAt DateTime @default(now())
+ taggedBy String?
+
+ linkId String?
+ link Link? @relation(fields: [linkId], references: [id], onDelete: Cascade)
+
+ documentId String?
+ document Document? @relation(fields: [documentId], references: [id])
+
+ dataroomId String?
+ dataroom Dataroom? @relation(fields: [dataroomId], references: [id])
+
+ @@index([itemType, linkId])
+ @@index([itemType, documentId])
+ @@index([itemType, dataroomId])
+ @@index([tagId, linkId])
+ @@index([tagId, documentId])
+ @@index([tagId, dataroomId])
+}
+
model LinkPreset {
id String @id @default(cuid())
name String
@@ -476,8 +528,9 @@ model Dataroom {
viewerGroups ViewerGroup[]
brand DataroomBrand?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ taggedItems TaggedItem[]
@@index([teamId])
}