Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add tag modal

Tim Wilsonda4f9b609c41
diff --git a/apps/web/app/api/projects/[slug]/tags/route.ts b/apps/web/app/api/projects/[slug]/tags/route.ts
index 1c8d18963c..74f57bc808 100644
--- a/apps/web/app/api/projects/[slug]/tags/route.ts
+++ b/apps/web/app/api/projects/[slug]/tags/route.ts
@@ -1,7 +1,7 @@
import { exceededLimitError } from "@/lib/api/errors";
import { withAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
-import { randomBadgeColor } from "@/ui/links/tag-badge";
+import { COLORS_LIST, randomBadgeColor } from "@/ui/links/tag-badge";
import { NextResponse } from "next/server";
// GET /api/projects/[slug]/tags - get all tags for a project
@@ -41,11 +41,14 @@ export const POST = withAuth(async ({ req, project, headers }) => {
},
);
}
- const { tag } = await req.json();
+ const { tag, color } = await req.json();
const response = await prisma.tag.create({
data: {
name: tag,
- color: randomBadgeColor(),
+ color:
+ color && COLORS_LIST.map(({ color }) => color).includes(color)
+ ? color
+ : randomBadgeColor(),
projectId: project.id,
},
});
diff --git a/apps/web/app/api/route.ts b/apps/web/app/api/route.ts
index be5e4a0d6a..8df23b0ced 100644
--- a/apps/web/app/api/route.ts
+++ b/apps/web/app/api/route.ts
@@ -1,3 +1,4 @@
+import { COLORS_LIST } from "@/ui/links/tag-badge";
import { NextResponse } from "next/server";
import { OpenAPIV3 } from "openapi-types";
@@ -672,7 +673,14 @@ export function GET(): NextResponse<OpenAPIV3.Document> {
type: "string",
description: "The name of the tag to create.",
},
+ color: {
+ type: "string",
+ enum: COLORS_LIST.map(({ color }) => color),
+ description:
+ "The color of the tag (random if not provided).",
+ },
},
+ required: ["tag"],
},
},
},
diff --git a/apps/web/ui/links/link-filters.tsx b/apps/web/ui/links/link-filters.tsx
index b4e96c3b91..02efee9468 100644
--- a/apps/web/ui/links/link-filters.tsx
+++ b/apps/web/ui/links/link-filters.tsx
@@ -34,6 +34,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { mutate } from "swr";
import { useDebouncedCallback } from "use-debounce";
+import { useAddEditTagModal } from "@/ui/modals/add-edit-tag-modal";
export default function LinkFilters() {
const { data: domains } = useLinksCount({ groupBy: "domain" });
@@ -276,6 +277,9 @@ const TagsFilter = ({
const [search, setSearch] = useState("");
const [showMore, setShowMore] = useState(false);
+ const { setShowAddEditTagModal, AddEditTagModal, AddEditTagButton } =
+ useAddEditTagModal();
+
const selectedTagIds =
searchParams?.get("tagId")?.split(",")?.filter(Boolean) ?? [];
@@ -315,6 +319,7 @@ const TagsFilter = ({
return (
<fieldset className="overflow-hidden py-6">
+ <AddEditTagModal />
<div className="flex h-8 items-center justify-between">
<button
onClick={() => {
@@ -327,6 +332,7 @@ const TagsFilter = ({
/>
<h4 className="font-medium text-gray-900">Tags</h4>
</button>
+ <AddEditTagButton />
</div>
<AnimatePresence initial={false}>
{!collapsed && (
diff --git a/apps/web/ui/modals/add-edit-tag-modal.tsx b/apps/web/ui/modals/add-edit-tag-modal.tsx
new file mode 100644
index 0000000000..b881e3855e
--- /dev/null
+++ b/apps/web/ui/modals/add-edit-tag-modal.tsx
@@ -0,0 +1,241 @@
+import {
+ Dispatch,
+ FormEvent,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+import va from "@vercel/analytics";
+import { mutate } from "swr";
+import useProject from "@/lib/swr/use-project";
+import useTags from "@/lib/swr/use-tags";
+import { TagProps } from "@/lib/types";
+import {
+ Button,
+ InfoTooltip,
+ Logo,
+ Modal,
+ TooltipContent,
+ useMediaQuery,
+ useRouterStuff,
+} from "@dub/ui";
+import { HOME_DOMAIN, capitalize, cn } from "@dub/utils";
+import { COLORS_LIST, randomBadgeColor } from "../links/tag-badge";
+import { toast } from "sonner";
+
+function AddEditTagButton({
+ setShowAddEditTagModal,
+}: {
+ setShowAddEditTagModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const { plan, tagsLimit } = useProject();
+ const { tags } = useTags();
+ const { queryParams } = useRouterStuff();
+
+ const exceededTags = tags && tagsLimit && tags.length >= tagsLimit;
+
+ return (
+ <div>
+ <Button
+ variant="secondary"
+ text="Add Tag"
+ className="h-8 px-2"
+ disabledTooltip={
+ exceededTags ? (
+ <TooltipContent
+ title={`You can only add up to ${tagsLimit} tag${
+ tagsLimit === 1 ? "" : "s"
+ } on the ${capitalize(plan)} plan. Upgrade to add more tags`}
+ cta="Upgrade"
+ onClick={() => {
+ queryParams({
+ set: {
+ upgrade: plan === "free" ? "pro" : "business",
+ },
+ });
+ }}
+ />
+ ) : undefined
+ }
+ onClick={() => setShowAddEditTagModal(true)}
+ />
+ </div>
+ );
+}
+
+export function useAddEditTagModal({ props }: { props?: TagProps } = {}) {
+ const [showAddEditTagModal, setShowAddEditTagModal] = useState(false);
+
+ const AddEditTagModalCallback = useCallback(() => {
+ return (
+ <AddEditTagModal
+ showAddEditTagModal={showAddEditTagModal}
+ setShowAddEditTagModal={setShowAddEditTagModal}
+ props={props}
+ />
+ );
+ }, [showAddEditTagModal, setShowAddEditTagModal]);
+
+ const AddEditTagButtonCallback = useCallback(() => {
+ return <AddEditTagButton setShowAddEditTagModal={setShowAddEditTagModal} />;
+ }, [setShowAddEditTagModal]);
+
+ return useMemo(
+ () => ({
+ setShowAddEditTagModal,
+ AddEditTagModal: AddEditTagModalCallback,
+ AddEditTagButton: AddEditTagButtonCallback,
+ }),
+ [setShowAddEditTagModal, AddEditTagModalCallback, AddEditTagButtonCallback],
+ );
+}
+
+function AddEditTagModal({
+ showAddEditTagModal,
+ setShowAddEditTagModal,
+ props,
+}: {
+ showAddEditTagModal: boolean;
+ setShowAddEditTagModal: Dispatch<SetStateAction<boolean>>;
+ props?: TagProps;
+}) {
+ const { slug: projectSlug } = useProject();
+
+ const [data, setData] = useState<TagProps>(
+ props || {
+ id: "",
+ name: "",
+ color: randomBadgeColor(),
+ },
+ );
+ const { id, name, color } = data;
+
+ const endpoint = useMemo(() => {
+ if (props) {
+ return {
+ method: "PUT",
+ url: `/api/tags/${id}`,
+ successMessage: "Successfully updated tag!",
+ };
+ } else {
+ return {
+ method: "POST",
+ url: `/api/tags`,
+ successMessage: "Successfully added tag!",
+ };
+ }
+ }, [id]);
+
+ const [saving, setSaving] = useState(false);
+
+ const { isMobile } = useMediaQuery();
+
+ return (
+ <Modal
+ showModal={showAddEditTagModal}
+ setShowModal={setShowAddEditTagModal}
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 sm:px-16">
+ <Logo />
+ <h3 className="text-lg font-medium">Create a new tag</h3>
+ <a
+ href={`${HOME_DOMAIN}/help/article/how-to-use-tags#what-is-a-tag`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="-translate-y-2 text-center text-xs text-gray-500 underline underline-offset-4 hover:text-gray-800"
+ >
+ What is a tag?
+ </a>
+ </div>
+
+ <form
+ onSubmit={async (e: FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+ setSaving(true);
+ fetch(endpoint.url, {
+ method: endpoint.method,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ tag: data.name,
+ color: data.color,
+ }),
+ }).then(async (res) => {
+ if (res.status === 200) {
+ // track tag creation event
+ va.track("Created Tag");
+ await mutate("/api/tags");
+ toast.success(endpoint.successMessage);
+ setShowAddEditTagModal(false);
+ } else {
+ toast.error(await res.text());
+ }
+ setSaving(false);
+ });
+ }}
+ className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16"
+ >
+ <div>
+ <label htmlFor="name" className="flex items-center space-x-2">
+ <p className="block text-sm font-medium text-gray-700">Tag Name</p>
+ </label>
+ <div className="mt-2 flex rounded-md shadow-sm">
+ <input
+ name="name"
+ id="name"
+ type="text"
+ required
+ autoFocus={!isMobile}
+ autoComplete="off"
+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ placeholder="New Tag"
+ value={name}
+ onChange={(e) => {
+ setData({ ...data, name: e.target.value });
+ }}
+ />
+ </div>
+ </div>
+
+ <div>
+ <label htmlFor="name" className="flex items-center space-x-2">
+ <p className="block text-sm font-medium text-gray-700">Tag Color</p>
+ <InfoTooltip content={`A color to make your tag stand out.`} />
+ </label>
+ <div className="mt-2 flex flex-wrap gap-3">
+ {COLORS_LIST.map(({ color: colorOption, css }) => (
+ <div key={colorOption}>
+ <label className="flex cursor-pointer items-center">
+ <input
+ type="radio"
+ name="color"
+ value={colorOption}
+ onChange={(e) => {
+ if (e.target.checked)
+ setData({ ...data, color: colorOption });
+ }}
+ className="peer pointer-events-none absolute opacity-0"
+ />
+ <span
+ aria-hidden="true"
+ className={cn(
+ css,
+ "whitespace-nowrap rounded-md px-2 py-0.5 text-sm capitalize ring-current peer-focus-visible:ring-offset-2",
+ color === colorOption && "ring-2",
+ )}
+ >
+ {colorOption}
+ </span>
+ </label>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <Button loading={saving} text="Create tag" />
+ </form>
+ </Modal>
+ );
+}
diff --git a/packages/ui/src/button.tsx b/packages/ui/src/button.tsx
index fbf7dc8569..d468d90e07 100644
--- a/packages/ui/src/button.tsx
+++ b/packages/ui/src/button.tsx
@@ -21,12 +21,18 @@ export function Button({
icon,
shortcut,
disabledTooltip,
+ className,
...props
}: ButtonProps) {
if (disabledTooltip) {
return (
<Tooltip content={disabledTooltip}>
- <div className="flex h-10 w-full cursor-not-allowed items-center justify-center space-x-2 rounded-md border border-gray-200 bg-gray-100 px-4 text-sm text-gray-400 transition-all focus:outline-none">
+ <div
+ className={cn(
+ "flex h-10 w-full cursor-not-allowed items-center justify-center space-x-2 rounded-md border border-gray-200 bg-gray-100 px-4 text-sm text-gray-400 transition-all focus:outline-none",
+ className,
+ )}
+ >
<p>{text}</p>
{shortcut && (
<kbd className="hidden rounded bg-zinc-200 px-2 py-0.5 text-xs font-light text-gray-400 md:inline-block">
@@ -57,7 +63,7 @@ export function Button({
"border-red-500 bg-red-500 text-white hover:bg-white hover:text-red-500":
variant === "danger",
},
- props.className,
+ className,
)}
disabled={props.disabled || loading}
{...props}